Abc Java
Abc Java
Object-Oriented: Security:
T FROM • Java emphasizes security
• Java follows the principles of object-
oriented programming (OOP), features, such as the sandboxing
emphasizing encapsulation,
DIFFEREN of applets and a security
inheritance, and polymorphism. manager, making it suitable for
IS building secure applications.
Strong Typing:
Portability:
• Java is a statically-typed language, HOW JAVA
meaning variable types are explicitly • Java's "write once, run anywhere"
declared at compile time. This helps philosophy contributes to its
catch type-related errors early in the portability across different
development process. operating systems and devices.
PHASES OF A JAVA PROGRAM
• Edit: Write the Java source code using a text editor or an integrated
development environment (IDE).
• 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
Heap
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
JAVA PROGRAMMING ENVIRONMENT
1. How to Install & set Path.
2. A Simple Java Program
3. Phases of Java Program
4. Runtime Exception
5. Name of a Java Source File
6. Platform Independent
7. Java Technology (JDK, JRE, JVM, JIT)
JDK JRE JVM JIT
• JDK (Java Development Kit) :
The JDK is a software development environment that provides the
necessary tools and libraries to develop and run Java applications.
• JRE (Java Runtime Environment) :
The JRE is an environment that allows you to run Java applications. It includes the
JVM and other necessary libraries.
• JVM (Java Virtual Machine) :
The JVM is the runtime engine that executes Java bytecode. It provides
platform independence and memory management.
• JIT (Just-In-Time Compilation)
JIT is a technique used by the JVM to improve performance by dynamically compiling
Java bytecode into native machine code.
SYNTAX RULES
• Java follows a strict set of rules for constructing statements and expressions, including rules for naming
conventions and semicolons .
• 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
• 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
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.
•
2) Interface declarations and implementations.
3) Extends vs implements
4) Interface methods
5) Interface variables
6) Interface naming conflicts
a) Method naming conflicts
• 7) Marker interface
• Any service requirement specification (srs) is called an interface.
• 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
• Byte to int
• Down casting ( explicit casting ) - programmer is responsible
• Long to int(long)
• Float to int
OPERATORS IN JAVA
• 1. 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));
• 2. Comparison Operators:
• == (Equal to)
• != (Not equal to)
• < (Less than)
• > (Greater than)
• <= (Less than or equal to)
• >= (Greater than or equal to)
• int x = 5, y = 10;
counter--; // Decrement by 1
System.out.println(counter); // 10
• 6. Conditional (Ternary) Operator:
• ? : (Conditional)
int number = 7;
• String result = (number % 2 == 0) ? "Even" : "Odd";
• System.out.println(result); // Odd
FLOW CONTROL IN THE JAVA
• 1 selection statement - if else , switch
• 2 iterative statement - while loop, do, for loop, for each
• 3 transfer statement - break, continue, return, try - catch - finally.
1 SELECTION STATEMENT -
if else
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:
• They are subclasses of RuntimeException and typically represent programming errors or conditions that are beyond the programmer's
control.
• 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.
// Constructor
public BankAccount(String accountNumber) {
this.accountNumber = accountNumber;
this.balance = 0.0;
}
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.
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.
• Stack:
Each thread in a Java program has its own stack, which stores local variables and partial results.
The stack is used for method execution and managing method call frames.
It consists of two parts: the operand stack and the method call stack.
• PC Register:
The Program Counter (PC) register is a small area of memory that stores the address of the Java virtual machine
instruction currently being executed.
Each thread has its own PC register.
• Native Method Stack:
It is used to support native methods, which are methods written in languages other than Java (e.g., C or C++).
Similar to the Java stack, but used for native code execution.
• Direct Memory:
Memory allocated outside the Java heap by using the java.nio package for buffer operations.
It is not subject to garbage collection but requires manual management.
• Runtime Constant Pool:
Part of the method area that stores constant values, symbols, and class-level final variables.
• Class (Metadata) Data:
Part of the method area that stores information about classes, interfaces, methods, and fields.
STRING CONCEPTS
• string is basically an object that represents sequence of char values.
• 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
• charAt()
compareT0()
concat()
endsWith()
equals()
equalsgnoreCase()
indexOf()
isEmpty()
lastIndexOf()
length()
replace()
replaceAll()
split()
startsWith()
toCharArray
toLowerCase()
toUpperCase()
trim()
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.
• By default, it checks for reference equality.
• hashCode():
• Returns a hash code value for the object.
• Used for hash-based data structures like HashMap.
• toString():
• Returns a string representation of the object.
• 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.
• Useful for obtaining information about the class.
• clone():
• Creates and returns a copy of this object.
• The class must implement the Cloneable interface.
• finalize():
• Called by the garbage collector before the object is reclaimed.
• Deprecated in recent Java versions. Use try-with-resources or AutoCloseable instead.
• notify(), notifyAll(), wait():
• Used for inter-thread communication and synchronization.
COLLECTIONS
• Almost done
GENERICS
• Generics in Java provide a way to create classes, interfaces, and methods with
parameters that can work with any data type.
• 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;
}
class MyClass {
// Class definition
}