Core Java
Core Java........................................................................................................................................................................ 1
Introduction to java:............................................................................................................................................. 1
♦ Implementation of a Java application program........................................................................1
♦ Java Terminology................................................................................................................................... 3
♦ Primary/Main Features of Java........................................................................................................3
♦ JDK vs JRE.................................................................................................................................................. 6
♦ IMPORTANT POINTS OF JAVA..........................................................................................................7
Advantages of Java:...........................................................................................................................7
Disadvantages of Java:.....................................................................................................................8
Keywords, Identifiers, variables:....................................................................................................................8
♦ Keywords................................................................................................................................................... 8
Important Keywords in Java.........................................................................................................8
♦ final, finally and finalize in Java.....................................................................................................10
final keyword.................................................................................................................................... 10
finally keyword (try/catch & finally).....................................................................................10
finalize method................................................................................................................................ 10
♦ Identifiers................................................................................................................................................ 10
Rules for Identifiers in Java........................................................................................................11
♦ Variables.................................................................................................................................................. 12
Local Variable................................................................................................................................... 13
Instance Variable............................................................................................................................ 13
Static variable................................................................................................................................... 13
♦ Data Types.............................................................................................................................................. 13
Primitive datatype:........................................................................................................................ 14
Non-primitive datatype: (user defined)...............................................................................14
Operators:.............................................................................................................................................................. 14
♦ Arithmetic Operators......................................................................................................................... 15
♦ Java Assignment Operators.............................................................................................................15
♦ Java Comparison Operators............................................................................................................16
♦ Java Logical Operators.......................................................................................................................16
Method/Functions:............................................................................................................................................ 17
♦ Create/Call a Method......................................................................................................................... 17
Create a Method.............................................................................................................................. 17
Call a Method.................................................................................................................................... 18
♦ Method Parameters............................................................................................................................ 19
Parameters and Arguments.......................................................................................................19
Return Values................................................................................................................................... 19
♦ Naming a Method.................................................................................................................................20
Single-word method name: sum(), area()...........................................................................20
Multi-word method name: areaOfCircle(), stringComparision()..............................20
♦ Types of Method................................................................................................................................... 20
Predefined Method:....................................................................................................................... 20
User-defined Method:................................................................................................................... 21
Flow Control Statements:................................................................................................................................21
♦ Java for Loop vs while Loop vs do-while Loop.......................................................................23
♦ Types of control flow statements.................................................................................................24
♦ Decision-Making statements (Conditional statements):....................................................24
if statements......................................................................................................................................24
switch statement.............................................................................................................................26
♦ Loop Statements.................................................................................................................................. 27
for loop................................................................................................................................................ 27
for-each loop..................................................................................................................................... 28
while loop........................................................................................................................................... 28
do-while loop.................................................................................................................................... 29
♦ Jump statements.................................................................................................................................. 30
break statement.............................................................................................................................. 30
continue statement........................................................................................................................ 30
Arrays:..................................................................................................................................................................... 31
♦ Types of Array in java........................................................................................................................31
Single-Dimensional Array in Java............................................................................................32
Multi-Dimensional Arrays.......................................................................................................... 32
Strings:..................................................................................................................................................................... 33
♦ What is a String in Java?................................................................................................................... 33
♦ How to create a string object?........................................................................................................33
String Literal..................................................................................................................................... 33
By new keyword..............................................................................................................................33
♦ Interfaces and Classes in Strings in Java...................................................................................33
String.................................................................................................................................................... 33
CharBuffer.......................................................................................................................................... 34
♦ Java String class methods.................................................................................................................35
Java User Input (Scanner)/Dynamic Input:............................................................................................48
♦ Methods................................................................................................................................................... 49
Object-Oriented Programming System:........................................................................................................49
The principles of java:....................................................................................................................................... 49
Object Relationships In JAVA:....................................................................................................................... 50
Classes and Objects:........................................................................................................................................... 50
♦ Components of Java Classes............................................................................................................51
Java Objects:.......................................................................................................................................................... 52
♦ How to Create Object in Java.......................................................................................................... 52
Methods:........................................................................................................................................................ 52
1) Using new Keyword..................................................................................................................53
2) Using clone () Method..............................................................................................................54
3) Using newInstance() Method of Class class...................................................................55
4) Using newInstance() Method of Constructor class.....................................................56
5) Using Deserialization............................................................................................................... 57
Reference Variable:............................................................................................................................................ 59
Local and Global Variables:............................................................................................................................ 60
♦ Local Variable:.......................................................................................................................................60
Advantages of local variable:.....................................................................................................61
Disadvantages of local variable:...............................................................................................61
♦ Global Variable:.................................................................................................................................... 62
Advantages of global variable:..................................................................................................62
Disadvantages of global variable:............................................................................................63
♦ Comparison Between Global and Local Variable...................................................................63
Constructors:........................................................................................................................................................ 64
♦ What are Constructors in Java?.....................................................................................................64
♦ Rules for Creating Java Constructor:...........................................................................................65
♦ Types of constructors in Java:........................................................................................................65
1) Java Default Constructor............................................................................................................. 65
2) Java Parameterized Constructor..............................................................................................66
♦ Constructor Overloading in Java...................................................................................................67
♦ Difference Between Constructor and Method in Java.........................................................68
Aggregation and Composition.......................................................................................................................69
Inheritance:........................................................................................................................................................... 70
♦ What is Inheritance?.......................................................................................................................... 70
♦ Why Do We Need Java Inheritance?............................................................................................70
♦ Terms used in Inheritance...............................................................................................................71
♦ The syntax of Java Inheritance...................................................................................................... 71
♦ Java Inheritance Types......................................................................................................................71
1. Single level Inheritance...................................................................................................................... 72
2. Multilevel Inheritance / Chaining inheritance.........................................................................73
3. Hierarchical Inheritance.................................................................................................................... 75
4. Multiple Inheritance (Through Interfaces)...............................................................................77
5. Hybrid Inheritance............................................................................................................................... 77
♦ Java IS-A type of Relationship........................................................................................................78
♦ Advantages and Disadvantages of Inheritance......................................................................79
Advantages Of Inheritance in Java:.........................................................................................79
Disadvantages of Inheritance in Java:....................................................................................79
Method Overloading and Method Overriding:.......................................................................................79
Java Method Overloading............................................................................................................................79
Java Method Overriding.............................................................................................................................. 79
Abstract Class....................................................................................................................................................... 81
Interface in Java................................................................................................................................................... 81
Casting: UP and Down...................................................................................................................................... 81
Polymorphism:.................................................................................................................................................... 81
Types of Java Polymorphism.....................................................................................................................82
1. Compile-Time Polymorphism......................................................................................................... 82
Subtypes of Compile-time Polymorphism:................................................................................82
2. Runtime Polymorphism..................................................................................................................... 83
Subtype of Run-Time Polymorphism...........................................................................................83
Advantages and Disadvantages of Polymorphism..........................................................................83
Advantages of Polymorphism.............................................................................................................. 83
Disadvantages of Polymorphism........................................................................................................ 83
Abstraction:........................................................................................................................................................... 84
Abstraction Real-Life Example:................................................................................................................84
Advantages and Disadvantages of Abstraction.................................................................................84
Advantages of Abstraction.....................................................................................................................84
Disadvantages of Abstraction...............................................................................................................84
Encapsulation....................................................................................................................................................... 85
Advantages and disadvantages of Encapsulation............................................................................85
Advantages of Encapsulation............................................................................................................... 85
Disadvantages of Encapsulation in Java..........................................................................................86
Java packages........................................................................................................................................................ 86
Advantage of Java Package.........................................................................................................................86
Access Modifiers.................................................................................................................................................. 87
There are four types of Java access modifiers:..................................................................................87
Introduction to java:
Java is a class-based, object-oriented programming language that is
designed to have as few implementation dependencies as possible.
Java was originally developed by James Gosling (Father of java) at Sun
Microsystems (which has since been acquired by Oracle) and released in 1995.
Java is known for its simplicity, robustness, and security features, which
makes it a popular choice for developing applications.
Java makes writing, compiling, and debugging programming easy. It helps to
create reusable code and modular programs.
It is a general-purpose programming language planned to let application
developers to write once run anywhere that is compiled Java code can run on
all platforms that support Java.
Java applications are compiled to byte code that can run on any Java Virtual
Machine (JVM).
The principles for java: - simple, robust, secured, high-performance, portable,
multi-threaded, interpreted, dynamic, etc.
Types of Java:
JSE (Java Standard Edition)/ Core JAVA, J2EE (JAVA Enterprise
Edition)/Advanced JAVA, JMW (JAVA Micro Edition) for Android
♦ Implementation of a Java application program
1. Creating the program
2. Compiling the program
3. Running the program
Before creating the program, the Java Development Kit (JDK) must be properly
installed on our system and a path will be set.
• Creating Program / Coding
class Test {
public static void main (String []args) {}
};
• Compiling the program
To compile the program, we must run the Java compiler (javac) which is a
primary Java compiler included in the Java development kit (JDK). It takes the
Java program as input and generates bytecode as output.
• Running the program / Execution
We need to use the Java Interpreter to run a program. JVM executes the
bytecode generated by the compiler.
Java interpreter is a computer program (system software) that implements the
JVM. It is responsible for reading and executing the program. It is designed in such
a way that it can read the source program and translate the source code instruction
by instruction. It converts the high-level program into machine language.
Interpreter Compiler
It translates the code instruction by It translates the entire program at once.
instruction.
Its execution is slower. Its execution is faster.
Its compile time is less. It takes more time to compile the code.
It does not generate the intermediate object It generates the intermediate object
code. code.
It compiles the program until an error is All the errors show once at the end of
found. the compilation.
Python, PHP, Ruby, and Perl use an Java, C++, Scala, and C use a compiler.
interpreter.
♦ Java Terminology
1. Java Virtual Machine (JVM):
This is generally called JVM. There are three execution phases of a program. They
are write, compile and run the program.
2. Bytecode in the Development Process:
The Javac compiler of JDK compiles the java source code into bytecode so that it
can be executed by JVM. It is saved as *.class file by the compiler.
3. Java Development Kit (JDK):
we need to install JDK on our computer to create, compile and run the java
program.
4. Java Runtime Environment (JRE):
For running the java program, a computer needs JRE.
5. Garbage Collector
6. ClassPath:
The classpath is the file path where the java runtime and Java compiler look for
.class files to load. By default, JDK provides many libraries. If you want to include
external libraries, they should be added to the classpath.
♦ Primary/Main Features of Java
1. Platform Independent:
The compiler converts source code to bytecode and then the JVM executes the
bytecode generated by the compiler. This bytecode can run on any platform be it
Windows, Linux, or macOS which means if we compile a program on Windows,
then we can run it on Linux and vice versa. Each operating system has a different
JVM, but the output produced by all the OS is the same after the execution of the
bytecode. That is why we call java a platform-independent language.
2. Object-Oriented Programming Language:
Object-oriented programming (OOP) is a programming standard based on the
concept of "objects", which can contain data and methods.
The four main concepts of Object-Oriented programming are:
Abstraction
Encapsulation
Inheritance
Polymorphism
3. Simple:
Java is one of the simple languages as it does not have complex features like
pointers, operator overloading, multiple inheritances, and Explicit memory
allocation. Java syntax is easy to write and maintain.
4. Robust:
Java language is robust which means reliable. It is developed so that it puts a lot of
effort into checking errors as early as possible, that is why the java compiler can
detect even errors that are not easy to detect by another programming language.
The main features of java that make it robust are garbage collection, Exception
Handling, and memory allocation.
5. Secure:
In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e. it
shows ArrayIndexOutOfBound Exception if we try to do so. Java programs run in
an environment that is independent of the os(operating system) environment which
makes java programs more secure.
6. Distributed:
We can create distributed applications using the java programming language.
Remote Method Invocation used for creating distributed applications in java. The
java programs can be easily distributed on one or more systems connected through
an internet connection.
7. Multithreading:
Java supports multithreading. It is a Java feature that allows concurrent execution
of two or more parts of a program for maximum utilization of the CPU.
8. Portable:
As we know, java code written on one machine can be run on another machine.
The platform-independent feature of java in which its platform-independent
bytecode can be taken to any platform for execution makes java portable.
9. High Performance:
Java architecture is defined in such a way that it reduces overhead during the
runtime and at sometimes java uses Just In Time (JIT) compiler where the
compiler compiles code on-demand basics where it only compiles those methods
that are called to execute faster.
10. Dynamic flexibility:
Java being completely object-oriented gives us the flexibility to add classes, new
methods to existing classes, and even create new classes through sub-classes
(Extends). Java even supports functions written in other languages such as C, C++
which are referred to as native methods.
11. Sandbox Execution:
Java programs run in a separate space that allows users to execute their
applications without affecting the underlying system with the help of a bytecode
verifier.
12. Write Once Run Anywhere:
Java application generates a ‘.class’ file that corresponds to our program but
contains code in binary format. Bytecode is not dependent on any machine
architecture. It is the primary reason java is used in the enterprising IT industry
globally worldwide.
13. Power of compilation and interpretation:
Most languages are designed for either compiled or interpreted language. But java
integrates power as Java compiler compiles the source code to bytecode and JVM
executes this bytecode to machine OS-dependent executable code.
class: class keyword is used to declare classes in Java
public: It is an access specifier. Public means this function is visible in the whole
project.
static: static is a keyword used to make a function static. To execute a static
function, we do not have to create an Object of the class.
The main () method here is called JVM, without creating any object for class.
void: It is the return type, meaning this function will not return anything.
main: This is the method, which is executed, hence all the logic must be inside the
main () method. If a java class does not have a main () method, it causes
compilation error.
String[] args: This is used to specify that the user may opt to enter parameters to
the Java Program at command line. We can use both String [] args or String args[].
Java compiler would accept both forms.
[Link] : This is used to print anything on the console like “printf” in
C language.
Scanner: Scanner scan = new Scanner ([Link]);
[Link]("Enter the First No:");
a = [Link]();
Comments:
// Single line comment
/* Multi line comments*/
♦ JDK vs JRE
Aspect JDK JRE JVM
Purpose Used to develop Java Used to run Java Responsible for
applications applications running Java code
Platform
Platform-dependent Platform-dependent Platform-Independent
Dependency
Includes It runs the java byte
It includes It includes libraries to
code and make java
development tools run Java application +
application to work
like (compiler) + JRE JVM
on any platform.
Use Case Running a Java
Writing and Convert bytecode into
application on a
compiling Java code native machine code
system
♦ IMPORTANT POINTS OF JAVA
Here are some important points about Java:
1. Java is a high-level, object-oriented programming language that was first
released in 1995.
2. Java is platform-independent, which means that code written in Java can run on
any platform that has a Java Virtual Machine (JVM) installed.
3. Java code is compiled into bytecode, which can then be executed by the JVM.
4. Java is known for its “write once, run anywhere” philosophy, which makes it a
popular choice for cross-platform development.
5. Java provides automatic memory management through garbage collection,
which makes it easier to write and maintain code.
6. Java has a vast standard library that provides a wide range of tools for common
programming tasks.
7. Java is widely used in enterprise applications, web development, and Android
app development.
8. Java is a strongly typed language, which means that every variable and
expression has a specific type that must be declared before use.
9. Java has a robust exception-handling mechanism that makes it easier to handle
errors and unexpected behavior in code.
[Link] supports multithreading, which makes it possible to write programs that
can perform multiple tasks simultaneously.
Advantages of Java:
1. Platform independent: Java code can run on any platform that has a Java
Virtual Machine (JVM) installed, which means that applications can be written
once and run on any device.
2. Object-Oriented: Java is an object-oriented programming language, which
means that it follows the principles of abstraction, encapsulation, inheritance,
and polymorphism.
3. Security: Java has built-in security features that make it a secure platform for
developing applications, such as automatic memory management and type
checking.
4. Large community: Java has a large and active community of developers,
which means that there is a lot of support available for learning and using the
language.
5. Enterprise-level applications: Java is widely used for developing enterprise-
level applications, such as web applications, e-commerce systems, and database
systems.
Disadvantages of Java:
1. Performance: Java can be slower compared to other programming languages,
such as C++, due to its use of a virtual machine and automatic memory
management.
2. Memory management: Java’s automatic memory management can lead to
slower performance and increased memory usage, which can be a drawback for
some applications.
Keywords, Identifiers, variables:
♦ Keywords
Keywords are nothing but reserved words (predefined) in Java having special
meanings. These words are not allowed to be used as variable names or object
names (Method name and class name).
There are 68 Keywords in Java.
Important Keywords in Java
Keywords refer to the reserved set of words of a language. These are used for some
predefined actions.
[Link]: It is a non-access modifier applicable for classes and methods. It is used
to achieve abstraction.
[Link]: It is used to define Enum in Java
[Link]: It is used to know whether the object is an instance of the specified
type (class or subclass or interface).
[Link]: It is an access modifier. Anything declared private can’t be accessed
from other classes. The scope of the private element remains only within the class
declared.
[Link]: The scope of the protected element remains only within the package
declared. The class which is outside the package can access it by one condition. I.e.
Inheritance operation.
[Link]: Anything declared public can be accessed from anywhere. The scope of
the public element remains throughout the project.
[Link]: It is used to create a member (block, method, variable, nested classes) that
can be used by itself, without reference to a specific instance.
[Link]: It is used for restricting floating-point calculations and ensuring the same
result on every platform while performing operations in the floating-point variable.
[Link]: Applicable for blocks methods. It is used to get synchronization in
java. [Link]: transient is a variables modifier used in serialization. At the time
of serialization, if we don’t want to save the value of a particular variable in a file,
then we use the transient keyword.
[Link]: The volatile modifier tells the compiler that the variable modified by
volatile can be changed unexpectedly by other parts of your program.
[Link]: this keyword is used to access global variables from the same class.
[Link]: super keyword is used to access global variable from super class.
[Link]: The final method in Java is used as a non-access modifier applicable only
to a variable, a method, or a class. It is used to restrict a user in Java.
The following are different contexts where the final is used:
Variable
Method
Class
♦ final, finally and finalize in Java
final keyword
final (lowercase) is a reserved keyword in java. We can’t use it as an identifier, as
it is reserved. We can use this keyword with variables, methods, and classes. The
final keyword in java has a different meaning depending upon whether it is applied
to a variable, class, or method.
finally keyword (try/catch & finally)
Just as final is a reserved keyword, so in the same way finally is also a reserved
keyword in java i.e., we can’t use it as an identifier. The finally keyword is used in
association with a try/catch block and guarantees that a section of code will be
executed, even if an exception is thrown. The finally block will be executed after
the try and catch blocks. finally is executed even if try block has return statement.
finalize method
It is a method that the Garbage Collector always calls just before the
deletion/destroying of the object, which is eligible for Garbage Collection, to
perform clean-up activity. Clean-up activity means closing the resources associated
with that object like Database Connection, Network Connection, or we can say
resource de-allocation. Remember, it is not a reserved keyword. Once the finalized
method completes immediately Garbage Collector destroys that object. finalize
method is present in the Object class and its syntax is:
protected void finalize throws Throwable {}
♦ Identifiers
Identifiers are user defined words. All Java variables, methods, classes must be
identified with unique names. These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum,
total Volume).
They can be a class name, variable name, method name, package name, constant
name, and more. However, In Java, there are some reserved words that cannot be
used as an identifier.
public class HelloJava {
public static void main(String[] args) {
[Link]("Hello JavaTpoint");
}
}
From the above example, we have the following Java identifiers:
1. HelloJava (Class name)
2. main (main method)
3. String (Predefined Class name)
4. args (String variables)
5. System (Predefined class)
6. out (Variable name)
7. println (method)
Rules for Identifiers in Java
There are some rules and conventions for declaring the identifiers in Java. If the
identifiers are not properly declared, we may get a compile-time error. Following
are some rules and conventions for declaring identifiers:
Names must begin with a letter
Names should start with a lowercase letter, and cannot contain whitespace
Names can also begin with $ and _.
A valid identifier must have characters [A-Z] or [a-z] or numbers [0-9], and
underscore (_) or a dollar sign ($). for example, @javatpoint is not a valid
identifier because it contains a special character which is @.
There should not be any space in an identifier.
For example, java tpoint is an invalid identifier. (java_tpoint)
An identifier should not contain a number at the start.
For example, 123javatpoint is an invalid identifier.
An identifier should be of length 4-15 letters only. However, there is no limit to
its length. But it is good to follow the standard conventions.
Names are case-sensitive ("myVar" and "myvar" are different variables)
We can't use the Java reserved keywords as an identifier such as int, float,
double, char, etc. For example, int double is an invalid identifier in Java.
An identifier should not be any query language keywords such as SELECT,
FROM, COUNT, DELETE, etc.
♦ Variables
♦ Variables are nothing but a piece of memory used to store information /
program data.
♦ One variable can store 1 piece of information at a time.
♦ We can create multiple variables with the help of appropriate datatype.
♦ We can create temporary variables.
♦ Variables are also used in information reusability.
To utilize variables in java programing language we need to follow below steps:
1. Variable declaration (Allocating/Reserving memory) => money;
2. Variable Initialization (Assigning or Inserting value) => money=1L;
3. Usage (Printing/ or any other operations) => syso(money)
A variable is assigned with a data type.
There are two types of data types in Java: primitive and non-primitive.
A variable is the 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
Local Variable
A variable declared inside the body of the method is called local variable. The
scope of the variable remains only within that method. We can declare multiple
local variables in different method bodies.
A local variable cannot be defined with "static" keyword.
Instance Variable
A variable declared inside the class but outside the method's body is called an
instance variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not
shared among instances.
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.
♦ Data Types
Data types are used to represent the type of data or information which we are going
to use in our java program. We can store different types of data by specifying data
type.
In java programming it is mandatory to declare data type before declaration of
variable.
In java datatypes are classified into two types:
1. Primitive datatype --> language
2. Non-primitive datatype--> user defined data types
Primitive datatype:
The datatype which is declared as a keyword is known as primitive datatype.
There are 8 types of primitive datatypes. All the primitive datatypes are keywords.
keyword starts with lower case
1.(Numeric + non-decimal): -
Data Type Size
1. byte 1 byte / 8 bit
2. short 2 bytes
3. int 4 bytes
4. long 8 bytes
2.(Numeric + decimal): -
5. float 4 byte
6. double 8 byte
[Link]: -
7. char 2 byte
[Link]: -
8. boolean 1 bit
Non-primitive datatype: (user defined)
There are 2 types of non-primitive datatypes.
Non primitive datatypes are identifiers.
Memory size of non-primitive datatype is not fixed.
The Identifier starts with capital letters.
e.g. String, Class
Operators:
Operators are used to perform operations on variables and values.
Java divides the operators into the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
♦ Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
♦ Java Assignment Operators
Assignment operators are used to assign values to variables.
♦ Java Comparison Operators
Comparison operators are used to compare two values (or variables). This is
important in programming, because it helps us to find answers and make decisions.
The return value of a comparison is either true or false. These values are known as
Boolean values.
♦ Java Logical Operators
You can also test for true or false values with logical operators.
Method/Functions:
Method is collection of executable java statements.
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Why use methods?
=> To reuse code: define the code once and use it many times.
♦ Create/Call a Method
Create a Method
A method must be declared within a class. It is defined with the name of the
method, followed by parentheses (). Java provides some pre-defined methods, such
as [Link](), but you can also create your own methods to perform
certain actions:
public class Main {
static void myMethod() {
// code to be executed
}
}
Example Explained
myMethod() is the name of the method
Static means that the method belongs to the Main class and not an object of the
Main class.
void means that this method does not have a return value.
Call a Method
To call a method in Java, write the method's name followed by two parentheses ()
and a semicolon;
Inside main, call the myMethod() method:
public class Main {
static void myMethod() {
[Link]("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}
}
// Outputs "I just got executed!"
A method can also be called multiple times.
To call static method form same class:-
Call with only method name
Mymethod();
To call static method form another/diff class:-
[Link];
♦ Method Parameters
Parameters and Arguments
Information can be passed to methods as a parameter. Parameters act as variables
inside the method.
Parameters are specified after the method name, inside the parentheses (). You can
add as many parameters as you want, just separate them with a comma.
The following example has a method that takes a String called fname as a
parameter. When the method is called, we pass along a first name, which is used
inside the method to print the full name:
public class Main {
static void myMethod(String fname) {
[Link](fname + " Refsnes");
}
public static void main(String[] args) {
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
Return Values
Return type represents type of information which method is going to return. we
used the void keyword in all examples, which indicates that the method should not
return a value.
If you want the method to return a value, you can use a primitive data type (such as
int, char, etc.) instead of void, and use the return keyword inside the method:
public class Main {
static String myMethod(String str) {
return "A" + str;
}
public static void main(String[] args) {
[Link](myMethod("BC"));
}
}
♦ Naming a Method
While defining a method, remember that the method name must be a verb and start
with a lowercase letter. If the method name has more than two words, the first
name must be a verb followed by adjective or noun. In the multi-word method
name, the first letter of each word must be in uppercase except the first word. For
example:
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()
It is also possible that a method has the same name as another method name in the
same class, it is known as method overloading.
♦ Types of Method
There are two types of methods in Java:
Predefined Method:
In Java, predefined methods are the methods that are already defined in the Java
class libraries. It is also known as the 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 length (), equals (), compareTo (), sqrt
(), main etc. When we call any of the predefined methods in our program, a series
of codes related to the corresponding method runs in the background that is already
stored in the library.
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.
import [Link];
public class EvenOdd {
public static void main (String args[]) {
//creating Scanner class object
Scanner scan=new Scanner([Link]);
[Link]("Enter the number: ");
int num=[Link]();
findEvenOdd(num);
Flow Control Statements:
Types of Control Flow statements
Control Flow Control Description
Statements Flow
Type Statement
Conditional Executes a block of code if a specified condition
if-else
Statements is true, and another block if the condition is false.
switch-case Evaluates a variable or expression and executes
code based on matching cases.
Executes a block of code a specified number of
for
times, typically iterating over a range of values.
Looping Executes a code block if a specified condition is
while
Statements true.
Executes a block of code once and repeats it if a
do-while
specified condition is true.
Terminates the loop or switch statement and
break transfers control to the statement immediately
following the loop or switch.
Skips the current iteration of a loop and continues
continue
with the next iteration.
Jump
Statements
return Exits a function and returns a value to the caller.
Transfers control to a labeled statement within
the same function. (Note: goto is generally
goto
discouraged due to its potential for creating
unreadable and error-prone code.)
♦ Java for Loop vs while Loop vs do-while Loop
Compa for loop while loop do-while loop
rison
Introduc The Java for loop is The Java while loop The Java do while
tion control flow is a control flow loop is a control flow
statement that iterates statement that statement that
a part of the programs executes a part of executes a part of the
multiple times. the programs programs at least once
repeatedly on the and the further
basis of given execution depends
boolean condition. upon the given
boolean condition.
When to If the number of If the number of If the number of
use iteration is fixed, it is iteration is not iteration is not fixed
recommended to use fixed, it is and you must have to
for loop. recommended to use execute the loop at
while loop. least once, it is
recommended to use
the do-while loop.
Syntax for(init;condition;incr while(condition){ do{
/decr){ //code to be //code to be executed
// code to be executed executed }while(condition);
} }
Example //for loop //while loop //do-while loop
for(int i=1;i<=10;i++) int i=1; int i=1;
{ while(i<=10){ do{
[Link](i); [Link](i [Link](i);
} ); i++;
i++; }while(i<=10);
}
Syntax for(;;){ while(true){ do{
for //code to be executed //code to be //code to be executed
infinitiv } executed }while(true);
e loop }
♦ Types of control flow statements.
1. Decision Making statements
a. if statements
b. switch statement
2. Loop statements
a. for loop
b. for-each loop
c. while loop
d. do while loop
3. Jump statements
a. break statement
b. continue statement
♦ Decision-Making statements (Conditional statements):
if statements
In Java, the "if" statement is used to evaluate a condition. The control of the
program is diverted depending upon the specific condition. The condition of the If
statement gives a Boolean value, either true or false. In Java, there are four types of
if-statements given below.
Simple if statement
if-else statement
if-else-if ladder
Nested if-statement
1) Simple 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 be true.
Syntax:
if(condition) {
statement 1; //executes when condition is true
2) 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.
Syntax:
if (condition) {
statement 1; //executes when condition is true
} else {
statement 2; //executes when condition is false
3) if-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
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
}
}
switch statement
In Java, Switch statements are like 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:
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. The execution of the set of instructions
depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are
differences in their syntax and condition checking time.
for loop
For-each loop
while loop
do-while loop
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.
Syntrax:
int sum = 0;
for (int j = 1; j<=10; j++) {
sum = sum + j;
[Link]("The sum of first 10 natural numbers is " + sum);
for-each loop
Java provides an enhanced loop to traverse the data structures like array or
collection. In the for-each loop, we don't need to update the loop variable.
Syntrax:
String [] names = {"Java","C","C++","Python","JavaScript"};
[Link]("Printing the content of the array names:\n");
for (String name: names) {
[Link](name);
while 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. Unlike for loop, the initialization and increment/decrement
doesn't take place inside the loop statement in 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.
Syntrax:
int i = 0;
[Link]("Printing the list of first 10 even numbers \n");
while(i<=10) {
[Link](i);
i = i + 2;
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 iteration 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 checked in the
end.
Syntax:
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, i.e.,
break and continue.
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 (inner)
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.
Syntax:
for(int i = 0; i<= 10; i++) {
[Link](i);
if(i==6) {
break;
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.
Syntax:
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++) {
if(j == 4) {
continue;
}
[Link](j);
Arrays:
An array is typically a grouping of elements of the same kind that are stored in a
single, contiguous block of memory.
A Java array is an object which contains elements of a similar data type. We can
store only a fixed set of elements in a Java array.
For primitive arrays, elements are stored in a contiguous memory location.
For non-primitive arrays, references are stored at contiguous locations, but the
actual objects may be at different locations in memory.
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.
♦ Types of Array in java
There are two types of array.
Single Dimensional Array
Multidimensional Array
Single-Dimensional Array in Java
A single-dimensional array in Java is a linear collection of elements of the same
data type. It is declared and instantiated using the following syntax:
Declare
Initialize
Access
Syntax:
//Array Declaration
int [] numbers;
// Create an Array
numbers = new int [5];
// Access an Element of an Array
// Setting the first element of the array
numbers[0] = 10;
int firstElement = numbers[0];
// Change an Array Element
numbers[0] = 20;
// Array Length
int length = [Link];
Multi-Dimensional Arrays
Arrays with more than one dimension, such as two-dimensional arrays (matrices).
Syntax:
// A 2D array (matrix)
int[][] multiDimArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
Strings:
♦ What is a String in Java?
A string is basically an object that represents a sequence of char values. 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.
The [Link] class implements Serializable, Comparable and Char
Sequence interfaces.
♦ How to create a string object?
There are two ways to create String object:
1. By string literal
2. By new keyword
String Literal
Java String literal is created by using double quotes. For Example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
By new keyword
String s=new String("Welcome"); //creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap
memory, and the literal "Welcome" will be placed in the string constant pool.
♦ Interfaces and Classes in Strings in Java
In Java, both String and CharBuffer interact with sequences of characters, but
they are designed with different use cases and underlying mechanisms in mind.
String
The String class is one of the most fundamental types in Java, designed to
represent immutable sequences of characters. Here's a characteristic and the
interfaces it implements:
Immutability: An immutable object is an object whose state cannot be
modified after it is created. In Java, this concept applies to strings, which means
that once a string object is created, its content cannot be changed. If we try to
change a string, a new string object is created instead.
String Pool: Java maintains a pool of string literals to help save memory. When
a new string literal is created, Java checks the Pool for a matching string. If
found, the new variable references the pooled string. If not, the new string is
added to the Pool.
Implemented Interfaces: The String class implements several interfaces,
including:
o Serializable: Allows string objects to be serialized into byte streams,
facilitating their transmission or storage.
o Comparable<String>: Enables grammatical comparison between two
strings, supporting natural ordering within collections.
o CharSequence: Provides a unified read-only interface for different kinds
of char sequences, allowing String objects to be manipulated and
accessed generically.
CharBuffer
CharBuffer, is a part of the [Link] package, which provides a set of classes for
non-blocking I/O operations. CharBuffer is a mutable sequence of characters with
more flexibility for manipulation. Here's more about CharBuffer:
Mutability and Direct Buffers: Unlike strings, CharBuffer instances can be
modified. They can be either heap-based or direct buffers. Direct buffers can
offer higher performance, especially for I/O operations, as they are managed
outside the Java heap and interact directly with the operating system's native
I/O operations.
Usage Scenarios: It is particularly useful for reading and writing to channels,
regular expressions, and character processing in a more efficient manner,
especially when dealing with large datasets or requiring fine-grained control
over character data.
♦ Java String class methods
Modifier and Method and Description
Type
char charAt(int index)
Returns the char value at the specified index.
int codePointAt(int index)
Returns the character (Unicode code point) at the specified
index.
int codePointBefore(int index)
Returns the character (Unicode code point) before the
specified index.
int codePointCount(int beginIndex, int endIndex)
Returns the number of Unicode code points in the
specified text range of this String.
int compareTo(String anotherString)
Compares two strings lexicographically.
int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case
differences.
String concat(String str)
Concatenates the specified string to the end of this string.
boolean contains(CharSequence s)
Returns true if and only if this string contains the specified
sequence of char values.
boolean contentEquals(CharSequence cs)
Compares this string to the specified CharSequence.
boolean contentEquals(StringBuffer sb)
Compares this string to the specified StringBuffer.
static String copyValueOf(char[] data)
Equivalent to valueOf(char[]).
static String copyValueOf(char[] data, int offset, int count)
Equivalent to valueOf(char[], int, int).
boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.
boolean equals(Object anObject)
Compares this string to the specified object.
boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case
considerations.
static String format(Locale l, String format, Object... args)
Returns a formatted string using the specified locale,
format string, and arguments.
static String format(String format, Object... args)
Returns a formatted string using the specified format string
and arguments.
byte[] getBytes()
Encodes this String into a sequence of bytes using the
platform's default charset, storing the result into a new byte
array.
byte[] getBytes(Charset charset)
Encodes this String into a sequence of bytes using the
given charset, storing the result into a new byte array.
void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)
Deprecated.
This method does not properly convert characters into
bytes. As of JDK 1.1, the preferred way to do this is via
the getBytes() method, which uses the platform's default
charset.
byte[] getBytes(String charsetName)
Encodes this String into a sequence of bytes using the
named charset, storing the result into a new byte array.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination
character array.
int hashCode()
Returns a hash code for this string.
int indexOf(int ch)
Returns the index within this string of the first occurrence
of the specified character.
int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence
of the specified character, starting the search at the
specified index.
int indexOf(String str)
Returns the index within this string of the first occurrence
of the specified substring.
int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence
of the specified substring, starting at the specified index.
String intern()
Returns a canonical representation for the string object.
boolean isEmpty()
Returns true if, and only if, length() is 0.
static String join(CharSequence delimiter, CharSequence... elements)
Returns a new String composed of copies of the
CharSequence elements joined together with a copy of the
specified delimiter.
static String join(CharSequence delimiter, Iterable<? extends
CharSequence> elements)
Returns a new String composed of copies of the
CharSequence elements joined together with a copy of the
specified delimiter.
int lastIndexOf(int ch)
Returns the index within this string of the last occurrence
of the specified character.
int lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence
of the specified character, searching backward starting at
the specified index.
int lastIndexOf(String str)
Returns the index within this string of the last occurrence
of the specified substring.
int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence
of the specified substring, searching backward starting at
the specified index.
int length()
Returns the length of this string.
boolean matches(String regex)
Tells whether or not this string matches the given regular
expression.
int offsetByCodePoints(int index, int codePointOffset)
Returns the index within this String that is offset from the
given index by codePointOffset code points.
boolean regionMatches(boolean ignoreCase, int toffset, String
other, int ooffset, int len)
Tests if two string regions are equal.
boolean regionMatches(int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
String replace(char oldChar, char newChar)
Returns a string resulting from replacing all occurrences of
oldChar in this string with newChar.
String replace(CharSequence target, CharSequence
replacement)
Replaces each substring of this string that matches the
literal target sequence with the specified literal
replacement sequence.
String replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the
given regular expression with the given replacement.
String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the
given regular expression with the given replacement.
String[] split(String regex)
Splits this string around matches of the given regular
expression.
String[] split(String regex, int limit)
Splits this string around matches of the given regular
expression.
boolean startsWith(String prefix)
Tests if this string starts with the specified prefix.
boolean startsWith(String prefix, int toffset)
Tests if the substring of this string beginning at the
specified index starts with the specified prefix.
CharSequence subSequence(int beginIndex, int endIndex)
Returns a character sequence that is a subsequence of this
sequence.
String substring(int beginIndex)
Returns a string that is a substring of this string.
String substring(int beginIndex, int endIndex)
Returns a string that is a substring of this string.
char[] toCharArray()
Converts this string to a new character array.
String toLowerCase()
Converts all of the characters in this String to lower case
using the rules of the default locale.
String toLowerCase(Locale locale)
Converts all of the characters in this String to lower case
using the rules of the given Locale.
String toString()
This object (which is already a string!) is itself returned.
String toUpperCase()
Converts all of the characters in this String to upper case
using the rules of the default locale.
String toUpperCase(Locale locale)
Converts all of the characters in this String to upper case
using the rules of the given Locale.
String trim()
Returns a string whose value is this string, with any
leading and trailing whitespace removed.
static String valueOf(boolean b)
Returns the string representation of the boolean argument.
static String valueOf(char c)
Returns the string representation of the char argument.
static String valueOf(char[] data)
Returns the string representation of the char array
argument.
static String valueOf(char[] data, int offset, int count)
Returns the string representation of a specific subarray of
the char array argument.
static String valueOf(double d)
Returns the string representation of the double argument.
static String valueOf(float f)
Returns the string representation of the float argument.
static String valueOf(int i)
Returns the string representation of the int argument.
static String valueOf(long l)
Returns the string representation of the long argument.
static String valueOf(Object obj)
Returns the string representation of the Object argument.
Java User Input (Scanner)/Dynamic Input:
The Scanner class is an internal class used to get input from end user. The Scanner
class is used to get user input of the primitive types like int, double, etc. and
strings, and it is found in the [Link] package.
Mostly it is used for desktop applications.
import [Link]; // Import the Scanner class
class Main {
public static void main(String[] args) {
Scanner sc= new Scanner([Link]); // Create a Scanner object
[Link]("Enter username");
String userName = [Link](); // Read user input
[Link]("Username is: " + userName); // Output user input
}
}
♦ Methods
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine()/ next() Reads a String value from the user (Take complete line/
Take only first word from line)
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
Object-Oriented Programming System:
OOPs is Object-Oriented Programming language which is used to develop Object oriented
applications. It is possible to develop object-based applications using java.
The principles of java:
1. Inheritance – Object relationships
2. Polymorphism – For multiple behaviors of object
3. Encapsulation – Data hiding
4. Abstraction – Data hiding
Object Relationships In JAVA:
A relationship in Java means different relations between two or more classes. For
example, if a class Bulb inherits another class Device, then we can say that Bulb is
having is-a relationship with Device, which implies Bulb is a device.
we have two types of relationship:
1. Is-A relationship: Whenever one class inherits another class, it is called an
IS-A relationship.
2. Has-A relationship: Whenever an instance of one class is used in another
class, it is called HAS-A relationship.
Classes and Objects:
In Java, classes and objects are basic concepts of object-oriented Programming
(OOPs) that are used to represent real-world concepts and entities.
Class is nothing but definition block where programmer can declare
1. Variables/ data members
2. Methods / member functions
3. Constructor
4. blocks
The class represents a group of objects having similar properties and behavior.
For example:
Class: Human Object: Man, Woman
Class: Mobile phone Object: iPhone, Samsung, Moto
Class: Food Object: Pizza, Burger, Samosa
Class: Food Object: car Attributes: weight, color Methods: drive, brake
No. Object Class
1) Object is an instance of a class. Class is a blueprint or template
from which objects are created.
2) Object is a real world entity Class is a group of similar objects.
such as pen, laptop, mobile, bed,
keyboard, mouse, chair etc.
3) Object is a physical entity. Class is a logical entity.
4) Object is created through new Class is declared using class
keyword mainly e.g. keyword e.g.
Student s1=new Student(); class Student{}
5) Object is created many times as Class is declared once.
per requirement.
6) Object allocates memory when Class doesn't allocated memory
it is created. when it is created.
7) There are many ways to create There is only one way to define class
object in java such as new in java using class keyword.
keyword, newInstance() method,
clone() method, factory method
and deserialization.
♦ Components of Java Classes
In general, class declarations can include these components, in order:
Modifiers: A class can be public or has default access
Class keyword: Class keyword is used to create a class.
Class name: The name should begin with an initial letter (capitalized by
convention).
Superclass (if any): The name of the class’s parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass) one
parent.
Interfaces (if any): A comma-separated list of interfaces implemented by the
class, if any, preceded by the keyword implements. A class can implement more
than one interface.
Body: The class body is surrounded by braces, { }.
Java Objects:
An object in Java is a basic unit of Object-Oriented Programming and represents
real-life entities. Objects are the instances of a class that are created to use the
attributes and methods of a class. A typical Java program creates many objects,
which as you know, interact by invoking methods. An object consists of:
State: It is represented by attributes of an object. It also reflects the properties
of an object.
Behavior: It is represented by the methods of an object. It also reflects the
response of an object with other objects.
Identity: It gives a unique name to an object and enables one object to interact
with other objects.
♦ How to Create Object in Java
The object is a basic building block of an OOPs language. In Java, we cannot
execute any program without creating an object. There are several ways by which
we can create objects of a class in java as we all know a class provides the
blueprint for objects, you create an object from a class.
Methods:
There are many different ways to create objects in Java.
Using new Keyword
Using clone() method
Using newInstance() method of the Class class
Using newInstance() method of the Constructor class
Using Deserialization
1) Using new Keyword
Using the new keyword is the most popular way to create an object or instance of
the class. When we create an instance of the class by using the new keyword, it
allocates memory (heap) for the newly created object and also returns the
reference of that object to that memory. The new keyword is also used to create an
array. The syntax for creating an object is:
Syntax:
// ClassName object = new ClassName();
public class CreateObjectExample1 {
void show() {
[Link]("Welcome to javaTpoint");
}
public static void main(String[] args) {
// creating an object using new keyword
CreateObjectExample1 obj = new CreateObjectExample1();
// invoking method using the object
[Link]();
}
}
// we can also invoke the constructor (default or parametrized) of the class.
public class CreateObjectExample2 {
// constructor of the class
CreateObjectExample2() {
[Link]("Welcome to javaTpoint");
}
public static void main(String[] args) {
// creating an object using new keyword
CreateObjectExample2 obj = new CreateObjectExample2();
}
}
2) Using clone () Method
The clone() method is the method of Object class. It creates a copy of an object
and returns the same copy. The JVM creates a new object when the clone() method
is invoked. It copies all the content of the previously created object into new one
object. Note that it does not call any constructor. We must implement the
Cloneable interface while using the clone() method. The method throws
CloneNotSupportedException exception if the object's class does not support the
Cloneable interface. The subclasses that override the clone() method can throw an
exception if an instance cannot be cloned.
public class CreateObjectExample3 implements Cloneable{
@Override
protected Object clone() throws CloneNotSupportedException {
//invokes the clone() method of the super class
return [Link]();
}
String str = "New Object Created";
public static void main(String[] args) {
//creating an object of the class
CreateObjectExample3 obj1 = new CreateObjectExample3();
//try catch block to catch the exception thrown by the method
try {
//creating a new object of the obj1 suing the clone() method
CreateObjectExample3 obj2 = (CreateObjectExample3) [Link]();
[Link]([Link]);
} catch (CloneNotSupportedException e){
[Link]();
}
}
}
3) Using newInstance() Method of Class class
The newInstance() method of the Class class is also used to create an object. It
calls the default constructor to create the object. It returns a newly created instance
of the class represented by the object. It internally uses the newInstance() method
of the Constructor class.
Syntax:
public class CreateObjectExample4 {
void show() {
[Link]("A new object created.");
}
public static void main(String[] args){
try {
//creating an instance of Class class
Class cls = [Link]("CreateObjectExample4");
//creates an instance of the class using the newInstance() method
CreateObjectExample4 obj = (CreateObjectExample4) [Link]();
//invoking the show() method
[Link]();
} catch (ClassNotFoundException e) {
[Link]();
} catch (InstantiationException e) {
[Link]();
} catch (IllegalAccessException e) {
[Link]();
}
}
}
4) Using newInstance() Method of Constructor class
It is like the newInstance() method of the Class class. It is known as a reflective
way to create objects. The method is defined in the Constructor class which is the
class of [Link] package. We can also call the parameterized constructor
and private constructor by using the newInstance() method. It is widely preferred
in comparison to newInstance() method of the Class class.
Syntax:
public T newInstance(Object... initargs) throws InstantiationException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException
The method parses an array of Objects as an argument. The values of primitive
types wrapped in a wrapper Object of the appropriate type. It returns a new object
created by calling the constructor. It throws IllegalAccessException,
IllegalArgumentException, InstantiationException, InvocationTargetException,
ExceptionInInitializerError Exceptions.
Syntax:
import [Link].*;
public class CreateObjectExample5 {
private String str;
CreateObjectExample5() {
}
public void setName(String str) {
[Link] = str;
}
public static void main(String[] args) {
try {
Constructor<CreateObjectExample5> constructor =
[Link]();
CreateObjectExample5 r = [Link]();
[Link]("JavaTpoint");
[Link]([Link]);
} catch (Exception e) {
[Link]();
}
}
}
5) Using Deserialization
In Java, serialization is the process of converting an object into a sequence of
byte-stream. The reverse process (byte-stream to object) of serialization is called
deserialization. The JVM creates a new object when we serialize or deserialize an
object. It does not use constructor to create an object. While using deserialization,
the Serializable interface (marker interface) must be implemented in the class.
Serialization: The writeObject() method of the ObjectOutputStream class is
used to serialize an object. It sends the object to the output stream.
Deserialization: The method readObject() of ObjectInputStream class is used
to deserialize an object. It references objects out of a stream.
[Link]
import [Link];
public class Employee implements Serializable {
int empid;
String empname;
public Empoyee(int empid, String empname)
{
[Link] = empid;
[Link] = empname;
}
}
[Link]
import [Link].*;
class SerializationExample {
public static void main(String args[])
{
Try {
//Creating the object
Employee emp = new Employee(198054,"Andrew");
//Creates a stream and writes the object
FileOutputStream fout=new FileOutputStream("[Link]");
ObjectOutputStream out=new ObjectOutputStream(employeeout);
[Link](emp);
[Link]();
//closes the output stream
[Link]();
[Link]("Successfully Created");
}
catch(Exception e)
{
[Link](e);
}
}
}
[Link]
import [Link].*;
class DeserializationExample {
public static void main(String args[]) {
try {
// Creating a stream to read the object
ObjectInputStream in = new ObjectInputStream(new
FileInputStream("[Link]"));
Employee e = (Employee) [Link]();
// prints the data of the serialized object
[Link]([Link] + " " + [Link]);
// closing the input stream
[Link]();
} catch (Exception e) {
[Link](e);
}
}
}
Reference Variable:
Java, being an object-oriented programming language, allows the use of reference
variables to work with objects and their data. In Java, objects are created
dynamically on the heap memory, and reference variables are used to hold the
memory address of these objects. This concept of reference variables is
fundamental to Java's approach to object-oriented programming.
A reference variable is a variable that holds the memory address of an object rather
than the actual object itself. It acts as a reference to the object and allows
manipulation of its data and methods. Reference variables are declared with a
specific type, which determines the methods and fields that can be accessed
through that variable.
When an object is created using the new keyword, memory is allocated on the heap
to store the object's data. The reference variable is then used to refer to this
memory location, making it possible to access and manipulate the object's
properties and behaviors.
Syntax:
class Car {
String brand;
int year;
}
public class ReferenceVariableExample {
public static void main(String[] args) {
// Declare a reference variable of type Car
Car myCar;
// Create a new Car object and assign its reference to myCar
myCar = new Car();
// Access and modify the object's properties
[Link] = "Toyota";
[Link] = 2021;
// Use the reference variable to perform actions on the object
[Link]("Brand: " + [Link]);
[Link]("Year: " + [Link]);
}
}
Local and Global Variables:
Local variables are declared within a specific block of code, such as a function or
method, and have limited scope and lifetime, existing only within that block.
Global variables, on the other hand, are declared outside of any function and can
be accessed from any part of the program, persisting throughout its execution.
♦ Local Variable:
Local variables are variables that are declared within a specific scope, such as
within a function or a block of code. These variables are only accessible within that
particular scope and are typically used for temporary storage of data or for
performing calculations within a limited context. Once the scope in which a local
variable is defined ends, the variable typically goes out of scope and its memory is
released.
In many programming languages, local variables have a limited visibility and
lifespan compared to global variables, which are accessible from any part of the
program. This encapsulation of variables within specific scopes helps to organize
code, prevent unintended modifications, and manage memory efficiently.
Syntax:
public class Main {
public static void exampleFunction() {
// Local variable declaration
int x = 10;
int y = 20;
int z = x + y;
[Link]("The sum is: " + z);
}
public static void main(String[] args) {
exampleFunction();
}
}
Advantages of local variable:
1. Encapsulation: Local variables help encapsulate data within specific functions
or blocks, reducing the risk of unintended modification.
2. Memory Management: They promote efficient memory usage by
automatically releasing memory once the scope exits.
3. Code Clarity: Local variables make code easier to read and understand by
limiting the scope of variables to where they are needed.
4. Name Reusability: Local variables allow the reuse of variable names without
causing conflicts with variables in other scopes.
Disadvantages of local variable:
1. Limited Accessibility: Local variables cannot be accessed outside of the scope
in which they are defined, which may restrict their use in certain scenarios.
2. Potential for Shadowing Bugs: Shadowing, where a local variable hides
another variable with the same name in an outer scope, can lead to bugs and
confusion if not handled properly.
3. Lifetime Limited to Scope: Local variables cease to exist once the scope in
which they are defined exits, which may be a disadvantage if persistent data
storage is required.
♦ Global Variable:
Global variables are variables that are declared outside of any function or block of
code and can be accessed from any part of the program. Unlike local variables,
which have limited scope, global variables have a broader scope and can be used
across multiple functions, modules, or files within a program.
Syntax:
public class Main {
// Global variable declaration
static int global_var = 100;
public static void exampleFunction() {
// Local variable declaration
int x = 10;
int y = 20;
int z = x + y + global_var;
[Link]("The sum is: " + z);
}
public static void main(String[] args) {
exampleFunction();
}
}
Advantages of global variable:
1. Accessibility: Global variables provide a convenient way to share data across
different parts of the program without passing them as function arguments.
2. Ease of Use: They simplify the sharing of data between functions and modules,
reducing the need for complex parameter passing mechanisms.
3. Persistence: Global variables retain their values throughout the entire execution
of the program, making them suitable for storing persistent data.
4. Reduced Code Duplication: Global variables can help reduce code duplication
by centralizing data that is used in multiple parts of the program.
Disadvantages of global variable:
1. Encapsulation Issues: Global variables can lead to encapsulation issues by
allowing any part of the program to modify their values, potentially leading to
unintended side effects.
2. Debugging Complexity: Since global variables can be accessed and modified
from anywhere in the program, tracking down bugs related to their usage can be
challenging.
3. Potential for Race Conditions: In multithreaded or concurrent programs,
global variables can introduce race conditions if accessed and modified
concurrently by multiple threads or processes.
4. Maintainability: Excessive use of global variables can make code harder to
understand and maintain, as their effects may not be localized to specific
functions or modules.
♦ Comparison Between Global and Local Variable
Global Variable Local Variable
Global variables are declared outside Local Variables are declared within a
all the function blocks. function block.
The scope is limited and remains
The scope remains throughout the
within the function only in which they
program.
are declared.
Any change in global variable affects Any change in the local variable does
the whole program, wherever it is not affect other functions of the
being used. program.
A local variable is created when the
A global variable exists in the program
function is executed, and once the
for the entire time the program is
execution is finished, the variable is
executed.
destroyed.
It can be accessed throughout the It can only be accessed by the function
program by all the functions present in statements in which it is declared and
the program. not by the other functions.
If the global variable is not initialized, If the local variable is not initialized, it
it takes zero by default. takes the garbage value by default.
Global variables are stored in the data Local variables are stored in a stack in
segment of memory. memory.
We cannot declare many variables with We can declare various variables with
the same name. the same name but in other functions.
Constructors:
Java constructors or constructors in Java is a terminology used to construct
something in our programs. A constructor in Java is a special method that is used
to initialize objects. The constructor is called when an object of a class is created. It
can be used to set initial values for object attributes.
♦ What are Constructors in Java?
In Java, a Constructor is a block of codes similar to the method. It is called when
an instance of the class is created. At the time of calling the constructor, memory
for the object is allocated in the memory. It is a special type of method that is used
to initialize the object. Every time an object is created using the new () keyword, at
least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such
case, Java compiler provides a default constructor by default.
Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because Java
compiler creates a default constructor if your class does not have any.
♦ Rules for Creating Java Constructor:
There are following rules for defining a constructor:
1. Constructor name must be the same as its class name.
2. A Constructor must have no explicit return type.
3. A Java constructor cannot be abstract, static, final, and synchronized.
Note: We can use access modifiers while declaring a constructor. It controls the
object creation. In other words, we can have private, protected, public or default
constructor in Java.
Types of Java Constructors
♦ Types of constructors in Java:
1. Default Constructor (no-arg constructor)
2. Parameterized Constructor
1) Java Default Constructor
A constructor is called "Default Constructor" when it does not have any parameter.
Example of Default Constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.
Syntax:
// Java Program to create and call a default constructor
class Bike1 {
// creating a default constructor
Bike1() {
[Link]("Bike is created");
}
// main method
public static void main(String args[]) {
// calling a default constructor
Bike1 b = new Bike1();
}
}
Q) What is the purpose of a default constructor?
The default constructor is used to provide the default values to the object like 0,
null, etc., depending on the type.
2) Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.
Why use the parameterized constructor?
The parameterized constructor is used to provide different values to distinct
objects. However, you can provide the same values also.
Example of Parameterized Constructor
In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.
Syntax:
public class test {
int id;
String name;
// creating a parameterized constructor
test(int i, String n) {
id = i;
name = n;
}
// method to display the values
void display() {
[Link](id + " " + name);
}
public static void main(String args[]) {
// creating objects and passing values
test s1 = new test(111, "Karan");
test s2 = new test(222, "Aryan");
// calling method to display the values of object
[Link]();
[Link]();
}
}
♦ Constructor Overloading in Java
In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.
Constructor overloading in Java is a technique of having more than one constructor
with different parameter lists. They are arranged in a way that each constructor
performs a different task. They are differentiated by the compiler by the number of
parameters in the list and their types.
Syntax:
public class test {
int id;
String name;
int age;
// creating two arg constructor
test(int i,String n){
id = i;
name = n;
}
// creating three arg constructor
test(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display() {
[Link](id + " " + name + " " + age);
}
public static void main(String args[]) {
test s1 = new test(111, "Karan");
test s2 = new test(222, "Aryan", 25);
[Link]();
[Link]();
}
}
♦ Difference Between Constructor and Method in Java
Java Constructor Java Method
A constructor is used to initialize the A method is used to expose the
state of an object. behavior of an object.
A constructor must not have a return
A method must have a return type.
type.
The constructor is invoked implicitly. The method is invoked explicitly.
The Java compiler provides a default
The method is not provided by the
constructor if we do not have any
compiler in any case.
constructor in a class.
The constructor name must be same as The method name may or may not be
the class name. same as the class name.
Aggregation and Composition
Aggregation Composition
Association between two objects that A specific type of Aggregation that
defines the "has-a" relationship is implies ownership is referred to as
referred to as Aggregation. Composition.
In Aggregation, objects can remain in In a composition relationship, objects
the scope of a system without each cannot remain in the scope of a system
other. without each other.
In Aggregation, linked objects are In Composition, objects are tightly
independent of each other. coupled or dependent on each other.
In Aggregation, if we delete the parent In Composition, if we delete a parent
object, the child object will still exist in object, the child object also gets
the system. For example, if we remove deleted. For example, if we delete a
wheels from a car, the car can function folder, the files will also get deleted
adequately with another wheel. which contain in the folder.
We represent it by using the filled We represent it by using the empty
diamond. diamond.
In Aggregation, child objects don't have In Composition, child objects have a
a lifetime. lifetime.
In Aggregation, if we delete an In the case of owning a class, it affects
assembly, it will never affect its parts. the containing class object.
Inheritance:
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object with the help of extends keyword.
Java, Inheritance is an important pillar of OOP (Object-Oriented Programming). It is the
mechanism in Java by which one class is allowed to inherit the features (fields and
methods) of another class.
In Java, Inheritance means creating new classes based on existing ones. A class that is
inherited from another class can reuse the methods and fields of that class. In addition, you
can add new fields and methods to your current class as well.
♦ What is Inheritance?
Inheritance is one of the Oops principles where one class acquires properties and
actions of another class with the help of 'extends' keywords. The class from where
properties are acquiring/inheriting is called super/base/parent class. The class to
where properties are inherited/delivered is called sub/child class. Inheritance
takes place between 2 or more than 2 classes.
Through inheritance, a subclass can access members of its superclass (fields and
methods), enforce reuse rules, and encourage hierarchy.
Inheritance represents the IS-A relationship which is also known as a parent-child
relationship.
♦ Why Do We Need Java Inheritance?
Code Reusability: The code written in the Superclass is common to all
subclasses. Child classes can directly use the parent class code.
Method Overriding: Method Overriding is achievable only through
Inheritance. It is one of the ways by which Java achieves Run Time
Polymorphism.
Abstraction: The concept of abstract where we do not have to provide all
details, is achieved through inheritance. Abstraction only shows the
functionality to the user.
♦ Terms used in Inheritance
Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is
also called a derived class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
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.
♦ The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that we are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class that is inherited is called a parent or superclass,
and the new class is called child or subclass.
♦ Java Inheritance Types
Below are the different types of inheritance which are supported by Java.
1. Single level Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
1. Single level Inheritance
When a class sub class inherits another super class, it is known as a single level
inheritance.
To perform single level inheritance only 2 classes are mandatory.
In single inheritance, a sub-class inherits the properties and behavior of a single-
parent class. Sometimes, it is also known as simple inheritance.
RealTime Example:
Employee >> manager
Employee is the base class with basic attributes and methods.
Manager inherits from Employee and adds more specific attributes and methods.
In the below figure, ‘A’ is a parent class and ‘B’ is a child class. Class ‘B’ inherits
all the properties of class ‘A’.
Syntax:
class Animal {
void eat() {
[Link]("eating...");
}
}
class Dog extends Animal {
void bark() {
[Link]("barking...");
}
}
class TestInheritance {
public static void main(String args[]) {
Dog d = new Dog();
[Link]();
[Link]();
}
}
2. Multilevel Inheritance / Chaining inheritance
Multilevel Inheritance takes place between 3 or more than 3 classes. In Multilevel
Inheritance 1 sub class acquires properties of another super class & that super class
acquires properties of its another super class & phenomenon continuous.
When there is a chain of inheritance, it is known as multilevel inheritance. In
Multilevel Inheritance, a derived class will be inheriting a base class, and as well
as the derived class also acts as the base class for other classes.
RealTime Example:
Employee >> Manager >> Senior Manager
Employee is the base class with basic attributes and methods.
Manager inherits from Employee and adds more specific attributes and
methods.
SeniorManager inherits from Manager and further extends it with
additional attributes and methods.
In the below image, class A serves as a base class for the derived class B, which in
turn serves as a base class for the derived class C. In Java, a class cannot directly
access the grandparent’s members.
Syntax:
class Animal {
void eat() {
[Link]("eating...");
}
}
class Dog extends Animal {
void bark() {
[Link]("barking...");
}
}
class BabyDog extends Dog {
void weep() {
[Link]("weeping...");
}
}
class TestInheritance2 {
public static void main(String args[]) {
BabyDog d = new BabyDog();
[Link]();
[Link]();
[Link]();
}
}
3. Hierarchical Inheritance
When two or more classes inherit properties of a single class, it is known as
hierarchical inheritance.
Multiple sub classes can acquire properties of 1 super class is known as
hierarchical Inheritance.
In Hierarchical Inheritance, one class serves as a superclass (base class) for more
than one subclass.
RealTime Example:
Employee >> Manager, intern, Developer
Employee is the base class with basic attributes and methods.
Manager, Intern, and Engineer are derived classes that inherit data from
Employee and add their own specific attributes and methods.
In the below image, class A serves as a base class for the derived classes B, C, and
D.
Syntax:
class Animal {
void eat() {
[Link]("eating...");
}
}
class Dog extends Animal {
void bark() {
[Link]("barking...");
}
}
class Cat extends Animal {
void meow() {
[Link]("meowing...");
}
}
class TestInheritance3 {
public static void main(String args[]) {
Cat c = new Cat();
[Link]();
[Link]();
// [Link]();//[Link]
}
}
4. Multiple Inheritance (Through Interfaces)
To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
In Multiple inheritances, one sub class can have more than one superclass and
inherit features from all parent classes.
Java doesn't support Multiple Inheritance using class because of diamond
ambiguity problem.
By using interface, we can achieve Multiple Inheritance.
Note: object class is the super most class in java
In the image below, Class C is derived from interfaces A and B.
5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn’t
support multiple inheritances with classes, hybrid inheritance involving multiple
inheritance is also not possible with classes.
In Java, we can achieve hybrid inheritance only through Interfaces if we want to
involve multiple inheritance to implement Hybrid inheritance.
However, it is important to note that Hybrid inheritance does not necessarily
require the use of Multiple Inheritance exclusively. It can be achieved through a
combination of Multilevel Inheritance and Hierarchical Inheritance with classes,
Hierarchical and Single Inheritance with classes. Therefore, it is indeed possible to
implement Hybrid inheritance using classes alone, without relying on multiple
inheritance type.
♦ Java IS-A type of Relationship
IS-A is a way of saying: This object is a type of that object. Let us see how the
extends keyword is used to achieve inheritance.
public class SolarSystem {
}
public class Earth extends SolarSystem {
}
public class Mars extends SolarSystem {
}
public class Moon extends Earth {
}
Now, based on the above example, in Object-Oriented terms, the following are
true:-
SolarSystem is the superclass of Earth class.
SolarSystem is the superclass of Mars class.
Earth and Mars are subclasses of SolarSystem class.
Moon is the subclass of both Earth and SolarSystem classes.
♦ Advantages and Disadvantages of Inheritance
Advantages Of Inheritance in Java:
1. Code Reusability: Inheritance allows for code reuse and reduces the amount of
code that needs to be written. The subclass can reuse the properties and
methods of the superclass, reducing duplication of code.
2. Abstraction: Inheritance allows for the creation of abstract classes that define a
common interface for a group of related classes. This promotes abstraction and
encapsulation, making the code easier to maintain and extend.
3. Class Hierarchy: Inheritance allows for the creation of a class hierarchy, which
can be used to model real-world objects and their relationships.
4. Polymorphism: Inheritance allows for polymorphism, which is the ability of an
object to take on multiple forms. Subclasses can override the methods of the
superclass, which allows them to change their behavior in different ways.
Disadvantages of Inheritance in Java:
1. Complexity: Inheritance can make the code more complex and harder to
understand. This is especially true if the inheritance hierarchy is deep or if
multiple inheritances are used.
2. Tight Coupling: Inheritance creates a tight coupling between the superclass and
subclass, making it difficult to make changes to the superclass without affecting
the subclass.
Method Overloading and Method Overriding:
♦ Java Method Overloading
Method overloading is a feature in Java that allows a class to have more than one
method with the same name, provided their parameter lists are different. Itenables
methods to perform similar but distinct tasks. Method overloading is a form of
compile-time polymorphism, meaning that the compiler determines which method
to call based on the method signature (name and parameter list).
♦ Java Method Overriding
Method overriding is a fundamental concept in object-oriented programming
(OOP) that allows a subclass to provide a specific implementation for a method
that is already defined in its superclass. It enables a subclass to inherit the method
from the superclass but override it to perform a different task. Method overriding is
essential for achieving runtime polymorphism, where the method that gets called is
determined by the actual object type at runtime, not the reference type.
No. Method Overloading Method Overriding
Method overriding is used to
Method overloading is used to
provide the specific implementation
1) increase the readability of the
of the method that is already
program.
provided by its super class.
Method overriding occurs in two
Method overloading is performed
2) classes that have IS-A (inheritance)
within class.
relationship.
In case of method overloading, In case of method overriding,
3)
parameter must be different. parameter must be same.
Method overloading is the
Method overriding is the example of
4) example of compile time
run time polymorphism.
polymorphism.
In Java, method overloading
cannot be performed by changing
return type of the method only.
Return type must be same or
5) Return type can be same or
covariant in method overriding.
different in method overloading.
But you must have to change the
parameter.
6) It uses static binding. It uses dynamic binding.
It provides specific implementation
7) It enhances code readability. of the method that is provided by the
parent class.
If any error occurs, can be caught If any error occurs, can be caught at
8)
at compile-time. run-time.
It is applicable to both private and It is not applicable to private and
9)
final methods. final methods.
10) It is called early binding. It is called late binding.
11) Static method can be overloaded. Static method cannot be overridden.
12) Implemented in single class. Implemented in two classes.
Abstract Class
A class that is declared with the abstract keyword is known as an abstract class in
Java. It can have abstract and non-abstract methods (method with the body).
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
The interface in Java is a mechanism to achieve abstraction. There can be only
abstract methods in the Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java.
Casting: UP and Down
Polymorphism:
The word ‘polymorphism’ means ‘having many forms’. In Java, polymorphism
refers to the ability of a message to be displayed in more than one form. This
concept is a key feature of Object-Oriented Programming and it allows objects
to behave differently based on their specific class type.
Real-life Illustration of Polymorphism in Java: A person can have different
characteristics at the same time. Like a man at the same time is a father, a husband,
and an employee. So the same person possesses different behaviors in different
situations. This is called polymorphism.
♦ Types of Java Polymorphism
In Java Polymorphism is mainly divided into two types:
Compile-Time Polymorphism
Runtime Polymorphism
1. Compile-Time Polymorphism
Compile-Time Polymorphism in Java is also known as static polymorphism. This
type of polymorphism is achieved by function overloading or operator overloading.
Note: But Java doesn’t support the Operator Overloading.
Subtypes of Compile-time Polymorphism:
Function Overloading: It is a feature in C++/Java where multiple functions
can have the same name but with different parameter lists. The compiler will
decide which function to call based on the number and types of arguments
passed to the function.
Operator Overloading: It is a feature in C++ where the operators such as +, -,
*, etc. can be given additional meanings when applied to user-defined data
types.
Template: It is a powerful feature in C++ that allows us to write generic
functions and classes. A template is a blueprint for creating a family of
functions or classes.
2. Runtime Polymorphism
Runtime Polymorphism in Java known as Dynamic Method Dispatch. It is a
process in which a function call to the overridden method is resolved at Runtime.
This type of polymorphism is achieved by Method Overriding. Method overriding,
on the other hand, occurs when a derived class has a definition for one of the
member functions of the base class. That base function is said to be overridden.
Subtype of Run-Time Polymorphism
Virtual Functions: It allows an object of a derived class to behave as if it were an
object of the base class. The derived class can override the virtual function of the
base class to provide its own implementation. The function call is resolved at
runtime, depending on the actual type of the object.
♦ Advantages and Disadvantages of Polymorphism
Advantages of Polymorphism
Increases code reusability by allowing objects of different classes to be treated
as objects of a common class.
Improves readability and maintainability of code by reducing the amount of
code that needs to be written and maintained.
Supports dynamic binding, enabling the correct method to be called at runtime,
based on the actual class of the object.
Enables objects to be treated as a single type, making it easier to write generic
code that can handle objects of different types.
Disadvantages of Polymorphism
Can make it more difficult to understand the behavior of an object, especially if
the code is complex.
This may lead to performance issues, as polymorphic behavior may require
additional computations at runtime.
Abstraction:
Abstraction in Java is the process of hiding the implementation details and only
showing the essential functionality or features to the user. This helps simplify the
system by focusing on what an object does rather than how it does it. The
unnecessary details or complexities are not displayed to the user.
In Java, abstraction is achieved by interfaces and abstract classes. We can
achieve 100% abstraction using interfaces. Data Abstraction may also be defined
as the process of identifying only the required characteristics of an object ignoring
the irrelevant details. The properties and behaviors of an object differentiate it from
other objects of similar type and also help in classifying/grouping the objects.
♦ Abstraction Real-Life Example:
Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerator will increase the speed of a car or applying brakes will
stop the car, but he does not know how on pressing the accelerator the speed is
actually increasing, he does not know about the inner mechanism of the car or the
implementation of the accelerator, brakes, etc. in the car. This is what abstraction
is.
♦ Advantages and Disadvantages of Abstraction
Advantages of Abstraction
Simplifies complex systems by hiding implementation details.
Increases code reusability and maintainability.
Enhances security by exposing only essential features.
Improves modularity and separation of concerns.
Provides a clear and user-friendly interface.
Disadvantages of Abstraction
It can add unnecessary complexity if overused.
May reduce flexibility in implementation.
Makes debugging and understanding the system harder for unfamiliar users.
Overhead from abstraction layers can affect performance.
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.
We can create a fully encapsulated class in Java by making all the data members of
the class private. Now we can use setter and getter methods to set and get the data
in it.
The Java Bean class is the example of a fully encapsulated class.
♦ Advantages and disadvantages of Encapsulation
Advantages of Encapsulation
Data Hiding: Encapsulation provides data hiding. Users don’t see the
implementation of the class. The user only knows that we are passing the values
to a setter method and variables are getting initialized with that value.
Increased Flexibility: We can make the variables of the class read-only or
write-only depending on our requirements want variables read-only then we
have to omit the setter methods like setName(), and implementingsetAge(), if
we wish to make the variables write-only then we have to omit the get methods
like getName().
Reusability: Encapsulation also improves the re-usability and is easy to change
with new requirements.
Testing code is easy: Encapsulated code is easy to test for unit testing.
Freedom of advantages the details: one of the major advantages of
encapsulation is that it gives the programmer freedom to implement the details
of a system. The only constraint on the programmer is to maintain the abstract
interface that outsiders see.
Disadvantages of Encapsulation in Java
Can lead to increased complexity, especially if not used properly.
Can make it more difficult to understand how the system works.
This may limit the flexibility of the implementation.
Java packages
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined
package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util,
sql etc.
♦ Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Sequence of the program must be package then import then class.
Access Modifiers
There are two types of modifiers in Java: access modifiers and non-access
modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors,
methods, and class by applying the access modifier on it.
♦ There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package.
If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package
and outside the package through inheritance. If you do not make the child
class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It has the
widest scope among all other modifiers. It can be accessed from within the
class, outside the class, within the package and outside the package.
Access within class within outside outside
Modifier package package by package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y