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

Java 2

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

Java 2

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

JAVA

Java is a class-based, object-oriented programming language that is designed to have as


few implementation dependencies as possible. It 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 was first
released in 1995 and is widely used for developing applications for desktop, web, and mobile
devices. Java is known for its simplicity, robustness, and security features, making it a
popular choice for enterprise-level applications.
Java was developed by James Gosling at Sun Microsystems Inc in May 1995 and later
acquired by Oracle Corporation.

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.

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.

Types of Variables in Java


Now let us discuss different types of variables which are listed as follows:
1. Local Variables :: in method
2. Instance Variables: outside method specific for object
3. Static Variables: outside method with static keyword constant for all objects

Wrapper Classes in Java


Last Updated : 04 Oct, 2024

A Wrapper class in Java is a class whose object wraps or contains primitive data types. When
we create an object to a wrapper class, it contains a field and in this field, we can store
primitive data types. In other words, we can wrap a primitive value into a wrapper class
object. Let’s check on the wrapper classes in Java with examples:
Need of Wrapper Classes
There are certain needs for using the Wrapper class in Java as mentioned below:
1. They convert primitive data types into objects. Objects are needed if we wish to
modify the arguments passed into a method (because primitive types are passed by
value).
2. The classes in java.util package handles only objects and hence wrapper classes help
in this case also.
3. Data structures in the Collection framework, such as ArrayList and Vector, store only
objects (reference types) and not primitive types.
4. An object is needed to support synchronization in multithreading

Differences Between BufferedReader and Scanner


 BufferedReader is a very basic way to read the input generally used to read the
stream of characters. It gives an edge over Scanner as it is faster than Scanner
because Scanner does lots of post-processing for parsing the input; as seen in
nextInt(), nextFloat()
 BufferedReader is more flexible as we can specify the size of stream input to be read.
(In general, it is there that BufferedReader reads larger input than Scanner)
 These two factors come into play when we are reading larger input. In general, the
Scanner Class serves the input.
 BufferedReader is preferred as it is synchronized. While dealing with multiple threads
it is preferred.
 For decent input, and easy readability. The Scanner is preferred over BufferedReader.

Strings
. StringBuffer
StringBuffer is a peer class of String, it is mutable in nature and it is thread safe class , we
can use it when we have multi threaded environment and shared object of string buffer i.e,
used by mutiple thread. As it is thread safe so there is extra overhead, so it is mainly used for
multithreaded program.
3. StringBuilder
StringBuilder in Java represents an alternative to String and StringBuffer Class, as it creates a
mutable sequence of characters and it is not thread safe. It is used only within the thread ,
so there is no extra overhead , so it is mainly used for single threaded program
Pillar 1: Abstraction
Data Abstraction is the property by virtue of which only the essential details are displayed to
the user. The trivial or non-essential units are not displayed to the user. Ex: A car is viewed as
a car rather than its individual components.
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 object.
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the car speed 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 accelerators, brakes etc.
in the car. This is what abstraction is.
In Java, abstraction is achieved by interfaces and abstract classes. We can achieve 100%
abstraction using interfaces.
Pillar 2: Encapsulation
It is defined as the wrapping up of data under a single unit. It is the mechanism that binds
together the 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 the data in a class is hidden from any
other class and can be accessed only through any member function of the class in
which they are declared.
 In encapsulation, the data in a class is hidden from other classes, which is similar to
what data-hiding does. So, the terms “encapsulation” and “data-hiding” are used
interchangeably.
 Encapsulation can be achieved by declaring all the variables in a class as private and
writing public methods in the class to set and get the values of the variables.
Pillar 3: Inheritance
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. We are achieving inheritance by using extends keyword. Inheritance is also
known as “is-a” relationship.
Let us discuss some frequently used important terminologies:
 Superclass: The class whose features are inherited is known as superclass (also
known as base or parent class).
 Subclass: The class that inherits the other class is known as subclass (also known as
derived or extended 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.
Pillar 4: Polymorphism
It refers to the ability of object-oriented programming languages to differentiate between
entities with the same name efficiently. This is done by Java with the help of the signature
and declaration of these entities. The ability to appear in many forms is called
polymorphism.

Can a Java constructor be private?


Yes, a constructor can be declared private. A private constructor is used in restricting object
creation.
Why Do We Need Java Inheritance?
Inheritance is a key feature of OOP, allowing you to create flexible and reusable code.
Understanding how to implement it effectively can greatly improve the structure of your
programs. The Java Programming Course provides real-world examples to help you see how
inheritance plays out in large-scale Java applications.
 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 u
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 abstract method 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
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
What are Interfaces in Java?
The interface in Java is a mechanism to achieve abstraction. Traditionally, an interface could
only have abstract methods (methods without a body) and public, static, and final variables
by default. It is used to achieve abstraction and multiple inheritances in Java. In other words,
interfaces primarily define methods that other classes must implement. Java Interface also
represents the IS-A relationship.
If all abstract methods defined
a Simple way, the interface contains multiple abstract methods, so write the
implementation in implementation classes. If the implementation is unable to provide an
implementation of all abstract methods, then declare the implementation class with an
abstract modifier, and complete the remaining method implementation in the next created
child classes. It is possible to declare multiple child classes but at final we have completed
thDifference Between Abstract Class and Interface

Points Abstract Class Interface

Cannot be instantiated;
Specifies a set of methods a
contains both abstract (without
class must implement;
implementation) and concrete
methods are abstract by
methods (with
default.
Definition implementation)

Methods are abstract by


Can have both implemented
Implementation default; Java 8, can have
and abstract methods.
Method default and static methods.

class can inherit from only one A class can implement


Inheritance abstract class. multiple interfaces.

Methods and properties can


Methods and properties are
have any access modifier
implicitly public.
Access Modifiers (public, protected, private).

Variables Can have member variables Variables are implicitly public,


Points Abstract Class Interface

(final, non-final, static, non-


static, and final (constants)
static).

e implementation of all abstract methods.

Abstraction Encapsulation

Abstraction is process of hiding the Encapsulation is a process of binding data


implementation details and showing only and methods together in a single unit,
the functionality to the users. providing controlled access to data.

Main feature: reduce complexity,


promote maintainability, and also provide Main feature: data hiding, providing access
clear separation between the interface control and modularity.
and its concrete implementation.

In abstraction, problems are solved at the While in encapsulation, problems are solved
design or interface level. at the implementation level.

Whereas encapsulation can be implemented


We can implement abstraction using
using by access modifier i.e. private,
abstract class and interfaces.
protected and public and nested classes.

In abstraction, implementation While encapsulation uses private access


complexities are hidden using abstract modifier to hide the data and use getter and
classes and interfaces. setter to provide controlled access to data.

The objects that help to perform Whereas the objects that result in
abstraction are encapsulated. encapsulation need not be abstracted.

Abstraction provides access to specific Encapsulation hides data, preventing the


part of data. users from directly accessing it, (providing
controlled access) which is also known as
Abstraction Encapsulation

data hiding.

Abstraction focuses on “what” the object Encapsulation focuses on “How” the object
does . does it.

Example: A bank can be thought of as a fully


Example: CAR – the driver of the car only encapsulated class that provides access to
needs to know how to drive it. Not how the customers through various methods
its engine and the gear box and other (getters and setters). Rest of the data inside
internal components work. bank is hidden to protect from outside
world.

hat is a Singleton class?


As the name implies, a class is said to be singleton if it limits the number of objects of that
class to one.
3. Difference Between Instance method vs Static method
 Instance method can access the instance methods and instance variables directly.
 Instance method can access static variables and static methods directly.
 Static methods can access the static variables and static methods directly.
 Static methods can’t access instance methods and instance variables directly. They
must use reference to object. And static method can’t use this keyword as there is no
instance for ‘this’ to refer to.

et’s study these parts of memory area in detail:


Heap :
 It is a shared runtime data area and stores the actual object in a memory. It is
instantiated during the virtual machine startup.
 This memory is allocated for all class instances and array. Heap can be of fixed or
dynamic size depending upon the system’s configuration.
 JVM provides the user control to initialize or vary the size of heap as per the
requirement. When a new keyword is used, object is assigned a space in heap, but
the reference of the same exists onto the stack.
 There exists one and only one heap for a running JVM process.
Scanner sc = new Scanner(System.in);
The above statement creates the object of Scanner class which gets allocated to heap
whereas the reference ‘sc’ gets pushed to the stack.
Note: Garbage collection in heap area is mandatory.
Method Area:
 It is a logical part of the heap area and is created on virtual machine startup.
 This memory is allocated for class structures, method data and constructor field data,
and also for interfaces or special method used in class. Heap can be of fixed or
dynamic size depending upon the system’s configuration.
 Can be of a fixed size or expanded as required by the computation. Needs not to be
contiguous.
Note: Though method area is logically a part of heap, it may or may not be garbage
collected even if garbage collection is compulsory in heap area.
JVM Stacks:
 A stack is created at the same time when a thread is created and is used to store data
and partial results which will be needed while returning value for method and
performing dynamic linking.
 Stacks can either be of fixed or dynamic size. The size of a stack can be chosen
independently when it is created.
 The memory for stack needs not to be contiguous.
Native method Stacks:
Also called as C stacks, native method stacks are not written in Java language. This memory
is allocated for each thread when its created. And it can be of fixed or dynamic nature.
Program counter (PC) registers:
Each JVM thread which carries out the task of a specific method has a program counter
register associated with it. The non native method has a PC which stores the address of the
available JVM instruction whereas in a native method, the value of program counter is
undefined. PC register is capable of storing the return address or a native pointer on some
specific platform.
Working of a Garbage Collector:
 JVM triggers this process and as per the JVM garbage collection process is done or
else withheld. It reduces the burden of programmer by automatically performing the
allocation or deallocation of memory.
 Garbage collection process causes the rest of the processes or threads to be paused
and thus is costly in nature. This problem is unacceptable for the client but can be
eliminated by applying several garbage collector based algorithms. This process of
applying algorithm is often termed as Garbage Collector tuning and is important for
improving the performance of a program.
 Another solution is the generational garbage collectors that adds an age field to the
objects that are assigned a memory. As more and more objects are created, the list
of garbage grows thereby increasing the garbage collection time. On the basis of how
many clock cycles the objects have survived, objects are grouped and are allocated
an ‘age’ accordingly. This way the garbage collection work gets distributed.
 In the current scenario, all garbage collectors are generational, and hence, optimal.
Note: System.gc() and Runtime.gc() are the methods which requests for Garbage collection
to JVM explicitly but it doesn’t ensures garbage collection as the final decision of garbage
collection is of JVM only.
Key Points:
 We receive the corresponding error message if Heap-space is entirely full, java.
lang.OutOfMemoryError by JVM.
 This memory allocation scheme is different from the Stack-space allocation, here no
automatic de-allocation feature is provided. We need to use a Garbage collector to
remove the old unused objects in order to use the memory efficiently.
 The processing time(Accessing time) of this memory is quite slow as compared to
Stack-memory.
 Heap memory is also not as threaded-safe as Stack-memory because data stored in
Heap-memory are visible to all threads.
 The size of the Heap-memory is quite larger as compared to the Stack-memory.
 Heap memory is accessible or exists as long as the whole application(or java
program) runs.
CPP
i
hat are Java Exceptions?
In Java, Exception is an unwanted or unexpected event, which occurs during the execution
of a program, i.e. at run time, that disrupts the normal flow of the program’s instructions.
Exceptions can be caught and handled by the program. When an exception occurs within a
method, it creates an object. This object is called the exception object. It contains
information about the exception, such as the name and description of the exception and the
state of the program when the exception occurred.
Major reasons why an exception Occurs
Java throws
throws is a keyword in Java that is used in the signature of a method to indicate that this
method might throw one of the listed type exceptions. The caller to these methods has to
handle the exception using a try-catch block.

THREADS

ultithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread. So,
threads are light-weight processes within a process.
Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface
Thread creation by extending the Thread class
We create a class that extends the java.lang.Thread class. This class overrides the run()
method available in the Thread class. A thread begins its life inside run() method. We create
an object of our new class and call start() method to start the execution of a thread. Start()
invokes the run() method on the Thread object.

You might also like