0% found this document useful (0 votes)
19 views23 pages

JAVA

Uploaded by

sgojo889
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views23 pages

JAVA

Uploaded by

sgojo889
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Java

Java is a class-based, object-oriented programming language that is intended to let


application developers write once, and run anywhere (WORA), meaning that
compiled Java code can run on all platforms that support Java without the need for
recompilation.

Java is known for its simplicity, robustness, and security features, making it a popular
choice for enterprise-level applications.

It helps to create reusable code and modular programs.

Key Features of Java

1. Platform Independent

Compiler converts source code to byte code and then the JVM executes the bytecode
generated by the compiler. This byte code 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 byte code. That is why we
call java a platform-independent language.

2. Object-Oriented Programming

Java is an object-oriented language, promoting the use of objects and classes.


Organizing the program in the terms of a collection of objects is a way of object-oriented
programming, each of which represents an instance of the class.

The four main concepts of Object-Oriented programming are:

Abstraction

Abstraction in Java is the process in which we only show essential details/functionality


to the user. The non-essential implementation details 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 behaviours
of an object differentiate it from other objects of similar type and also help in
classifying/grouping the objects.

Java Abstract classes and Java Abstract methods

1. An abstract class is a class that is declared with an abstract keyword.

2. An abstract method is a method that is declared without implementation.


3. An abstract class may or may not have all abstract methods. Some of them can
be concrete methods

4. A method-defined abstract must always be redefined in the subclass, thus


making overriding compulsory or making the subclass itself abstract.

5. Any class that contains one or more abstract methods must also be declared with
an abstract keyword.

6. There can be no object of an abstract class. That is, an abstract class can not be
directly instantiated with the new operator.

7. An abstract class can have parameterized constructors and the default


constructor is always present in an abstract class.

Interface
Interfaces are another method of implementing abstraction in Java. The key difference
is that, by using interfaces, we can achieve 100% abstraction in Java classes. In Java or
any other language, interfaces include both methods and variables but lack a method
body. Apart from abstraction, interfaces can also be used to implement interfaces in
Java.
Advantages of Abstraction

Here are some advantages of abstraction:

• It reduces the complexity of viewing things.

• Avoids code duplication and increases reusability.

• Helps to increase the security of an application or program as only essential


details are provided to the user.

• It improves the maintainability of the application.

• It improves the modularity of the application.

Disadvantages of Abstraction in Java

Here are the main disadvantages of abstraction in Java:

• Abstraction can make it more difficult to understand how the system works.

• It can lead to increased complexity, especially if not used properly.

• This may limit the flexibility of the implementation.

Encapsulation

• Encapsulation in Java is a fundamental concept in object-oriented


programming (OOP) that refers to the bundling of data and methods that operate
on that data within a single unit, which is called a class in Java. Java
Encapsulation is a way of hiding the implementation details of a class from
outside access and only exposing a public interface that can be used to interact
with the class.
• In Java, encapsulation is achieved by declaring the instance variables of a
class as private, which means they can only be accessed within the class. To
allow outside access to the instance variables, public methods called getters
and setters are defined, which are used to retrieve and modify the values of the
instance variables, respectively. By using getters and setters, the class can
enforce its own data validation rules and ensure that its internal state remains
consistent.
Encapsulation is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together code and the data it manipulates. Another way to
think about encapsulation is, that it is a protective shield that prevents the data from
being accessed by the code outside this shield.

• Technically in encapsulation, the variables or data of a class is hidden from any


other class and can be accessed only through any member function of its own
class in which it is declared.

• As in encapsulation, the data in a class is hidden from other classes using the
data hiding concept which is achieved by making the members or methods of a
class private, and the class is exposed to the end-user or the world without
providing any details behind implementation using the abstraction concept, so it
is also known as a combination of data-hiding and abstraction.

• Encapsulation can be achieved by Declaring all the variables in the class as


private and writing public methods in the class to set and get the values of
variables.

• It is more defined with the setter and getter method.

Advantages of Encapsulation

• Data Hiding: it is a way of restricting the access of our data members by hiding
the implementation details. Encapsulation also provides a way for data hiding.
The user will have no idea about the inner implementation of the class. It will not
be visible to the user how the class is storing values in the variables. The user will
only know that we are passing the values to a setter method and variables are
getting initialized with that value.

• Increased Flexibility: We can make the variables of the class read-only or write-
only depending on our requirements. If we wish to make the variables read-only
then we have to omit the setter methods like setName(), setAge(), etc. from the
above program or if we wish to make the variables write-only then we have to
omit the get methods like getName(), getAge(), etc. from the above program
• 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 to programmer in implementing the details of the system: This is


one of the major advantage of encapsulation that it gives the programmer
freedom in implementing 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.

• May limit the flexibility of the implementation.

class Name {

// Private is using to hide the data

private int age;

// getter

public int getAge() { return age; }

// setter

public void setAge(int age) { this.age = age; }

// Driver Class

class GFG {

// main function

public static void main(String[] args)

Name n1 = new Name();


n1.setAge(19);

System.out.println("The age of the person is: "

+ n1.getAge());

Inheritance

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

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.

Important Terminologies Used in Java Inheritance

• Class: Class is a set of objects which shares common characteristics/ behavior


and common properties/ attributes. Class is not a real-world entity. It is just a
template or blueprint or prototype from which objects are created.

• Super Class/Parent Class: The class whose features are inherited is known as a
superclass(or a base class or a parent class).

• Sub Class/Child Class: The class that inherits the other class is known as a
subclass(or a derived class, extended class, or child class). The subclass can
add its own fields and methods in addition to the superclass fields and methods.

• Reusability: Inheritance supports the concept of “reusability”, i.e. when we want


to create a new class and there is already a class that includes some of the code
that we want, we can derive our new class from the existing class. By doing this,
we are reusing the fields and methods of the existing class.

Polymorphism

Polymorphism allows us to perform a single action in different ways. In other


words, polymorphism allows you to define one interface and have multiple
implementations. The word “poly” means many and “morphs” means forms, So
it means many forms.

Types of Java Polymorphism

In Java Polymorphism is mainly divided into two types:

• Compile-time Polymorphism

• Runtime Polymorphism

Compile-Time Polymorphism in Java

It is also known as static polymorphism. This type of polymorphism is achieved


by function overloading or operator overloading.

Java doesn’t support the Operator Overloading.

Method Overloading

When there are multiple functions with the same name but different parameters
then these functions are said to be overloaded. Functions can be overloaded by
changes in the number of arguments or/and a change in the type of arguments.

1. Function Overloading

It is a feature in C++ 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.

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

3. 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.
Runtime Polymorphism in Java

It is also 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

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

Diagram –

Polymorphism in Java is a concept that allows objects of different classes to be


treated as objects of a common class. It enables objects to behave differently
based on their specific class type.

Advantages of Polymorphism in Java

1. Increases code reusability by allowing objects of different classes to be treated


as objects of a common class.

2. Improves readability and maintainability of code by reducing the amount of code


that needs to be written and maintained.

3. Supports dynamic binding, enabling the correct method to be called at runtime,


based on the actual class of the object.

4. 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 in Java

1. Can make it more difficult to understand the behavior of an object, especially if


the code is complex.

2. This may lead to performance issues, as polymorphic behavior may require


additional computations at runtime.

3. Simplicity

Java’s syntax is simple and easy to learn, especially for those familiar with C or C++. It
eliminates complex features like pointers and multiple inheritances, making it easier
to write, debug, and maintain code.

4. Robustness

Java language is robust which means reliable. It is developed in such a way that it puts
a lot of effort into checking errors as early as possible, that is why the java compiler is
able to detect even those 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. Security

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. That’s why several security
flaws like stack corruption or buffer overflow are impossible to exploit in Java. Also, 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 and Enterprise Java Beans are used for creating
distributed applications in java. The java programs can be easily distributed on one or
more systems that are connected to each other through an internet connection.

7. Multithreading

Java supports multithreading, enabling the concurrent execution of multiple parts of


a program. This feature is particularly useful for applications that require high
performance, such as games and real-time simulations.

8. Portability

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. WORA(Write Once Run
Anywhere) makes java application to generates a ‘.class’ file that corresponds to our
applications(program) but contains code in binary format. It provides ease t architecture-
neutral ease as bytecode is not dependent on any machine architecture. It is the primary
reason java is used in the enterprising IT industry globally worldwide.

9. High Performance

Java architecture is defined in such a way that it reduces overhead during the runtime
and at some times java uses Just In Time (JIT) compiler where the compiler compiles
code on-demand basis where it only compiles those methods that are called making
applications to execute faster.

If you want to master Java, check out the Java Programming – Basic to Advanced course
by us. It’s perfect for taking your Java skills from beginner to expert.

How Java Code Executes

The execution of a Java application code involves three main steps:


How Java Code Executes

1. Creating the Program

Java programs are written using a text editor or an Integrated Development


Environment (IDE) like IntelliJ IDEA, Eclipse, or NetBeans. The source code is saved
with a .java extension.

2. Compiling the Program

The Java compiler (javac) converts the source code into bytecode, which is stored in
a .class file. This bytecode is platform-independent and can be executed on any
machine with a JVM.

3. Running the Program

The JVM executes the compiled bytecode, translating it into machine code specific to
the operating system and hardware.

Example Program:

Java

public class HelloWorld {

public static void main(String[] args)

System.out.println("Hello, World!");

Before learning Java, one must be familiar with these common terms of Java.

1. Java Virtual Machine(JVM)

The JVM is an integral part of the Java platform, responsible for executing Java bytecode.
It ensures that the output of Java programs is consistent across different platforms.

• Writing a program is done by a java programmer like you and me.

• The compilation is done by the JAVAC compiler 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.

• In the Running phase of a program, JVM executes the bytecode generated by the
compiler.
Now, we understood that the function of Java Virtual Machine is to execute the bytecode
produced by the compiler. Every Operating System has a different JVM but the output
they produce after the execution of bytecode is the same across all the operating
systems. This is why Java is known as a platform-independent language.

2. Bytecode

Bytecode is the intermediate representation of Java code, generated by the Java


compiler. It is platform-independent and can be executed by the JVM.

3. Java Development Kit(JDK)

While we were using the term JDK when we learn about bytecode and JVM. So, as the
name suggests, it is a complete Java development kit that includes everything
including compiler, Java Runtime Environment (JRE), java debuggers, java docs, etc.
For the program to execute in java, we need to install JDK on our computer in order to
create, compile and run the java program.

4. Java Runtime Environment (JRE)

JDK includes JRE. JRE installation on our computers allows the java program to run,
however, we cannot compile it. JRE includes a browser, JVM, applet support, and plugins.
For running the java program, a computer needs JRE.

5. Garbage Collector

In Java, programmers can’t delete the objects. To delete or recollect that memory JVM
has a program called Garbage Collector. Garbage Collectors can recollect the objects
that are not referenced. So Java makes the life of a programmer easy by handling
memory management. However, programmers should be careful about their code
whether they are using objects that have been used for a long time. Because Garbage
cannot recover the memory of objects being referenced.

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.

Basically everything in java is represented in Class as an object including the main


function.

Advantages of Java

• 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.
• Object-Oriented: Java is an object-oriented programming language, which
means that it follows the principles of encapsulation, inheritance, and
polymorphism.

• Security: Java has built-in security features that make it a secure platform for
developing applications, such as automatic memory management and type
checking.

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

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

Arrays are fundamental structures in Java that allow us to store multiple values of
the same type in a single variable. They are useful for managing collections of data
efficiently.

type[] arrayName;

Instantiating an Array in Java

var-name = new type [size];

numbers = new int[5]; // Creating an array of 5 integers

Here, type specifies the type of data being allocated, size determines the number of
elements in the array, and var-name is the name of the array variable that is linked
to the array. To use new to allocate an array, you must specify the type and number
of elements to allocate.

Example:

//declaring array
int intArray[];
// allocating memory to array
intArray = new int[20];
// combining both statements in one
int[] intArray = new int[20];

// Declaring array literal


int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : "+ arr[i]);

Types of Arrays in Java

Java supports different types of arrays:

1. Single-Dimensional Arrays

These are the most common type of arrays, where elements are stored in a linear order.

int[] singleDimArray = {1, 2, 3, 4, 5}; // A single-dimensional array

2. Multi-Dimensional Arrays

Arrays with more than one dimension, such as two-dimensional arrays (matrices).

int[][] multiDimArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
}; // A 2D array (matrix)

You can also access java arrays using for each loops.
Arrays of Objects in Java

An array of objects is created like an array of primitive-type data items in the following
way.

Student[] arr = new Student[5]; //Student is a user-defined class

// Java program to illustrate creating

// an array of objects

class Student {

public int roll_no;

public String name;

Student(int roll_no, String name)

this.roll_no = roll_no;

this.name = name;

// Elements of the array are objects of a class Student.

public class GFG {

public static void main(String[] args)

// declares an Array of Student

Student[] arr;

// allocating memory for 5 objects of type Student.

arr = new Student[5];


// initialize the first elements of the array

arr[0] = new Student(1, "aman");

// initialize the second elements of the array

arr[1] = new Student(2, "vaibhav");

// so on...

arr[2] = new Student(3, "shikar");

arr[3] = new Student(4, "dharmesh");

arr[4] = new Student(5, "mohit");

// accessing the elements of the specified array

for (int i = 0; i < arr.length; i++)

System.out.println("Element at " + i + " : "

+ arr[i].roll_no + " "

+ arr[i].name);

An array of objects is also created like :

// Java program to illustrate creating

// an array of objects

class Student

public String name;


Student(String name)

this.name = name;

@Override

public String toString(){

return name;

// Elements of the array are objects of a class Student.

public class GFG

public static void main (String[] args)

// declares an Array and initializing the elements of the array

Student[] myStudents = new Student[]{new Student("Dharma"),new


Student("sanvi"),new Student("Rupa"),new Student("Ajay")};

// accessing the elements of the specified array

for(Student m:myStudents){

System.out.println(m);

Example (Iterating the array):

public class GFG {


public static void main(String[] args)

int[] arr = new int[2];

arr[0] = 10;

arr[1] = 20;

for (int i = 0; i < arr.length; i++)

System.out.println(arr[i]);

Declaration:

int[][] intArray = new int[10][20]; //a 2D array or matrix


int[][][] intArray = new int[10][20][10]; //a 3D array

// Java Program to demonstrate

// Java Multidimensional Array

import java.io.*;

// Driver class

class GFG {

public static void main(String[] args)

// Syntax

int[][] arr = new int[3][3];

// 3 row and 3 column

// Number of Rows
System.out.println("Number of Rows:"+

arr.length);

// Number of Columns

System.out.println("Number of Columns:"+

arr[0].length);

// Java Program to Multidimensional Array

// Driver Class

public class multiDimensional {

// main function

public static void main(String args[])

// declaring and initializing 2D array

int arr[][]

= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };

// printing 2D array

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++)

System.out.print(arr[i][j] + " ");

System.out.println();

}
}

Output

279

361

742

Passing Arrays to Methods

Like variables, we can also pass arrays to methods. For example, the below program
passes the array to method sum to calculate the sum of the array’s values.

// Java program to demonstrate

// passing of array to method

public class Test {

// Driver method

public static void main(String args[])

int arr[] = { 3, 1, 2, 5, 4 };

// passing array to method m1

sum(arr);

public static void sum(int[] arr)

// getting sum of array values

int sum = 0;
for (int i = 0; i < arr.length; i++)

sum += arr[i];

System.out.println("sum of array values : " + sum);

Output

sum of array values : 15

Complexity of the above method:

Time Complexity: O(n)


Auxiliary Space : O(1)

Advantages of Java Arrays

• Efficient Access: Accessing an element by its index is fast and has constant time
complexity, O(1).

• Memory Management: Arrays have fixed size, which makes memory


management straightforward and predictable.

• Data Organization: Arrays help organize data in a structured manner, making it


easier to manage related elements.

Disadvantages of Java Arrays

• Fixed Size: Once an array is created, its size cannot be changed, which can lead
to memory waste if the size is overestimated or insufficient storage if
underestimated.

• Type Homogeneity: Arrays can only store elements of the same data type, which
may require additional handling for mixed types of data.

• Insertion and Deletion: Inserting or deleting elements, especially in the middle of


an array, can be costly as it may require shifting elements.
public class RIT {

public static void main(String[] args)

String[] arr = {"a", "b"};

for (int i = 0; i < arr.length; i++)

System.out.println(arr[i]);

public class RIT {

public static void main(String[] args)

int[] a = {1,2,3,4,5,6,7,8,9,10};

for (int i = 0; i < a.length; i++)

System.out.println(a[i]);

JVM

JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because
it doesn't physically exist. It is a specification that provides a runtime environment in
which Java bytecode can be executed. It can also run those programs which are written
in other languages and compiled to Java bytecode.

VMs are available for many hardware and software platforms. JVM, JRE, and JDK are
platform dependent because the configuration of each OS is different from each other.
However, Java is platform independent. There are three notions of the
JVM: specification, implementation, and instance.

The JVM performs the following main tasks:

o Loads code
o Verifies code

o Executes code

o Provides runtime environment

JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE.
The Java Runtime Environment is a set of software tools which are used for
developing Java applications. It is used to provide the runtime environment. It
is the implementation of JVM. It physically exists. It contains a set of libraries +
other files that JVM uses at runtime.

JDK

JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a
software development environment which is used to develop Java applications
and applets. It physically exists. It contains JRE + development tools.

JDK is an implementation of any one of the below given Java Platforms released by
Oracle Corporation:

o Standard Edition Java Platform

o Enterprise Edition Java Platform

o Micro Edition Java Platform

The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as
an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation
generator (Javadoc), etc. to complete the development of a Java Application.

You might also like