JAVA
Java, developed by James Gosling and his team at Sun Microsystems, has a history dating back to the early 1990s. Here's a brief overview of the key milestones in Java's history:
Version | Release Date | Code Name |
---|---|---|
JDK 1.0 | 1996-01-23 | Oak (changed to Java) |
JDK 1.1 | 1997-02-19 | Sparkler |
JDK 1.2 | 1998-12-08 | Playground |
JDK 1.3 | 2000-05-08 | Kestrel |
JDK 1.4 | 2002-02-06 | Merlin |
JDK 5.0 | 2004-09-30 | Tiger |
JDK 6 | 2006-12-11 | Mustang |
JDK 7 | 2011-07-28 | Dolphin |
JDK 8 | 2014-03-18 | Spider |
JDK 9 | 2017-09-21 | Project Jigsaw |
JDK 10 | 2018-03-20 | 18.3 (No Code Name) |
JDK 11 | 2018-09-25 | 18.9 (No Code Name) |
A class is a blueprint for creating objects. It defines the properties and behaviors common to all objects of a certain type. In other words, a class describes the attributes and methods that an object will have, but it doesn't actually create the objects themselves. Classes are often compared to templates or molds from which objects are created.
An object is an instance of a class. It represents a real-world entity and encapsulates both data (attributes) and behaviors (methods) defined by its class.
extend
karnahttps://www.geeksforgeeks.org/difference-between-compile-time-and-run-time-polymorphism-in-java/
Function having same name, but it performs different operations.
For example : If we use print operation then, method for printing an image and document will be different.
@Override
use karke uska method ko override karna (@Override
use karna is not necessary))It refers to the bundling of data (attributes or variables) and methods (functions or procedures) that operate on the data into a single unit known as a class. Encapsulation helps in hiding the internal implementation details of an object and protecting its state from external interference.
In Java, encapsulation is achieved by declaring the fields of a class as private and providing public getter and setter methods to access and modify the values of these fields.
In this lecture we will learn:
- What is Abstraction?
- Abstract method in Java
- Abstract class in Java
- Abstract vs Concrete classes
#1
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
#2
Abstract method:-
- Instead of defining the method, we can declare the method.
- If we put a semicolon at the end of a method, it means that you only declare the method like:
public void drive();
- This method does not contain any features and you will not be able to create an object of it.
- You need to add an abstract keyword to only declare a method.
#3
Abstract class:-
- Abstract methods can only be defined in an abstract class.
- We need to add an abstract keyword before a class to make it an abstract class.
- Objects of an abstract class can not be created.
- If you are extending an abstract class, then it is compulsory to define all abstract methods.
- It is not necessary that an abstract class should have an abstract method.
- Abstract class can have an abstract or a normal method or both.
- An abstract class can have more than one abstract method.
#4
Concrete class: A class other than an abstract class is known as a concrete class.
- An object of a concrete class can be created.
package com.hitarth.packages;
/* ------------------------------------------------------ */
//superclass or parent class
class Calc {
public int add(int n1, int n2) {
return n1 + n2;
}
public int sub(int n1, int n2) {
return n1 - n2;
}
}
//subclass or child class
class AdvCalc extends Calc
{
public int mult(int n1, int n2)
{
return n1*n2;
}
}
/* ------------------------------------------------------ */
public class _07_Inheritance {
public static void main(String[] args) {
Calc obj = new Calc();
int r1 = obj.add(1,2);
System.out.println(r1); // → 3
AdvCalc obj2 = new AdvCalc();
int r2 = obj2.mult(2,3);
int r3 = obj2.add(1,3);
System.out.println(r2); // → 6
System.out.println(r3); // → 4
}
}
AdvCalc
IS-A
(read as "is a") Calc
: means that AdvCalc
is a child class and Calc
is a parent class.
IS-A
relationshipexample khud se padh lena bhai
example khud se padh lena bhai
When any two inheritance types are combined :
Only 1,2,3 types of inheritances are used in JAVA.
Try Block:
try
block encloses the code that may generate exceptions.catch
blocks.try
block, the execution of the try
block is halted, and the control is transferred to the corresponding catch
block.Catch Block:
catch
block catches and handles exceptions thrown within the associated try
block.catch
block specifies the type of exception it can handle, allowing for selective exception handling.catch
block is executed.catch
block matches the thrown exception, it propagates up the call stack, potentially halting the program if unhandled.try {
// Code that may throw exceptions
} catch (ExceptionType1 e1) {
// Exception handling for ExceptionType1
} catch (ExceptionType2 e2) {
// Exception handling for ExceptionType2
} finally {
// Optional: Code that always executes, regardless of exceptions
}
Finally Block:
finally
block can be used after all catch
blocks.finally
block executes whether an exception occurs or not.Example:
try {
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("An error occurred: " + e.getMessage());
} finally {
System.out.println("This code always executes.");
}
public class Example {
public static void main(String[] args) {
try {
// Creating and throwing a NullPointerException with a "custom" esxception explicitly
throw new NullPointerException("Custom NullPointerException message");
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException: " + e.getMessage());
}
}
}
Difference between throw
and throws
:
throw:
throw
is a keyword used to explicitly throw an exception from within a method or block of code.throw
, you can throw both built-in exceptions provided by Java (such as NullPointerException
, IllegalArgumentException
, etc.) and custom exceptions that you define in your code.throw
an exception, you are responsible for creating and specifying the exception object to be thrown.Example:
public void method() {
if (condition) {
throw new SomeException("Custom message");
}
}
throws:
throws
is used in the method declaration to indicate that the method may throw certain types of exceptions during its execution.throws
, you are declaring the exceptions that can be thrown by a method, allowing the caller of the method to handle those exceptions.Example:
public void method() throws SomeException {
// Method code that may throw SomeException
}
The caller of this method would then need to handle the SomeException
either by catching it or declaring it to be thrown further.
In summary, throw
is used to throw an exception explicitly within a method, while throws
is used to declare the types of exceptions that a method might throw, allowing the caller to handle them appropriately.
In Java, you can create your own custom exceptions by extending the built-in Exception
class or one of its subclasses. Here's how you can create and use a custom exception:
Create Custom Exception Class:
First, create a new class that extends Exception
or one of its subclasses. You can define constructors and methods specific to your custom exception.
public class CustomException extends Exception {
public CustomException() {
super("Custom exception message");
}
public CustomException(String message) {
super(message);
}
}
Throw Custom Exception:
In your code, when you encounter a situation that warrants throwing your custom exception, use the throw
keyword followed by an instance of your custom exception class.
public void someMethod() throws CustomException {
// Condition that triggers the exception
if (condition) {
throw new CustomException("Custom message for the exception");
}
}
Handle Custom Exception:
When calling the method that can throw your custom exception, handle it using a try-catch
block.
try {
someObject.someMethod();
} catch (CustomException e) {
// Handle the custom exception
System.out.println("Custom exception occurred: " + e.getMessage());
}
Putting it all together, here's an example demonstrating the creation, throwing, and handling of a custom exception:
// CustomException.java
public class CustomException extends Exception {
public CustomException() {
super("Custom exception message");
}
public CustomException(String message) {
super(message);
}
}
// Example.java
public class Example {
public void someMethod() throws CustomException {
// Simulating a condition that triggers the custom exception
boolean condition = true;
if (condition) {
throw new CustomException("Custom message for the exception");
}
}
}
// Main.java
public class Main {
public static void main(String[] args) {
Example example = new Example();
try {
example.someMethod();
} catch (CustomException e) {
System.out.println("Custom exception occurred: " + e.getMessage());
}
}
}
In this example, we define a custom exception CustomException
and then throw and handle it in the Example
and Main
classes, respectively.
Multitasking in Java:
Thread
class or implementing the Runnable
interface.Multiprocessing in Java:
Multithreading in Java:
Thread
class and the java.util.concurrent
package.Thread
class or implementing the Runnable
interface and then starting these threads using the start()
method.ExecutorService
, ThreadPoolExecutor
, and ConcurrentHashMap
to simplify multithreaded programming and manage thread execution, synchronization, and communication.Here's a simple example demonstrating multithreading in Java:
class MyThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try {
Thread.sleep(1000); // Simulate some work
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start(); // Start the first thread
thread2.start(); // Start the second thread
}
}
This example creates two threads (thread1
and thread2
) that execute concurrently, each printing numbers from 0 to 4 with a 1-second delay between each iteration.
In summary:
These concepts are fundamental to understanding how modern computer systems handle concurrent execution and optimize resource utilization.
Thread synchronization is the process of controlling the access to shared resources by multiple threads to prevent data inconsistency and race conditions. In Java, synchronization can be achieved using synchronized blocks or methods, locks, or other concurrency utilities.
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
}
Concurrent Collections:
Java provides a set of thread-safe collection classes in the java.util.concurrent package, known as concurrent collections. These collections are designed to be used in multithreaded environments and provide better performance and scalability compared to traditional synchronized collections.
Examples of concurrent collections include ConcurrentHashMap, ConcurrentLinkedQueue, and CopyOnWriteArrayList.
ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("one", 1);
map.put("two", 2);
These concurrent collections offer thread-safe operations without the need for explicit synchronization, making them suitable for concurrent programming.
Understanding threads, thread management, synchronization, and concurrent collections is essential for developing efficient and scalable multithreaded Java applications. Proper synchronization ensures data consistency and avoids race conditions, while concurrent collections provide efficient access to shared data in multithreaded environments.