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

Java

The document provides an overview of Java programming concepts, including classes, objects, memory allocation, and the Java execution environment (JDK, JRE, JVM). It discusses key features such as abstraction, encapsulation, inheritance, polymorphism, and various Java keywords and constructs like final, finally, and constructors. Additionally, it covers file handling, threading, and the significance of method overloading and overriding in Java.

Uploaded by

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

Java

The document provides an overview of Java programming concepts, including classes, objects, memory allocation, and the Java execution environment (JDK, JRE, JVM). It discusses key features such as abstraction, encapsulation, inheritance, polymorphism, and various Java keywords and constructs like final, finally, and constructors. Additionally, it covers file handling, threading, and the significance of method overloading and overriding in Java.

Uploaded by

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

BY

Prof. Sucheta Chandra


BCA DEPT. IEM
CLASS AND OBJECT
A class in Java is a blueprint
or template that defines the
structure and behavior (fields
and methods) of objects.
*************************************
An object is an instance of a
class, created using the class
definition, containing actual
values and allowing
interaction with the class's
methods and properties.
WHY NO POINTERS IN JAVA?
ANY ALTERNATE OPTION ??
Direct manipulation of memory addresses through pointers is not allowed.
Java was designed with a focus on security and simplicity, aiming to
prevent common programming errors such as memory corruption and
pointer-related bugs.
However, Java does have references, which are similar to pointers in
concept but operate in a safer and more controlled manner.References are
declared using the class name followed by the variable name. They are initialized
using the new keyword to create an object:

MyClass obj = new MyClass();


Primitive types in Java
are basic data types
that are predefined by
the language and are
directly supported by
the Java programming
language itself

Non-primitive types
(also known as
reference types) are
derived from classes
and are not predefined
by the language itself..
What is a ClassLoader?

A classloader in Java is a subsystem of Java Virtual Machine, dedicated


to loading class files when a program is executed; ClassLoader is the
first to load the executable file.Java has Bootstrap, Extension, and
Application classloaders.
5 MEMORY ALLOCATIONS IN JAVA
Class Memory: Stores class-level data, including class
methods and variables.

Heap Memory - Stores objects created in Java programs. It's


managed by the garbage collector for automatic memory
management.

Stack Memory - Stores method calls, local variables, and


partial results. Each thread in Java has its own stack

Program Counter-Memory - Holds the address of the


currently executing instruction in the thread.
Native Method Stack Memory- Stores native method
WORA - JAVA &
INDEPENDENT JAVA
Write Once, Run Anywhere:
The key advantage of Java's platform independence is that once
you compile Java source code into bytecode, one can run it on
any platform that supports Java without needing to recompile the
code. This is often summarized as "write once, run anywhere."
DEFINING
JIT JDK,JRE,JVM,JIT
DEFINITION JDK COMPONENTS
● Software development environment ● an interpreter/loader (java)
for developing Java applications. ● compiler (javac)
● an archiver (jar)
● It physically exists. Contains JRE ● documentation generator
and JVM internally (Javadoc).

JDK VERSIONS
JDK 1.0 (January 23, 1996) (The initial
release of JDK)

Java SE 18 (Ongoing version)


JDK
JRE COMPONENTS
● Java Runtime Environment itself
(java command-line tool),
DEFINITION ● libraries (rt.jar)
● It is responsible for executing Java ● configuration files (java.security,
bytecode, which is the compiled deployment.properties, etc.)
format of Java programs.
● Contains class libraries, jar files and
other components necessary to run
Java applications.
● JRE provides the runtime
environment required to execute
Java applications.
JRE
JVM COMPONENTS
. DEFINITION
It's a crucial component of the Java ● Class Loader
Runtime Environment (JRE) and ● Bytecode Verifier
Java Development Kit (JDK), ● Interpreter/Just-in-Time (JIT)
Compiler
Responsible for executing Java ● Garbage Collector
bytecode. ● Execution Engine.

Versions

● Oracle HotSpot JVM (the most


widely used)
● OpenJ9 (from Eclipse) JVM
JIT
Optimization:
JIT compilers analyze sections of bytecode that
are frequently executed or are performance-
critical. They apply optimizations to this code to
generate highly optimized native machine code
tailored to the specific characteristics of the
underlying hardware and runtime environment.
Does both jre and jvm help in
bytecode execution ?
JVM is the core engine that executes Java
bytecode, while JRE provides the overall runtime
environment that includes the JVM and
necessary runtime libraries. Together, they
enable the execution of Java bytecode and
provide the platform independence and runtime
support that Java applications require.
LET’S SEE THE REAL WORLD EXAMPLES
1. Example: A coffee machine Explanation : Hides its functionality within a user-friendly
interface. Users interact with it through buttons or a touchscreen to select the type of coffee
(e.g., espresso, latte) and other options (e.g., milk froth, temperature).
2.Example: Online banking system. Explanation: Consider an online banking system
where customers can perform various transactions such as checking their balance,
transferring money, and paying bills. The user interacts with a simplified interface (website or
mobile app) that abstracts away the complexities of banking processes and backend
systems.
3.Example: Vehicles in a transportation system.Explanation: In a transportation system,
vehicles can be categorized into various types such as cars, buses, trucks, and motorcycles.
These vehicles share common attributes and behaviors, such as having wheels, an engine,
and the ability to move.
4.Example: Shape drawing in a graphics application. Explanation: In a graphics
program, shapes like circles, squares, and triangles are all drawn using a "draw" method.
However, each shape implements this method differently according to its own unique
requirements (e.g., a circle draws a curved outline, while a square draws straight lines).
Abstraction is a mechanism in
Encapsulation provides data
which complex systems can be
hiding, which means that the simplified by hiding
internal implementation details of a unnecessary details. In Java,
class are hidden from the outside abstraction can be achieved
world. EX- 1 through abstract classes and
interfaces. EX - 2

Inheritance is a mechanism in Polymorphism is a mechanism in


which one class inherits which a single method can have
properties and methods from
different forms or
another class. The class that
implementations. Polymorphism
inherits is called the subclass or
derived class, and the class that is
can be achieved through method
inherited from is called the overloading or method
superclass or base class. EX- 3 overriding. EX- 4
Method Overloading
● Definition: Method overloading in Java allows a class to have multiple
methods with the same name but different parameters.
● Purpose: It provides flexibility by enabling a class to define multiple
methods with similar functionalities but different parameter types or
numbers.
● Key Points:
○ Methods must have the same name.
○ Methods must have different parameter lists (different number of
parameters, or parameters of different types).
○ Return type may or may not be different.
○ Overloading is determined at compile-time based on the method
signature (name and parameters).
Method Overriding
● Definition: Method overriding in Java occurs when a subclass
provides a specific implementation of a method that is already
defined in its superclass.
● Purpose: It allows a subclass to provide its own implementation
of a method defined in the superclass, enabling polymorphic
behaviour.
● Key Points:
○ Methods have the same name, parameters, and return type
○ The @Override annotation is used to indicate that a method is being
overridden.
○ Overriding is determined at runtime (dynamic binding)
Public: Accessible from any other class, regardless of the package

Private: Accessible only within the same class. It is not visible to any
other class, even if they are in the same package.

Protected: Access specifier allows access to members within the same package and by
subclasses, whether they are in the same package or a different package. However, non-
subclasses in different packages cannot access protected members to maintain
encapsulation and prevent unintended dependencies between unrelated classes.

Default (Package-private): Accessible within the same package but


not outside it.
PSVM - MEANING
Public: It means the main method can be accessed (called) from outside the
class by the Java system.
static: This means the main method belongs to the class itself, not to any
specific object of the class. It allows the Java Virtual Machine (JVM) to call
the main method without creating an instance (object) of the class.
void: It indicates that the main method does not return any value after it
finishes executing.
main: This is the name of the method. When you run a Java program, the
JVM looks for this method as the entry point of the program.
String[] args: It's a parameter that the main method can accept. It's an array
(list) of strings where you can pass information (arguments) to your
program from the command line when you run it.
Why (String[ ] args)?
The main method in Java requires a String[] parameter because
it is the standard way for the Java Virtual Machine (JVM) to pass
command-line arguments to the application. This convention allows
the JVM to provide an entry point for the program, enabling it to
receive and process any command-line arguments specified by the
user when the program is launched.
Explain final keyword Java - 1
final is a keyword used to declare constants, prevent method
overriding, and restrict inheritance of classes.
● When applied to a variable, it means the variable's
value cannot be changed once initialized.
● When applied to a method, it means the method
cannot be overridden by subclasses.
● When applied to a class, it means the class cannot be
subclassed (cannot have child classes).
Explain finally (ftc-block) Java-2
In Java, the finally block is used in deal with try and catch blocks to ensure that
certain code statements are always executed, regardless of whether an exception is
thrown or not. Here's an explanation of how finally works and its key features:

Purpose of finally Block:


The finally block is used to execute important code such as cleanup operations,
releasing resources (like closing files or database connections), or ensuring final
actions are performed, regardless of whether an exception is thrown or not. This
ensures that critical tasks are always completed, even if an unexpected error occurs
during execution.
import java.io.*;

public class FinallyExample {


public static void main(String[] args) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("example.txt"));
String line = reader.readLine();
System.out.println("First line of the file: " + line);
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
finally {
try {
if (reader != null) {
reader.close(); // Close the BufferedReader
}
} catch (IOException e) {
System.err.println("Error closing reader: " + e.getMessage());
}
}
}
}
Explain finalize(GC) in Java-3
In Java, the finalize() method is a special method provided by the
Object class. Its primary purpose is to perform cleanup operations on an
object before it is garbage collected by the Java Virtual Machine (JVM).
Here’s a detailed explanation of how finalize() works and its implications:
The JVM calls finalize() on an object when it determines that there are
no more references to the object, meaning the object is eligible for
garbage collection.
It's important to note that the timing of when finalize() is called is not
guaranteed and is JVM-dependent. Objects may not be garbage collected
immediately after becoming unreachable, so there could be a delay.
CONSTRUCTOR
● To initialize an object
● Having same name as class name
● Every java class has a constructor
● During object creation constructor is
automatically called
● Has no return type
● To refer to the current instance of the class we
use the keyword “this”
Multi Threading
IS A PROCESS TO
EXECUTE MULTIPLE
THREADS AT THE SAME
TIME WITHOUT
DEPENDING ON THE
OTHER THREADS.
Thread and how to create thread
Predefined class available in Thread States: Threads can be in various
java.lang package states like New, Runnable, Blocked,
Waiting, Timed Waiting, and
It is the smallest unit of Terminated.
execution within a process. It Thread Synchronization: Ensures data
represents a single flow of consistency and prevents race conditions
control within a program that using the synchronized keyword or locks
can execute independently. (Lock interface).
Thread Communication: Threads can
communicate and coordinate using methods
like wait(), notify(), and notifyAll() from
Creating a Thread: the Object class.
1 Extending thread class Thread Pools: Managed by
2.Runnable interface creation. ExecutorService and
ThreadPoolExecutor, thread pools
optimize performance by reusing threads for
executing tasks.
CLASS TYPES AND
LOOPS
Regular Classes- Regular classes are the most common type in Java that can
have fields, methods, constructors, and can be instantiated to create objects.

Abstract Classes - Abstract classes cannot be instantiated directly and may


contain abstract methods (methods without a body) that must be implemented by
subclasses. They can also have concrete methods and field

Interface - Interfaces define a contract for classes to implement. They can contain
method signatures (without method bodies), default methods, static methods,
constants (public static final fields), and nested types (interfaces or classes).

Nested Classes- Nested classes are classes defined within another class. They
can be static or non-static (inner classes)
Final Classes - Final classes cannot be subclassed (extended). They are typically
used when inheritance is not intended.

Utility Classes - Utility classes are typically final with private constructors and
contain static methods that provide commonly used functions or constants.
LOOPS :QUICK NOTES
● for Loop: Use when the number of iterations is known.
● while Loop: Use when the condition depends on a
state that may change during execution.
● do-while Loop: Use when you need to execute the
block of code at least once, regardless of the condition.
● foreach Loop: Use for iterating over collections and
arrays without worrying about indices.Simplifies
iterating over collections and arrays.
What is an Association?

An Association can be defined as a relationship that has no ownership


over another. For example, In a school scenario, a teacher and a
student have an association where a teacher teaches multiple
students, and each student is taught by one teacher.

What do you mean by aggregation?

The term aggregation refers to the relationship between two classes


best described as a “whole/part” and “has-a” relationship. This kind is
the most specialized version of an association relationship. It contains
the reference to another class and is said to have ownership of that
class. Example- A car has an aggregation relationship with an engine.
FILE
HANDLING IN
JAVA
DEFINITION
In Java, with the help of File Class, we can work with files. This File Class is inside the java.io
package. The File class can be used by creating an object of the class and then specifying
the name of the file.
Why File Handling is Required?
• File Handling is an integral part of any programming language as file handling enables us
to store the output of any particular program in a file and allows us to perform certain
operations on it.
• In simple words, file handling means reading and writing data to a file.
Streams in Java
• In Java, a sequence of data is
known as a stream.
• This concept is used to perform I/O
operations on a file
S.No. Method Return Type Description
1. canRead() Boolean The canRead() method is
used to check whether we
can read the data of the file
or not.
2. createNewFile() Boolean The createNewFile() method
is used to create a new
empty file.
3. canWrite() Boolean The canWrite() method is
used to check whether we
can write the data into the
file or not.
4. exists() Boolean The exists() method is used
to check whether the
specified file is present or
not.
5. delete() Boolean The delete() method is used
to delete a file.
6. getName() String The getName() method is
used to find the file name.
7. getAbsolutePath() String The getAbsolutePath() meth
od is used to get the
absolute pathname of the
file.
8. length() Long The length() method is used
to get the size of the file in
bytes.
9. list() String[] The list() method is used to
get an array of the files
FEW STRING MANIPULATIONS
Use StringBuilder or StringBuffer for String StringBuilder sb = new
Concatenation StringBuilder();
Avoid using the “+” operator repeatedly when sb.append("Hello");
concatenating multiple strings. This can create sb.append(" ");
unnecessary string objects, leading to poor sb.append("World");
performance. Instead, use StringBuilder (or String result = sb.toString(); //
StringBuffer for thread safety) to efficiently "Hello World"
concatenate strings.

Split Strings String str = "Java is awesome";


Use the split() method to split a string into an array String[] parts = str.split(" "); //
of substrings based on a specified delimiter. ["Java", "is", "awesome"]
1.String Compression: Implement a method to perform basic string compression using the counts of repeated
characters. If the "compressed" string would not become smaller than the original string, your method should
return the original string.

Example: Input: “ccllaaas"


Output: “c2l2a3s1"

2.Anagrams Check: Write a function to check if two strings are anagrams of each other. Anagrams are strings
that contain the same characters with the same frequencies.

Example: Input: "listen", "silent"


Output: true

3.String Permutations: Implement a method to print all permutations of a given string. Assume all characters in
the string are unique.

Example: Input: "abc"


Output: "abc", "acb", "bac", "bca", "cab", "cba“
Given an array of integers ‘nums’ and an integer target, return indices of the two numbers
such
that they add up to target. You may assume that each input would have exactly one solution,
and you may not use the same element twice.

Valid Parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[', ']', determine if the input string is valid.
An input string is valid if:
1.Open brackets must be closed by the same type of brackets.
2.Open brackets must be closed in the correct order.

Write a Java program that checks if a given range of numbers (say between 1 and 1000) are prime using
multiple threads. Each thread should handle a subset of the numbers and report which numbers within its
subset are prime. Finally, collect and print all prime numbers found.

You might also like