https://updategadh.com/
How to Run AI Models Locally with Python Using Ollama
Run AI Models Locally with Python Artificial Intelligence is becoming easier to use in everyday software projects. Many developers use cloud-based
๐ How to Run AI Models Locally with Python Using Ollama
Want to run AI models directly on your own computer? ๐ค๐ป
In this beginner-friendly tutorial, learn how to use Ollama + Python to run local AI models and build your own AI applications.
๐ฅ What You'll Learn:
โ Install Ollama
โ Download and run an AI model
โ Connect Ollama with Python
โ Use "chat()" and "generate()"
โ Build a Python AI chatbot
โ Maintain conversation history
โ Stream AI responses
โ Explore local AI project ideas
๐ก Perfect for Python developers, AI learners, and students who want to experiment with Local LLMs.
๐ Read the Complete Tutorial:
๐ https://updategadh.com/run-ai-models-locally-with-python/
๐ Join for More Projects & Tutorials:
๐ @ProjectWithSourceCode
#Ollama #Python #AI #ArtificialIntelligence #LocalAI #LLM #PythonAI #GenerativeAI #AIChatbot #MachineLearning #PythonTutorial #AITutorial #LocalLLM #AIProjects
Want to run AI models directly on your own computer? ๐ค๐ป
In this beginner-friendly tutorial, learn how to use Ollama + Python to run local AI models and build your own AI applications.
๐ฅ What You'll Learn:
โ Install Ollama
โ Download and run an AI model
โ Connect Ollama with Python
โ Use "chat()" and "generate()"
โ Build a Python AI chatbot
โ Maintain conversation history
โ Stream AI responses
โ Explore local AI project ideas
๐ก Perfect for Python developers, AI learners, and students who want to experiment with Local LLMs.
๐ Read the Complete Tutorial:
๐ https://updategadh.com/run-ai-models-locally-with-python/
๐ Join for More Projects & Tutorials:
๐ @ProjectWithSourceCode
#Ollama #Python #AI #ArtificialIntelligence #LocalAI #LLM #PythonAI #GenerativeAI #AIChatbot #MachineLearning #PythonTutorial #AITutorial #LocalLLM #AIProjects
๐ Generative AI Interview Questions with Answers (Part 8)
3๏ธโฃ6๏ธโฃ What is Token Embedding in an LLM?
๐ Token Embedding converts each token into a numerical vector representation that a neural network can process.
๐ Basic flow:
Example:
๐ก Embeddings allow the model to represent relationships between tokens mathematically.
3๏ธโฃ7๏ธโฃ What is Positional Encoding?
๐ Positional Encoding provides information about the position or order of tokens in a sequence.
This is important because attention mechanisms alone do not inherently encode token order.
Example:
๐ก Different Transformer architectures use different approaches to represent positional information.
3๏ธโฃ8๏ธโฃ What is a Multi-Head Attention Mechanism?
๐ Multi-Head Attention uses multiple attention mechanisms (heads) so the model can capture different relationships within the same input.
๐ Simplified flow:
๐ก Different heads can learn different types of relationships between tokens.
3๏ธโฃ9๏ธโฃ What is a Transformer Layer?
๐ A Transformer layer is a repeated building block of a Transformer model. Depending on the architecture, it typically contains attention mechanisms and feed-forward neural network components, along with normalization and residual connections.
๐ Simplified structure:
๐ก Multiple Transformer layers are stacked together to build larger models.
4๏ธโฃ0๏ธโฃ What is Next-Token Prediction?
๐ Next-token prediction is the process of predicting the most likely next token based on the previous context.
Example:
The model calculates probabilities for possible next tokens and selects one according to its decoding strategy.
๐ Context โ Probability Distribution โ Next Token โ Repeat
๐ก Autoregressive language models generate text one token at a time.
๐ฌ Save this for your Generative AI interview preparation!
๐ฅ Next Part will cover 5 questions on Attention Q, K, V, Softmax, Logits, Sampling & Decoding.
#GenerativeAI #GenAI #LLM #Transformer #AI #ArtificialIntelligence #Attention #DeepLearning #AIInterview #InterviewQuestions
3๏ธโฃ6๏ธโฃ What is Token Embedding in an LLM?
๐ Token Embedding converts each token into a numerical vector representation that a neural network can process.
๐ Basic flow:
Text
โ
Tokens
โ
Token IDs
โ
Embeddings
โ
Transformer
Example:
"AI is powerful"
โ
[Token IDs]
โ
[Vector Representations]
๐ก Embeddings allow the model to represent relationships between tokens mathematically.
3๏ธโฃ7๏ธโฃ What is Positional Encoding?
๐ Positional Encoding provides information about the position or order of tokens in a sequence.
This is important because attention mechanisms alone do not inherently encode token order.
Example:
"The dog chased the cat"
โ
Position Information
โ
Model understands token order
๐ก Different Transformer architectures use different approaches to represent positional information.
3๏ธโฃ8๏ธโฃ What is a Multi-Head Attention Mechanism?
๐ Multi-Head Attention uses multiple attention mechanisms (heads) so the model can capture different relationships within the same input.
๐ Simplified flow:
Input
โ
โโโโโโโโโโฌโโโโโโโโโฌโโโโโโโโโ
Head 1 Head 2 Head 3 ...
โโโโโโโโโโดโโโโโโโโโดโโโโโโโโโ
โ
Combined
โ
Output
๐ก Different heads can learn different types of relationships between tokens.
3๏ธโฃ9๏ธโฃ What is a Transformer Layer?
๐ A Transformer layer is a repeated building block of a Transformer model. Depending on the architecture, it typically contains attention mechanisms and feed-forward neural network components, along with normalization and residual connections.
๐ Simplified structure:
Input
โ
Attention
โ
Feed-Forward Network
โ
Output
๐ก Multiple Transformer layers are stacked together to build larger models.
4๏ธโฃ0๏ธโฃ What is Next-Token Prediction?
๐ Next-token prediction is the process of predicting the most likely next token based on the previous context.
Example:
Input:
"Machine learning is"
Possible next tokens:
"powerful"
"important"
"used"
The model calculates probabilities for possible next tokens and selects one according to its decoding strategy.
๐ Context โ Probability Distribution โ Next Token โ Repeat
๐ก Autoregressive language models generate text one token at a time.
๐ฌ Save this for your Generative AI interview preparation!
๐ฅ Next Part will cover 5 questions on Attention Q, K, V, Softmax, Logits, Sampling & Decoding.
#GenerativeAI #GenAI #LLM #Transformer #AI #ArtificialIntelligence #Attention #DeepLearning #AIInterview #InterviewQuestions
โ๏ธ Java Interview Questions with Answers (Part 2)
6๏ธโฃ What is Inheritance in Java?
๐ Inheritance allows a class to acquire fields and methods from another class. It helps create reusable and hierarchical code.
Example:
๐
7๏ธโฃ What is Polymorphism in Java?
๐ Polymorphism means one interface or method name can represent different behaviors.
Two common forms are:
๐น Compile-time Polymorphism โ Method Overloading
๐น Runtime Polymorphism โ Method Overriding
Example of Overloading:
๐ก The same method name
8๏ธโฃ What is Encapsulation in Java?
๐ Encapsulation means bundling data and methods together while controlling direct access to the data.
Example:
๐
๐ก Encapsulation helps protect object state and provides controlled access.
9๏ธโฃ What is Abstraction in Java?
๐ Abstraction means hiding implementation details and exposing only the essential functionality.
Java supports abstraction using:
๐น Abstract Classes
๐น Interfaces
Example:
๐ก The user of
๐ What is a Constructor in Java?
๐ A constructor is a special member used to initialize an object when it is created.
Example:
๐ Constructor name must match the class name.
๐ก Constructors do not have a return type, including
๐ฌ Save this for your Java interview preparation!
๐ฅ Part 3 will cover 5 important questions on Method Overloading, Method Overriding,
#Java #JavaInterview #JavaProgramming #OOP #CodingInterview #Programming #SoftwareEngineer #InterviewQuestions #Developer #TechInterview
6๏ธโฃ What is Inheritance in Java?
๐ Inheritance allows a class to acquire fields and methods from another class. It helps create reusable and hierarchical code.
Example:
class Animal {
void eat() {
System.out.println("Eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.eat();
d.bark();
}
}๐
Dog inherits the eat() method from Animal.7๏ธโฃ What is Polymorphism in Java?
๐ Polymorphism means one interface or method name can represent different behaviors.
Two common forms are:
๐น Compile-time Polymorphism โ Method Overloading
๐น Runtime Polymorphism โ Method Overriding
Example of Overloading:
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}๐ก The same method name
add() works with different parameter lists.8๏ธโฃ What is Encapsulation in Java?
๐ Encapsulation means bundling data and methods together while controlling direct access to the data.
Example:
class Student {
private int age;
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
}๐
private prevents direct access from outside the class.๐ก Encapsulation helps protect object state and provides controlled access.
9๏ธโฃ What is Abstraction in Java?
๐ Abstraction means hiding implementation details and exposing only the essential functionality.
Java supports abstraction using:
๐น Abstract Classes
๐น Interfaces
Example:
abstract class Animal {
abstract void sound();
void sleep() {
System.out.println("Sleeping");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Bark");
}
}๐ก The user of
Animal does not need to know how sound() is implemented internally.๐ What is a Constructor in Java?
๐ A constructor is a special member used to initialize an object when it is created.
Example:
class Student {
String name;
Student(String name) {
this.name = name;
}
void display() {
System.out.println(name);
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student("Rahul");
s.display();
}
}๐ Constructor name must match the class name.
๐ก Constructors do not have a return type, including
void.๐ฌ Save this for your Java interview preparation!
๐ฅ Part 3 will cover 5 important questions on Method Overloading, Method Overriding,
this, super & static.#Java #JavaInterview #JavaProgramming #OOP #CodingInterview #Programming #SoftwareEngineer #InterviewQuestions #Developer #TechInterview
๐ง AI Search Algorithms Interview Questions with Answers (Part 3)
1๏ธโฃ1๏ธโฃ What is Uniform Cost Search (UCS)?
๐ Uniform Cost Search expands the node with the lowest path cost from the starting point.
๐ It uses:
๐ก UCS is useful when different actions have different costs.
โฑ๏ธ Time Complexity: Depends on the search space
๐พ Space Complexity: Depends on the search space
1๏ธโฃ2๏ธโฃ What is Bidirectional Search?
๐ Bidirectional Search runs two searches simultaneously:
๐น One from the initial state
๐น One from the goal state
The searches continue until they meet.
๐ก It can significantly reduce the search depth for suitable problems.
1๏ธโฃ3๏ธโฃ What is Local Search in AI?
๐ Local Search algorithms focus on the current state and its neighboring states rather than maintaining a complete search path.
Examples:
๐น Hill Climbing
๐น Simulated Annealing
๐น Local Beam Search
๐ก Local search is commonly used for optimization problems where the goal is to find a good solution rather than necessarily reconstructing a path.
1๏ธโฃ4๏ธโฃ What is Simulated Annealing?
๐ Simulated Annealing is a local optimization algorithm that sometimes accepts a worse solution temporarily to escape local optima.
๐ Basic idea:
๐ก The probability of accepting worse solutions gradually decreases as the algorithm progresses.
1๏ธโฃ5๏ธโฃ What is a Genetic Algorithm?
๐ A Genetic Algorithm is an optimization technique inspired by natural selection and evolution.
Main steps:
๐น Initialize Population
๐น Evaluate Fitness
๐น Selection
๐น Crossover
๐น Mutation
๐น Repeat
๐ก Genetic Algorithms are useful for complex optimization problems where traditional methods may be difficult to apply.
๐ฌ Save this for your AI interview preparation!
๐ฅ Next: Advanced Coding โ Part 4
#AI #ArtificialIntelligence #AISearch #GeneticAlgorithm #SimulatedAnnealing #AIInterview #InterviewQuestions
1๏ธโฃ1๏ธโฃ What is Uniform Cost Search (UCS)?
๐ Uniform Cost Search expands the node with the lowest path cost from the starting point.
๐ It uses:
Priority = Path Cost
๐ก UCS is useful when different actions have different costs.
โฑ๏ธ Time Complexity: Depends on the search space
๐พ Space Complexity: Depends on the search space
1๏ธโฃ2๏ธโฃ What is Bidirectional Search?
๐ Bidirectional Search runs two searches simultaneously:
๐น One from the initial state
๐น One from the goal state
The searches continue until they meet.
Start โ โ โ โ โ โ Goal
โ
Meet
๐ก It can significantly reduce the search depth for suitable problems.
1๏ธโฃ3๏ธโฃ What is Local Search in AI?
๐ Local Search algorithms focus on the current state and its neighboring states rather than maintaining a complete search path.
Examples:
๐น Hill Climbing
๐น Simulated Annealing
๐น Local Beam Search
๐ก Local search is commonly used for optimization problems where the goal is to find a good solution rather than necessarily reconstructing a path.
1๏ธโฃ4๏ธโฃ What is Simulated Annealing?
๐ Simulated Annealing is a local optimization algorithm that sometimes accepts a worse solution temporarily to escape local optima.
๐ Basic idea:
Current Solution
โ
Generate Neighbor
โ
Better? โ Accept
Worse? โ Sometimes Accept
โ
Continue
๐ก The probability of accepting worse solutions gradually decreases as the algorithm progresses.
1๏ธโฃ5๏ธโฃ What is a Genetic Algorithm?
๐ A Genetic Algorithm is an optimization technique inspired by natural selection and evolution.
Main steps:
๐น Initialize Population
๐น Evaluate Fitness
๐น Selection
๐น Crossover
๐น Mutation
๐น Repeat
Population
โ
Fitness
โ
Selection
โ
Crossover + Mutation
โ
New Population
๐ก Genetic Algorithms are useful for complex optimization problems where traditional methods may be difficult to apply.
๐ฌ Save this for your AI interview preparation!
๐ฅ Next: Advanced Coding โ Part 4
#AI #ArtificialIntelligence #AISearch #GeneticAlgorithm #SimulatedAnnealing #AIInterview #InterviewQuestions
๐ Advanced Coding Interview Questions with Answers (Part 4)
1๏ธโฃ6๏ธโฃ Find the Shortest Path Using Dijkstra's Algorithm
๐ Dijkstra's Algorithm finds the shortest path from a source node to other nodes in a graph with non-negative edge weights.
โฑ๏ธ Time Complexity: O((V + E) log V)
1๏ธโฃ7๏ธโฃ Implement a Trie
๐ A Trie is a tree-based data structure commonly used for prefix searching and autocomplete.
โฑ๏ธ Time Complexity: O(L) per operation
1๏ธโฃ8๏ธโฃ Find Connected Components Using Union-Find
๐ Union-Find, also called Disjoint Set Union (DSU), efficiently manages groups of connected elements.
๐ก It is commonly used in graph connectivity and Kruskal's algorithm.
โฑ๏ธ Amortized Time: Nearly O(1) per operation with path compression and union by rank/size.
1๏ธโฃ9๏ธโฃ Rotate a Matrix 90 Degrees Clockwise
๐ Rotate an
๐ Output:
โฑ๏ธ Time Complexity: O(nยฒ)
๐พ Space Complexity: O(1)
2๏ธโฃ0๏ธโฃ Solve the 0/1 Knapsack Problem
๐ Given items with weights and values, find the maximum value that can be placed in a bag with limited capacity.
๐ Output:
โฑ๏ธ Time Complexity: O(n ร capacity)
๐พ Space Complexity: O(capacity)
๐ฌ Save this for your advanced coding interview preparation!
๐ฅ Next: Generative AI โ Part 9
#Coding #DSA #Python #AdvancedCoding #Algorithms #DynamicProgramming #Graphs #InterviewQuestions
1๏ธโฃ6๏ธโฃ Find the Shortest Path Using Dijkstra's Algorithm
๐ Dijkstra's Algorithm finds the shortest path from a source node to other nodes in a graph with non-negative edge weights.
import heapq
def dijkstra(graph, start):
distances = {node: float("inf") for node in graph}
distances[start] = 0
heap = [(0, start)]
while heap:
distance, node = heapq.heappop(heap)
if distance > distances[node]:
continue
for neighbor, weight in graph[node]:
new_distance = distance + weight
if new_distance < distances[neighbor]:
distances[neighbor] = new_distance
heapq.heappush(heap, (new_distance, neighbor))
return distances
โฑ๏ธ Time Complexity: O((V + E) log V)
1๏ธโฃ7๏ธโฃ Implement a Trie
๐ A Trie is a tree-based data structure commonly used for prefix searching and autocomplete.
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end = True
def search(self, word):
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.is_end
โฑ๏ธ Time Complexity: O(L) per operation
L = length of the word1๏ธโฃ8๏ธโฃ Find Connected Components Using Union-Find
๐ Union-Find, also called Disjoint Set Union (DSU), efficiently manages groups of connected elements.
class DSU:
def __init__(self, n):
self.parent = list(range(n))
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, a, b):
root_a = self.find(a)
root_b = self.find(b)
if root_a != root_b:
self.parent[root_b] = root_a
๐ก It is commonly used in graph connectivity and Kruskal's algorithm.
โฑ๏ธ Amortized Time: Nearly O(1) per operation with path compression and union by rank/size.
1๏ธโฃ9๏ธโฃ Rotate a Matrix 90 Degrees Clockwise
๐ Rotate an
n ร n matrix 90 degrees clockwise in place.def rotate(matrix):
n = len(matrix)
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = (
matrix[j][i],
matrix[i][j]
)
for row in matrix:
row.reverse()
return matrix
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(rotate(matrix))
๐ Output:
[[7, 4, 1],
[8, 5, 2],
[9, 6, 3]]
โฑ๏ธ Time Complexity: O(nยฒ)
๐พ Space Complexity: O(1)
2๏ธโฃ0๏ธโฃ Solve the 0/1 Knapsack Problem
๐ Given items with weights and values, find the maximum value that can be placed in a bag with limited capacity.
def knapsack(weights, values, capacity):
dp = [0] * (capacity + 1)
for i in range(len(weights)):
for w in range(capacity, weights[i] - 1, -1):
dp[w] = max(
dp[w],
dp[w - weights[i]] + values[i]
)
return dp[capacity]
print(knapsack([1, 3, 4], [15, 50, 60], 4))
๐ Output:
65
โฑ๏ธ Time Complexity: O(n ร capacity)
๐พ Space Complexity: O(capacity)
๐ฌ Save this for your advanced coding interview preparation!
๐ฅ Next: Generative AI โ Part 9
#Coding #DSA #Python #AdvancedCoding #Algorithms #DynamicProgramming #Graphs #InterviewQuestions
๐ Generative AI Interview Questions with Answers (Part 9)
4๏ธโฃ1๏ธโฃ What are Query, Key, and Value (Q, K, V) in Attention?
๐ In the attention mechanism, each token is transformed into three vectors:
๐น Query (Q) โ What information am I looking for?
๐น Key (K) โ What information do I contain?
๐น Value (V) โ What information should I provide?
A simplified attention calculation is:
๐ก Q, K, and V help the model determine which tokens should receive more attention.
4๏ธโฃ2๏ธโฃ What are Logits in an LLM?
๐ Logits are the raw numerical scores produced by a model before they are converted into probabilities.
๐ Simplified flow:
๐ก Higher relative logits generally correspond to higher probabilities after softmax.
4๏ธโฃ3๏ธโฃ What is Softmax in AI?
๐ Softmax converts a set of numerical scores into a probability distribution.
For example:
๐ The probabilities sum to approximately 1.
๐ก Softmax is commonly used for converting model scores into probabilities over possible classes or tokens.
4๏ธโฃ4๏ธโฃ What is Greedy Decoding?
๐ Greedy decoding selects the highest-probability token at each generation step.
Example:
๐ It is simple and deterministic for a fixed model/input, but it may not always produce the most desirable overall sequence.
4๏ธโฃ5๏ธโฃ What is Sampling in Generative AI?
๐ Sampling selects the next token probabilistically from a distribution rather than always choosing the highest-probability token.
Common decoding controls include:
๐น Temperature
๐น Top-P
๐น Top-K
๐ Sampling can produce more varied outputs than greedy decoding.
๐ก The exact behavior depends on the model and decoding settings.
๐ฌ Save this for your Generative AI interview preparation!
๐ฅ Next: Java Interview Questions โ Part 3
#GenerativeAI #GenAI #LLM #Transformer #Attention #Softmax #AIInterview #InterviewQuestions #MachineLearning
4๏ธโฃ1๏ธโฃ What are Query, Key, and Value (Q, K, V) in Attention?
๐ In the attention mechanism, each token is transformed into three vectors:
๐น Query (Q) โ What information am I looking for?
๐น Key (K) โ What information do I contain?
๐น Value (V) โ What information should I provide?
A simplified attention calculation is:
Attention(Q, K, V)
= softmax(QKแต / โdโ)V
๐ก Q, K, and V help the model determine which tokens should receive more attention.
4๏ธโฃ2๏ธโฃ What are Logits in an LLM?
๐ Logits are the raw numerical scores produced by a model before they are converted into probabilities.
๐ Simplified flow:
Input
โ
LLM
โ
Logits
โ
Softmax
โ
Probabilities
โ
Next Token
๐ก Higher relative logits generally correspond to higher probabilities after softmax.
4๏ธโฃ3๏ธโฃ What is Softmax in AI?
๐ Softmax converts a set of numerical scores into a probability distribution.
For example:
Logits
โ
Softmax
โ
Token A โ 0.70
Token B โ 0.20
Token C โ 0.10
๐ The probabilities sum to approximately 1.
๐ก Softmax is commonly used for converting model scores into probabilities over possible classes or tokens.
4๏ธโฃ4๏ธโฃ What is Greedy Decoding?
๐ Greedy decoding selects the highest-probability token at each generation step.
Example:
Token probabilities
A โ 0.70
B โ 0.20
C โ 0.10
Selected โ A
๐ It is simple and deterministic for a fixed model/input, but it may not always produce the most desirable overall sequence.
4๏ธโฃ5๏ธโฃ What is Sampling in Generative AI?
๐ Sampling selects the next token probabilistically from a distribution rather than always choosing the highest-probability token.
Common decoding controls include:
๐น Temperature
๐น Top-P
๐น Top-K
๐ Sampling can produce more varied outputs than greedy decoding.
๐ก The exact behavior depends on the model and decoding settings.
๐ฌ Save this for your Generative AI interview preparation!
๐ฅ Next: Java Interview Questions โ Part 3
#GenerativeAI #GenAI #LLM #Transformer #Attention #Softmax #AIInterview #InterviewQuestions #MachineLearning
โ๏ธ Java Interview Questions with Answers (Part 3)
1๏ธโฃ1๏ธโฃ What is Method Overloading in Java?
๐ Method Overloading means having multiple methods with the same name but different parameter lists in the same class.
๐ก Overloading is resolved at compile time.
1๏ธโฃ2๏ธโฃ What is Method Overriding in Java?
๐ Method Overriding occurs when a subclass provides its own implementation of an inherited method.
๐ก Overriding is associated with runtime polymorphism.
1๏ธโฃ3๏ธโฃ What is the
๐
It is commonly used to:
๐น Access current object's fields
๐น Call current class methods
๐น Invoke another constructor
Example:
1๏ธโฃ4๏ธโฃ What is the
๐
It can be used to:
๐น Access parent fields
๐น Call parent methods
๐น Call the parent constructor
Example:
๐ Output:
1๏ธโฃ5๏ธโฃ What is the
๐
Example:
๐ Output:
๐ก A static field is shared among instances of the class.
๐ฌ Save this for your Java interview preparation!
๐ฅ Next: Python Interview Questions โ Part 2
#Java #JavaInterview #JavaProgramming #OOP #CodingInterview #Programming #InterviewQuestions #Developer #SoftwareEngineer
1๏ธโฃ1๏ธโฃ What is Method Overloading in Java?
๐ Method Overloading means having multiple methods with the same name but different parameter lists in the same class.
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}๐ก Overloading is resolved at compile time.
1๏ธโฃ2๏ธโฃ What is Method Overriding in Java?
๐ Method Overriding occurs when a subclass provides its own implementation of an inherited method.
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}๐ก Overriding is associated with runtime polymorphism.
1๏ธโฃ3๏ธโฃ What is the
this Keyword in Java?๐
this refers to the current object.It is commonly used to:
๐น Access current object's fields
๐น Call current class methods
๐น Invoke another constructor
Example:
class Student {
String name;
Student(String name) {
this.name = name;
}
}1๏ธโฃ4๏ธโฃ What is the
super Keyword in Java?๐
super refers to the immediate parent class.It can be used to:
๐น Access parent fields
๐น Call parent methods
๐น Call the parent constructor
Example:
class Animal {
String name = "Animal";
}
class Dog extends Animal {
String name = "Dog";
void display() {
System.out.println(super.name);
}
}๐ Output:
Animal
1๏ธโฃ5๏ธโฃ What is the
static Keyword in Java?๐
static indicates that a member belongs to the class rather than a particular object.Example:
class Counter {
static int count = 0;
Counter() {
count++;
}
}
public class Main {
public static void main(String[] args) {
new Counter();
new Counter();
System.out.println(Counter.count);
}
}๐ Output:
2
๐ก A static field is shared among instances of the class.
๐ฌ Save this for your Java interview preparation!
๐ฅ Next: Python Interview Questions โ Part 2
#Java #JavaInterview #JavaProgramming #OOP #CodingInterview #Programming #InterviewQuestions #Developer #SoftwareEngineer