Hja1) Java
Hja1) Java
Hja1) Java
• Big Data: Java is used in big data processing frameworks like Apache Hadoop.
• Compile:
Use the javac compiler to convert the source code into bytecode.
• Load:
The class loader loads the bytecode into memory.
• Verify:
The bytecode verifier checks the code for integrity and security.
• Execute:
The Java Virtual Machine (JVM) executes the bytecode.
• Unload:
When the program finishes, the class unloader unloads the classes from memory.
MEMORY TYPES IN JAVA
Class (Method) Area :
The class method area is the memory block that stores the class code, variable code(static variable, runtime constant), method code, and
the constructor of a Java program.
Class
The Heap area is the memory block where objects are created or objects are stored.
Heap memory allocates memory for class interfaces and arrays
Stack
Each thread has a private JVM stack, created at the same time as the thread.
It is used to store data and partial results which will be needed.
Each thread in a Java program has its own stack, which stores local variables and partial results.
Heap:
The heap is the runtime data area where objects are allocated.
It is divided into two regions: the Young Generation and the Old Generation.
The Young Generation is further divided into three areas: Eden space, and two survivor spaces (S0 and S1).
Garbage collection primarily occurs in the Young Generation, where short-lived objects are collected.
JAVA PROGRAMMING ENVIRONMENT
1. How to Install & set Path.
4. Runtime Exception.
6. Platform Independent.
Data Types
Java supports primitive data types like integers, floating-point numbers, characters, and boolean values, along with non primitive data types like
Class, Interface,String, arrays and objects.
Byte:
Size: 1byte (8bits)
Maxvalue: +127
Minvalue:-128
• Example:
byte b=10;
byte b2=130;//C.E:possible loss of precision
byte b=10.5;//C.E:possible loss of precision
CODING STANDARD
• Whenever we are writing any component the name of the component should reflect the purpose or functionality.
Like package, classname, methodname
Object:
• An instance of a class. Represents a real-world entity and has a state and behavior.
Constructor:
• A special method that is called when an object is created.
Types of Constructors:
• Parameterized Constructor
Short:
The most rarely used data type in java is short.
Size: 2 bytes
Range: -32768 to 32767
Example :
short s=130;
short s=32768;//C.E:possible loss of precision
short s=true;//C.E:incompatible types
Int:
This is most commonly used data type in java.
Size: 4 bytes
Range:-2147483648 to 2147483647
• Example:
int i=130;
int i=10.5;//C.E:possible loss of precision
int i=true;//C.E:incompatible types
long:
Whenever int is not enough to hold big values then we should go for long data type.
Example:
To hold the no. Of characters present in a big file int may not enough hence the return type of length() method is long.
long l=f.length(); //f is a file
Size: 8 bytes
Float
If we want to 5 to 6 decimal places of accuracy then we should go for float.
We can specify explicitly floating point literal as double type by suffixing with d or D.
Size:4 bytes. float follows single precision.
Example :float height = 167.7f (valid)
float f=123.456;//C.E:possible loss of precision(invalid)
double d=123.456;(valid)
Double
If we want to 14 to 15 decimal places of accuracy then we should go for double.
Size:8 bytes. double follows double precision.
Example : double price = 987.90D / double price = 987.90d / double price = 987.90
Char :
In java we are allowed to use any worldwide alphabets character and java is Unicode based to represent all these characters one byte is not
enough compulsory we should go for 2 bytes.
Size: 2 bytes
Range: 0 to 65535
Example:
char ch=97;(valid)
char ch2=65536;//C.E:possible loss of precision
Boolean
Size: Not applicable (virtual machine dependent)
Range: Not applicable but allowed values are true or false.
Which of the following boolean declarations are valid?
Example 1:
boolean b=true;
boolean b=True;//C.E:cannot find symbol
boolean b="True";//C.E:incompatible types
boolean b=0;//C.E:incompatible types
LITERALS
• Integer Literals: 10, 0x1A, 077.
static variables it is not required to perform initialization explicitly, JVM will always provide default values.
Static variables will be crated at the time of class loading and destroyed at the time of class unloading hence the scope of the static variable is exactly same as the
scope of the .class file.
Static variables will be stored in method area. Static variables should be declared with in the class directly but outside of any method or block or constructor.
Static variables can be accessed from both instance and static areas directly.
We can access static variables either by class name or by object reference but usage of class name is recommended.Example :
3) Local Variable
• The local variables will be created as part of the block execution in which it is declared and destroyed once that block execution completes. The local
variables will be stored on the stack.
• scope of the local variables is exactly same as scope of the block in which we declared.
• Example :
4) final variable
5) transient variable
Final Modifier:
• Final is the modifier applicable for classes, methods and variables.
• Final Methods:
Whatever the methods parent has by default available to the child.
If the child is not allowed to override any method, that method we have to declare with final in parent class. That is final methods cannot
overridden.
• The main advantage of final keyword is we can achieve security. Whereas the main disadvantage is we are missing the key benefits of oops
• It is never recommended to use because it reduces readability of the code. ( import java.util.*; )
• This type of import is highly recommended to use because it improves readability of the code. Import java.util.arraylist;
• Package structure
• com.icicibank.loan.houseingloadn.Account
• com.healthcare.doctor.doctorappointment
• Rule of the package - package name start with lowercase (pack com.class)
MAIN METHOD IN JAVA
Whether the class contains main() method or not and whether it is
properly declared or
not these checking’s are not responsibilities of the compiler, at
runtime JVM is
responsible for this. If jvm unable to find the required main()
method then we will get
runtime exception saying NoSuchMethodError: main.
ARRAY
• An array is a collection of elements of the same type stored in contiguous memory locations.
• The variables in the array are ordered, and each has an index beginning with 0.
• Arr = new int[5]; //allocating memory for 5 integers.also int[] myNum = {10, 20, 30, 40};
• int[] a;//valid
• int[5] a;//invalid
If we are taking array size with -ve int value then we will get runtime exception saying NegativeArraySizeException.
The allowed data types to specify array size are byte, short, char, int. By mistake if we are using any other type we will get compile time error.
The maximum allowed array size in java is maximum value of int size [2147483647].
Example:
int[] a1=new int[2147483647];(valid)
int[] a2=new int[2147483648];//C.E:integer number too large: 2147483648(invalid)
INTERFACE
Introduction
• If we don’t’ know anything about implementation just we have requirement specification then we should go for interface.Every method present
inside interface
is always public and abstract whether we are declaring or not.We can’t declare interface methods with the modifiers private, protected, final,
static, synchronized, native, strictfp.Every interface variable is always
public static final whether we are declaring or not.Inside interface we can’t take constructor.
• Example1: Sun people responsible to define JDBC API and database vendor will provide implementation for that.
• ATM GUI screen describes the set of services what bank people offering, at the same time the same GUI screen the set of
services what customer his excepting hence this GUI screen acts as a contract between bank and customer.
• Def3: Inside interface every method is always abstract whether we are declaring or not hence interface is considered as
100% pure abstract class.
• Any service requirement specification (SRS) or any contract between client and
service provider or 100% pure abstract classes is considered as an interface.
TYPE CASTING
Auto up casting ( implicit casting) - compiler (JVM) converts
Float to int
OPERATORS IN JAVA
Arithmetic Operators:
• + (Addition)
• - (Subtraction)
• * (Multiplication)
• / (Division)
• % (Modulus)
• int a = 10, b = 3;
System.out.println("Sum: " + (a + b));
System.out.println("Difference: " + (a - b));
System.out.println("Product: " + (a * b));
System.out.println("Quotient: " + (a / b));
System.out.println("Remainder: " + (a % b));
Comparison Operators:
• == (Equal to)
• int x = 5, y = 10;
• || (Logical OR)
• ! (Logical NOT)
• += (Addition assignment)
• -= (Subtraction assignment)
• *= (Multiplication assignment)
• /= (Division assignment)
• %= (Modulus assignment)
• int num = 5;
num += 3; // num = num + 3;
System.out.println(num); // 8
Increment and Decrement Operators:
• ++ (Increment)
• -- (Decrement)
counter--; // Decrement by 1
System.out.println(counter); // 10
• System.out.println(result); // Odd
FLOW CONTROL IN THE JAVA
if-else statement is used for decision-making. It executes a block of code if a specified condition is true, and another block if the condition is false.
Example :
if (num > 0) {
System.out.println("Positive number");
} else {
System.out.println("Non-positive number");
}
1 SELECTION STATEMENT -
switch
The switch statement is used for multiple branching based on the value of an expression..
Example :
int dayOfWeek = 3;
String dayName;
switch (dayOfWeek) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
// ... other cases
default:
dayName = "Invalid day";
}
System.out.println("Day: " + dayName);
2 ITERATIVE STATEMENT
while loop
The while loop repeatedly executes a block of code as long as a specified condition is true.
Example :
int i = 0;
while (i < 5) {
System.out.println("Value of i: " + i);
i++;
}
do-while loop
Similar to while loop, but it ensures that the block of code is executed at least once before checking the condition.
int j = 0;
do {
System.out.println("Value of j: " + j);
j++;
} while (j < 5);
2 ITERATIVE STATEMENT
For loop
The for loop provides a concise way to iterate over a range of values.
for-each loop:
return statement
• Exits the current method and returns a value to the calling code.
• Exception handling in Java is a mechanism that allows developers to deal with runtime errors or exceptional situations in a structured and controlled way.
• Java has a comprehensive exception-handling mechanism based on the concepts of try, catch, and finally blocks.
a. Checked Exceptions:
• Checked exceptions are exceptions that are checked at compile-time.
• The programmer is required to either handle them using try-catch blocks or declare that the method throws the exception using the throws clause.
• Example :
• import java.io.FileReader;
import java.io.IOException;
• They are subclasses of RuntimeException and typically represent programming errors or conditions that are beyond the programmer's control.
c. Error:
• Errors are exceptional situations that are typically beyond the control of the programmer.
• Unlike exceptions, errors are not meant to be caught or handled by the program, and they usually indicate serious issues
b. Catch Block:
• A catch block handles a specific type of exception.
c. Finally Block:
• The finally block contains code that is always executed, whether an exception occurs or not.
• Custom exceptions allow for more specific and meaningful error handling.
• Typically used when a specific condition is met and an exceptional situation needs to be signaled.
• The throws keyword is used in a method signature to indicate that the method might throw certain types of exceptions.
• Used in the method signature to declare the types of exceptions that might be thrown by the method.
• Indicates that the method does not handle the exceptions itself but expects the calling code to handle them.
• import java.io.FileNotFoundException;
• Checked exceptions are Checked at Compile Time. • Checked exceptions are not Checked at Compile Time.
• • ArithmeticException, NullPointerException,
IOException ,SQLException FileNotFoundException
ArrayIndexOutOfBoundsException
OOPS
• Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes for organizing code.
• Java is an object-oriented programming language, an OOP principles play a fundamental role in Java development.
Class
• A class is a blueprint or template that defines the structure and behavior of objects.
It encapsulates data (attributes) and methods (functions) that operate on the data.
object
An object is an instance of a class, representing a real-world entity.
Objects have state (attributes) and behavior (methods).
Abstraction
Abstraction is the process of simplifying complex systems by modeling classes based on their essential properties and behaviors.
It hides the implementation details and exposes only relevant features.
Abstract classes and interfaces are used to achieve abstraction.
Abstract Class: Shape with abstract methods like draw() and calculateArea() .
• ENCAPSULATION
Encapsulation is the bundling of data (attributes) and methods that operate on the data within a single unit (class).
It restricts direct access to some of an object's components and can prevent unintended interference.
Encapsulation: Private attributes like accountNumber and public methods like deposit() and withdraw() .
• // Class representing a Bank Account
class BankAccount {
private String accountNumber;
private double balance;
// Constructor
public BankAccount(String accountNumber) {
this.accountNumber = accountNumber;
this.balance = 0.0;
}
POLYMORPHISM
• Polymorphism allows objects to be treated as instances of their parent class rather than their actual class.
It enables methods to be invoked on objects of different types, leading to flexibility and extensibility.
Compile-time Polymorphism:
• Method Overloading in a class, e.g., calculateArea(int side) and calculateArea(int length, int width).
Runtime Polymorphism:
Method Overriding in a subclass, e.g., draw() in Shape overridden in Circle and Square.
MULTITHREADING
• a thread is the smallest unit of execution.
• Java provides built-in support for multithreading, allowing you to create and manage multiple threads within a single program.
• This allows for concurrent execution of tasks, which can improve program efficiency by utilizing the available CPU resources more effectively.
• Blocked:The thread is blocked, waiting for a monitor lock. This occurs when a thread attempts to access an object that another thread has
locked.
• Waiting:The thread is waiting indefinitely for another thread to perform a particular action. It enters this state when using methods like wait() or
join().
• Timed Waiting:Similar to the waiting state, but the thread can wait for a specified period. Methods like sleep() or wait(timeout) put a thread in
this state.
• Terminated:The thread has exited, either by completing its execution or by throwing an uncaught exception.
MULTITHREADING
• Multithreading allows multiple threads to execute concurrently.
Each thread runs independently, and the operating system manages their execution.
Multithreading is beneficial for tasks that can be performed concurrently, improving program responsiveness and efficiency.
In a Spring Boot web application, the web server handles multiple incoming requests simultaneously. Each incoming request is typically
processed in a separate thread, allowing the server to handle multiple clients concurrently without blocking.
Parallel Processing:
Imagine a Spring Boot application that needs to perform a complex computation or data processing task. By dividing the task into smaller units
and processing them concurrently using threads, the application can achieve parallel processing, improving performance.
Background Tasks:
Spring Boot applications often have tasks that run in the background, such as sending emails, updating caches, or performing periodic cleanup.
Using threads, you can run these tasks concurrently without affecting the main application flow.
File Upload/Download:
When handling file uploads or downloads, multithreading can be beneficial. For instance, in a Spring Boot application serving file downloads,
each download request can be processed in a separate thread, allowing multiple users to download files concurrently.
Asynchronous Processing:
Spring Boot supports asynchronous processing, where tasks can be executed asynchronously using threads. This is commonly used in scenarios
like handling long-running operations, such as making external API calls or processing large data sets, without blocking the main application
thread.
Database Operations:
In a Spring Boot application interacting with a database, multithreading can be employed to handle concurrent database operations. For example,
multiple database queries or updates can be executed simultaneously, improving overall database access performance.
Microservices Communication:
In a microservices architecture implemented with Spring Boot, individual microservices may communicate with each other. Multithreading can be
used to handle parallel communication with multiple microservices, improving the responsiveness of the overall system.
Immutable string
• string references are used to store various attributes like username, password, etc.
• In Java, String objects are immutable. Immutable simply means unmodifiable or unchangeable.
• String object is created its data or state can't be changed but a new String object is created.
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
} }
JAVA STRING COMPARE
By Using equals() Method
By Using == Operator
By compareTo() Method
STRING METHODS
1. CharAt()
2. CompareT0()
3. Concat()
4. EndsWith()
5. Equals()
6. EqualsgnoreCase()
7. IndexOf()
8. IsEmpty()
9. LastIndexOf()
10. Length()
11. Replace()
12. ReplaceAll()
13. Split()
14. StartsWith()
15. ToCharArray
16. ToLowerCase()
17. ToUpperCase()
18. Trim()
19. valueOf()
OBJECT CLASS
• Object class is an parent class of all class.
equals(Object obj):
• Indicates whether some other object is "equal to" this one.
hashCode():
• Returns a hash code value for the object.
toString():
• By default, it returns a string consisting of the class name followed by "@" and the object's hashcode.
getClass():
• Returns the runtime class of an object.
clone():
• Creates and returns a copy of this object.
finalize():
• Called by the garbage collector before the object is reclaimed.
• They allow you to write code that is more flexible, reusable, and type-safe. Here's an example to illustrate the use of generics
EXAMPLE
• // Generic class with a type parameter T
class Box<T> {
private T value;
// Constructor
public Box(T value) {
this.value = value;
}
• Object Reachability:
Garbage collection identifies objects that are no longer reachable or referenced by any part of the program.
Reachable objects are those that can be accessed directly or indirectly from the application's roots (e.g., local variables, static variables, method
parameters).
class MyClass {
// Class definition
}