SlideShare a Scribd company logo
JAVAInterview Questions and Answers with
Practical example
Questions discussed as a part of this course areon –
1. Snake & Ladder
2. Connection Pooling
Why and what this course is all about?
In order to understand this demonstration you should have to know the basics of arrays and
collections from JAVA Perspective.
The three major part of this course are –
• Logic Development
• Designing &
• Converting design into Coding
With practical interview questions you will also learn to improve your coding capability. To
develop your coding capability first learn to think logically and then convert that logic to design.
This concept goes as per the demand of today’s IT industry.
These coding questions play an important role during the interview process right from software
developer all the way till architects level. Here will be thoroughly understanding the solutions to
some of the important coding questions which will enable you to clear interview very easily.
Snake & Ladder
What is Snake & Ladder?
It is one of the popular board game worldwide mainly amongst children. It is played with the
help of a Dice where a dice has six sides with number 1 to 6. In the middle of the game you will
come across ladder climb and snake bite/snake mouth. Snake bite will bring you down all the
way till its tail position and ladder will help you going up. Players roll the dice one by one and
when they roll the dice based upon the points in the dice they will move starting from 1 and
their aim is to reach 100. If 6 comes in the dice then the player can roll again. Snake & Ladder
game consists of 2 or more players and the one who reaches 100 gets declared as winner.
Will be writing a program for Snakes and Ladders with practical examples. We will try to
capture the points where the snake’s mouth is which also known as head and where the snake’s
tail goes we will do coding for the same and how this game works so to see the same will create
solution here.
Solution to this question –
In this solution we will code to get output for below –
1. Capture positions where snake head and tail exists.
2. Capture positions where ladder start and end exists.
3. Capture the Dice Value.
4. Game ends if player reaches end.
To start with the coding of this program first we will create a new Maven project with name
snake-and-ladder.
And inside this Maven project we will create the program to perform Snake and Ladder
Create a new package called as com.vishwa.snakeladder and inside this we will create a JAVA
Class and will call it as GameMain and within this JAVA Class we will write our public static
void main program.
Now next step is we need to create positions where Snakes and Ladders exist. We will create a
method getSnakePositions. Create a Map entry within this to store Snake Positions. We can
create a treemap and return this to store the positions.
Same way we will write method to get Ladder positions.
After doing above steps we will capture head and tail positions of snakes for which we will write
below code :-
Same way we will write method to get Ladder positions.
Both of the above written code will help us maintaining the positions. Now within our main
method will call MAPS using hard coded values. Also we need to capture no. of players or
participants by using SCANNER. Scanner(System.in) will allow us to capture the input from the
console and we can get the no. of participants and we can just print out the no. of players.
Each player of Snake & Ladder game will roll a dice to get random output. So our next step is to
write Roll Dice function with the range of 1 to 6. We can use random class which is available in
JAVA.
Now the logic of the game is to catch a Boolean value which will be false and variable will be set
True whenever the game is over, until the game is not over will keep on looping, looping will
continue the game. We will also need other things like variable to indicate current participants
and collection to store score of each participant.
Within the while loop will print the player no where currentPlayer will tell how many players
are playing the game currently. For which we need to write below function –
Further to that we will require Score of each participant. To get Score we have something called
as ARRAY. This score will get stored in COLLECTION which is implemented by Array and we
can print it.
Also create integer score which capture same number as the no. of participants where we will
initialize everything to 0 as an Array starts with 0. Here we need to do score[currentPlayer-1]);
because current player starts with 1 while within the array it starts with 0 that’s why we have to
do this.
We will write code for where user will roll dice. Current Score of the player and roll dice will
make participants go to next position. Writing this code will give us random dice. Below that we
also create temporary score where participants would reach. This temporary score will take
participant to snake mouth or to climb ladder and to determine the same we will use if loop. If
temporary score is present there then the user will not go to the location which we found out
first but will go to the location which is given by the value of the score.
The user will go lower if snake bites and if the case is different if user will go to the location
which will be a head due to the ladder. Ladder always go to the higher location so both of these
values are captured here. Using else and if conditions we can make participants go ahead
or behind. To make it more user friendly will write the statements as snake bite for going
down and ladder climb for going ahead.
Next step is to declare Boolean Variables to check condition. We have 3 Boolean variables that
are as follows –
• boolean isSnakeBite
• boolean isLadderClimb
• boolean isDiceSix =false
The Boolean values which we have created we will initialize them to false so when we go to the
condition we can come to know whether they are at this location only.
We can isSnakeBite = true; , isLadderClimb = true; isdicevalue correct that also we need DiceSix
= (dicevalue ==6); If dice value comes six each dice value will become true else it will become
false.
If player got 6 he can continue to roll the dice. After getting 6 and if he reaches the position
where snake bites him so he cannot continue or retry. other cases he will get a retry so we have
to check for that. Also we will have to check after the calculation of temp score if temp score 0
then what will happen is we can say the game will be over. Let’s set condition and method for
the same in our code.
Most asked JAVA Interview Questions & Answers.
After this we will see retry condition. For example participant is at 97, he rolls the dice and gets
6 then in such he will not get another chance to roll dice. There are many conditions but first
two important conditions are Snake should not hit the player and the temp score should be less
than or equal to100, it should not be more than 100. Another condition is that Dice Six or
Ladder Climb, in this two cases player will get chance to retry so will put this condition also.
Else there is no retry so we will have to implies the current players, if we have three current
players current player started with 1 next will be 2 and then 3, after 3 again it’s a round robin
fashion means other three players will get chance to roll the dice or depending on how many
players are in the game other players will get chance to play.
And finally we have to capture/store the score of current player driven by temp score. If the
player is hit by snake or he climbs ladder, in these cases temp score is reflected if that is not the
case then the tempScore will be the value of the current score + dice value.
We will also need a roll dice post pressing button for user with the use of Sanner for which you
will write below highlighted code lines. One more we have to do is to have an enter option. Use
scanner.nextLine(); is capable of taking enter task by participants.
At the start of the game we should see two statements as Welcome to snake and ladder
tournament –
After doing correct coding the output you will get as below –
At the start of the game we should see two statements as Welcome to snake and ladder
tournament –
After doing correct coding the output you will get as below –
This was a short demonstration with code snippet on
Snake & Ladder game where we coded for Snake Bite,
Ladder Climb, Snake Position, Ladder Position, DiceSix,
Roll Dice, Temp Score, Starting Point, End game, Enter
key. The advantage of writing a program in this
manner is that we can extend to any number of
players to make it a full tournament as per the
expectation of people.
CONNECTION POOLING
Understand what exactly is Connection Pool in JAVA?
Connection pooling is a Data Access Pattern which deals more with data. It maintains a Cache of
connections which includes all available connections also the connections which are at use. Its
moto is to reduce over head. The arrows in below diagram shows that used connections are
given back to the available pool for reuse.
We will try to maintain a pool of available connections. This pool will store N number of
connections. This connection pooling can be done using any database. In our example we will
implement the connection pool using MySQL Database in JAVA.
First, in our pom.xml we need to add the dependency of mysql-connector-java to make use of
JDBC connector to connect to database. Inside package we have creates new package which we
named as com.Vishwa and inside this will create two more new packages “ConnectionPool” and
“util”. Within util package we will create a class “Connectionutil”
After this the first step we have to do is create method to get a database connection. The jar will
be initialized within this package for which we loaded Driver class within try catch block. This
driver class is coming with new mysql driver. This is new version of mysql jar which contains
“cj” within the entire package. Driver class changes from database to database, you are free to
use whatever database driver is available for your particular database. Incase, you are using
different database than mysql we have to use drive class of that that database.
Next step is to create connection object. Inside DriverManager class we getConnection where
we need dbUrl, Username and Password. Also pass an argument for these three functions(dbUrl,
Username and Password) and inside try catch we will store it as it will thrown an exception. We
will include standard e.printStackTrace(); which is available with exception and we will return
connection and this will get replaced with loggers. This try catch block of loading drivers will be
placed inside a static block which we will execute only at the time of class loading and it will
not get loaded every time and once this code is ready will format the code (Click on Code 
Format Code) to make it look good.
Most asked JAVA Interview Questions & Answers.
And utility class helps us to create DB connection. This utility we will use inside our coding class
and name this as DbConnectionPool.
Now inside this DbConnectionPool we will create public method returning a connection. We
can pass list of properties or map of property or simply properties within getDbConnectionPool.
To pass these properties we will require dbUrl, we can also pass username as well as password.
One more optional attribute which we can pass is “int initialCapacity” , this attribute will tell us
how many connections we want to maintain in the pool. DbConnectionPool is public static
method and <ListConnection> is we will mark as private method, will name it as
availableconnections.
We will have to import the corresponding interfaces and packages. get dbConnection instead of
making this as static we can keep it private so that it becomes available at variable level and
create a private constructor. Within this private constructor we can pass this properties which
we have so that it can use it correspondingly in creating object.
Now inside initial capacity code will put our try catch block and within this we can create our
connections and add it within availableConnections. Due to intial capacity method we can call
our ConnectionUtil. We will make this as a static method because it is a utility method.
Generally utility methods are generally static, we can say ConnectionUtil.createDbConnection()
and pass the dbUrl followed by the username and password. These are the available
connections, so we are creating number of connections and adding to the availabelConnections.
We can return new DbConnectionPool with all these properties which we passed as a part of
the method. DbConnectionPool we will mark as public so it can be called by all and
availableConnection is marked private as it can be called by within function only.
Then our next step will be to create list of busy/occupied connections.
We will need to export a public method for retrieve connection and within retrieve connection
we will check if available connections is empty. If the connections are empty will print a
message as No connection available or else we can return a connection here. We can add this
connection to the occupied Connections and then remove it from the available Connections.
After applying this method this will get removed and at final we can return the connection.
This “retreieveConnection” method will allow to retrieve the connection. It can throw us an
exception or return us null if connections are not available.
Next task is to create release method with Boolean datatype. For releasing connection we will
require the connection object. availableConnection.add(connection); and again Boolean
isRemoved = occupiedConnection.remove() , remove can also take an object so we will pass the
connection object and then finally return isRemoved; We will put
System.put.println(“connection released “ +isRemoved); Also at the time of getting connection we
can say connection received. Below is the code to retrieve the connection and create a release
method.
By using two list we are able to maintain a list of availableConnections as well as the list of
occupiedConnections. The second list i.e. occupiedConnections is optional, we can remove it
from the main list and then again add it after use.
Here we completes the implementation of Simple DbConnectionPool. Now will run this
program, for that we need to create DbConnectionPoolTestClass.
Inside this class we will create Public static void main and within this we will create
DbConnectionPool and will pass dbUrl. In case of My SQL we can pass dbUrl like this. It
indicates database name and ip address at the port.
We are using below database which consists of Dogs and Users table.
It is followed by the username and the password. In real world you will never give out a
password like this(always keep password encryption ON). You will try to encrypt and decrypt
the password correspondingly so that it becomes easy to share the code. After username
password we will also argument for initial capacity to 10 that means 10 connections will be
available in the form of cache and which can be used correspondingly.
Create a method to print statistics public void printstacks()
Public void printStacks(){
System.out.println(“ Available connections --->”+availableConnections.size());
System.out.println(“ In use connections --->”+occupiedConnections.size());
Below is code for retrieving connection and print stacks.
Now will run the program to see the output of DbConnectionPool.
In the shown output image you will see –
The connections were received.
2 in use connections we got out of 10 connections.
Available connections were 8.
Releasing the connection and print Stacks again the release connection became available in the
AvailableConnection and in use connection it is 1.
So the advantage of using the Connection Pooling is that it gives choice of how many
connections is required and it stores same.
There is a method we need to write to increase no. of connections. The loop becomes same and
instead of using initial capacity we can use more. When we do this we will also have to pass this
parameters because we are not storing it somewhere. If we have stored in the class we need not
have to do this so we can again keep it same as earlier one and we can again pass the int more.
In real world never use or make a connection pool unless you have some sort of custom
requirement. We will make use of connection pools because there are many connection pools
already available as third-party dependencies. Some available connection pool are – Apache
DPCP , Apache DB connection pool, C3 connection pool and also there is super-fast lite weight
connection pooling by Hikari. Third part connection pooling gives us same features that we saw
and also many more options and properties. This is a compete working coding example which
makes use of connection and use of a connection to store all the available connections.
GO DOWN BELOW TO THE DESCRIPTION TO GET MORE
DETAILED VIDEO LINK FOR SAME SOLUTIONS OF SNAKES
& LADDERS AND CONNECTION POOLING BY
THANK YOU FOR WATCHING…………..
Ad

More Related Content

Similar to Most asked JAVA Interview Questions & Answers. (20)

Snake project report
Snake project reportSnake project report
Snake project report
Manju Rajput
 
Java Guessing Game Number Tutorial
Java Guessing Game Number TutorialJava Guessing Game Number Tutorial
Java Guessing Game Number Tutorial
OXUS 20
 
Computer Science Homework Help
Computer Science Homework HelpComputer Science Homework Help
Computer Science Homework Help
Programming Homework Help
 
BSidesDelhi 2018: Headshot - Game Hacking on macOS
BSidesDelhi 2018: Headshot - Game Hacking on macOSBSidesDelhi 2018: Headshot - Game Hacking on macOS
BSidesDelhi 2018: Headshot - Game Hacking on macOS
BSides Delhi
 
How to create_your_own_android_app
How to create_your_own_android_appHow to create_your_own_android_app
How to create_your_own_android_app
Charo Cuart
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
Aimee Maree Forsstrom
 
Copy of repast javagettingstarted
Copy of repast javagettingstartedCopy of repast javagettingstarted
Copy of repast javagettingstarted
Nimish Verma
 
Programming in as3 the basics
Programming in as3 the basicsProgramming in as3 the basics
Programming in as3 the basics
Joseph Burchett
 
Introduction to Genetic Algorithms with Python - Hello World!
Introduction to Genetic Algorithms with Python  - Hello World!Introduction to Genetic Algorithms with Python  - Hello World!
Introduction to Genetic Algorithms with Python - Hello World!
Cℓinton Sheppard
 
Nullcon Hack IM 2011 walk through
Nullcon Hack IM 2011 walk throughNullcon Hack IM 2011 walk through
Nullcon Hack IM 2011 walk through
Anant Shrivastava
 
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdf
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdfLab Assignment 17 - Working with Object ArraysIn the old days we w.pdf
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdf
eyewaregallery
 
First game using c language
First game using c languageFirst game using c language
First game using c language
Saurabh Khetan
 
Going loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxGoing loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptx
Amy Nightingale
 
Dodo does-math
Dodo does-mathDodo does-math
Dodo does-math
Mohammed Kemal
 
ForLoops.pptx
ForLoops.pptxForLoops.pptx
ForLoops.pptx
RabiyaZhexembayeva
 
final presentation of sudoku solver project
final presentation of sudoku solver projectfinal presentation of sudoku solver project
final presentation of sudoku solver project
Arafat Bin Reza
 
Noughts and Crosses Design Information
Noughts and Crosses Design InformationNoughts and Crosses Design Information
Noughts and Crosses Design Information
Christopher Orchard
 
7.Advanced Scripts in Scratch.pptx
7.Advanced Scripts in Scratch.pptx7.Advanced Scripts in Scratch.pptx
7.Advanced Scripts in Scratch.pptx
dipalishewale2
 
Snake game implementation in c
Snake game implementation in cSnake game implementation in c
Snake game implementation in c
Upendra Sengar
 
Scratch for kids syllabus for 5 hours by bibek pandit
Scratch for kids syllabus for 5 hours by bibek panditScratch for kids syllabus for 5 hours by bibek pandit
Scratch for kids syllabus for 5 hours by bibek pandit
BibekPandit2
 
Snake project report
Snake project reportSnake project report
Snake project report
Manju Rajput
 
Java Guessing Game Number Tutorial
Java Guessing Game Number TutorialJava Guessing Game Number Tutorial
Java Guessing Game Number Tutorial
OXUS 20
 
BSidesDelhi 2018: Headshot - Game Hacking on macOS
BSidesDelhi 2018: Headshot - Game Hacking on macOSBSidesDelhi 2018: Headshot - Game Hacking on macOS
BSidesDelhi 2018: Headshot - Game Hacking on macOS
BSides Delhi
 
How to create_your_own_android_app
How to create_your_own_android_appHow to create_your_own_android_app
How to create_your_own_android_app
Charo Cuart
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
Aimee Maree Forsstrom
 
Copy of repast javagettingstarted
Copy of repast javagettingstartedCopy of repast javagettingstarted
Copy of repast javagettingstarted
Nimish Verma
 
Programming in as3 the basics
Programming in as3 the basicsProgramming in as3 the basics
Programming in as3 the basics
Joseph Burchett
 
Introduction to Genetic Algorithms with Python - Hello World!
Introduction to Genetic Algorithms with Python  - Hello World!Introduction to Genetic Algorithms with Python  - Hello World!
Introduction to Genetic Algorithms with Python - Hello World!
Cℓinton Sheppard
 
Nullcon Hack IM 2011 walk through
Nullcon Hack IM 2011 walk throughNullcon Hack IM 2011 walk through
Nullcon Hack IM 2011 walk through
Anant Shrivastava
 
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdf
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdfLab Assignment 17 - Working with Object ArraysIn the old days we w.pdf
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdf
eyewaregallery
 
First game using c language
First game using c languageFirst game using c language
First game using c language
Saurabh Khetan
 
Going loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxGoing loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptx
Amy Nightingale
 
final presentation of sudoku solver project
final presentation of sudoku solver projectfinal presentation of sudoku solver project
final presentation of sudoku solver project
Arafat Bin Reza
 
Noughts and Crosses Design Information
Noughts and Crosses Design InformationNoughts and Crosses Design Information
Noughts and Crosses Design Information
Christopher Orchard
 
7.Advanced Scripts in Scratch.pptx
7.Advanced Scripts in Scratch.pptx7.Advanced Scripts in Scratch.pptx
7.Advanced Scripts in Scratch.pptx
dipalishewale2
 
Snake game implementation in c
Snake game implementation in cSnake game implementation in c
Snake game implementation in c
Upendra Sengar
 
Scratch for kids syllabus for 5 hours by bibek pandit
Scratch for kids syllabus for 5 hours by bibek panditScratch for kids syllabus for 5 hours by bibek pandit
Scratch for kids syllabus for 5 hours by bibek pandit
BibekPandit2
 

More from Questpond (8)

30 C# Interview Questions and Answers
30 C# Interview Questions and Answers30 C# Interview Questions and Answers
30 C# Interview Questions and Answers
Questpond
 
OOP interview questions & answers.
OOP interview questions & answers.OOP interview questions & answers.
OOP interview questions & answers.
Questpond
 
Explain Delegates step by step.
Explain Delegates step by step.Explain Delegates step by step.
Explain Delegates step by step.
Questpond
 
AOT(Ahead Of Time)
AOT(Ahead Of Time)AOT(Ahead Of Time)
AOT(Ahead Of Time)
Questpond
 
What is CLS in .NET programming.
What is CLS in .NET programming.What is CLS in .NET programming.
What is CLS in .NET programming.
Questpond
 
Explain CTS in detail.
Explain CTS in detail. Explain CTS in detail.
Explain CTS in detail.
Questpond
 
Learn .NET step by step :- What is IL code in .NET?
Learn .NET step by step :- What is IL code in .NET?Learn .NET step by step :- What is IL code in .NET?
Learn .NET step by step :- What is IL code in .NET?
Questpond
 
What is Higher Language and Lower Language in programming.
What is Higher Language and Lower Language in programming.What is Higher Language and Lower Language in programming.
What is Higher Language and Lower Language in programming.
Questpond
 
30 C# Interview Questions and Answers
30 C# Interview Questions and Answers30 C# Interview Questions and Answers
30 C# Interview Questions and Answers
Questpond
 
OOP interview questions & answers.
OOP interview questions & answers.OOP interview questions & answers.
OOP interview questions & answers.
Questpond
 
Explain Delegates step by step.
Explain Delegates step by step.Explain Delegates step by step.
Explain Delegates step by step.
Questpond
 
AOT(Ahead Of Time)
AOT(Ahead Of Time)AOT(Ahead Of Time)
AOT(Ahead Of Time)
Questpond
 
What is CLS in .NET programming.
What is CLS in .NET programming.What is CLS in .NET programming.
What is CLS in .NET programming.
Questpond
 
Explain CTS in detail.
Explain CTS in detail. Explain CTS in detail.
Explain CTS in detail.
Questpond
 
Learn .NET step by step :- What is IL code in .NET?
Learn .NET step by step :- What is IL code in .NET?Learn .NET step by step :- What is IL code in .NET?
Learn .NET step by step :- What is IL code in .NET?
Questpond
 
What is Higher Language and Lower Language in programming.
What is Higher Language and Lower Language in programming.What is Higher Language and Lower Language in programming.
What is Higher Language and Lower Language in programming.
Questpond
 
Ad

Recently uploaded (20)

Tax evasion, Tax planning & Tax avoidance.pptx
Tax evasion, Tax  planning &  Tax avoidance.pptxTax evasion, Tax  planning &  Tax avoidance.pptx
Tax evasion, Tax planning & Tax avoidance.pptx
manishbaidya2017
 
The History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptxThe History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdfRanking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Rafael Villas B
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
TechSoup
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
Lecture 4 INSECT CUTICLE and moulting.pptx
Lecture 4 INSECT CUTICLE and moulting.pptxLecture 4 INSECT CUTICLE and moulting.pptx
Lecture 4 INSECT CUTICLE and moulting.pptx
Arshad Shaikh
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
Computer crime and Legal issues Computer crime and Legal issues
Computer crime and Legal issues Computer crime and Legal issuesComputer crime and Legal issues Computer crime and Legal issues
Computer crime and Legal issues Computer crime and Legal issues
Abhijit Bodhe
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
How to Add Customer Note in Odoo 18 POS - Odoo Slides
How to Add Customer Note in Odoo 18 POS - Odoo SlidesHow to Add Customer Note in Odoo 18 POS - Odoo Slides
How to Add Customer Note in Odoo 18 POS - Odoo Slides
Celine George
 
03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.
MCH
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
Lecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptx
Lecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptxLecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptx
Lecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptx
Arshad Shaikh
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
Lecture 1 Introduction history and institutes of entomology_1.pptx
Lecture 1 Introduction history and institutes of entomology_1.pptxLecture 1 Introduction history and institutes of entomology_1.pptx
Lecture 1 Introduction history and institutes of entomology_1.pptx
Arshad Shaikh
 
Tax evasion, Tax planning & Tax avoidance.pptx
Tax evasion, Tax  planning &  Tax avoidance.pptxTax evasion, Tax  planning &  Tax avoidance.pptx
Tax evasion, Tax planning & Tax avoidance.pptx
manishbaidya2017
 
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdfRanking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Rafael Villas B
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
TechSoup
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
Lecture 4 INSECT CUTICLE and moulting.pptx
Lecture 4 INSECT CUTICLE and moulting.pptxLecture 4 INSECT CUTICLE and moulting.pptx
Lecture 4 INSECT CUTICLE and moulting.pptx
Arshad Shaikh
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
Computer crime and Legal issues Computer crime and Legal issues
Computer crime and Legal issues Computer crime and Legal issuesComputer crime and Legal issues Computer crime and Legal issues
Computer crime and Legal issues Computer crime and Legal issues
Abhijit Bodhe
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
How to Add Customer Note in Odoo 18 POS - Odoo Slides
How to Add Customer Note in Odoo 18 POS - Odoo SlidesHow to Add Customer Note in Odoo 18 POS - Odoo Slides
How to Add Customer Note in Odoo 18 POS - Odoo Slides
Celine George
 
03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.
MCH
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
Lecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptx
Lecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptxLecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptx
Lecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptx
Arshad Shaikh
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
Lecture 1 Introduction history and institutes of entomology_1.pptx
Lecture 1 Introduction history and institutes of entomology_1.pptxLecture 1 Introduction history and institutes of entomology_1.pptx
Lecture 1 Introduction history and institutes of entomology_1.pptx
Arshad Shaikh
 
Ad

Most asked JAVA Interview Questions & Answers.

  • 1. JAVAInterview Questions and Answers with Practical example Questions discussed as a part of this course areon – 1. Snake & Ladder 2. Connection Pooling
  • 2. Why and what this course is all about? In order to understand this demonstration you should have to know the basics of arrays and collections from JAVA Perspective. The three major part of this course are – • Logic Development • Designing & • Converting design into Coding With practical interview questions you will also learn to improve your coding capability. To develop your coding capability first learn to think logically and then convert that logic to design. This concept goes as per the demand of today’s IT industry. These coding questions play an important role during the interview process right from software developer all the way till architects level. Here will be thoroughly understanding the solutions to some of the important coding questions which will enable you to clear interview very easily.
  • 3. Snake & Ladder What is Snake & Ladder? It is one of the popular board game worldwide mainly amongst children. It is played with the help of a Dice where a dice has six sides with number 1 to 6. In the middle of the game you will come across ladder climb and snake bite/snake mouth. Snake bite will bring you down all the way till its tail position and ladder will help you going up. Players roll the dice one by one and when they roll the dice based upon the points in the dice they will move starting from 1 and their aim is to reach 100. If 6 comes in the dice then the player can roll again. Snake & Ladder game consists of 2 or more players and the one who reaches 100 gets declared as winner. Will be writing a program for Snakes and Ladders with practical examples. We will try to capture the points where the snake’s mouth is which also known as head and where the snake’s tail goes we will do coding for the same and how this game works so to see the same will create solution here.
  • 4. Solution to this question – In this solution we will code to get output for below – 1. Capture positions where snake head and tail exists. 2. Capture positions where ladder start and end exists. 3. Capture the Dice Value. 4. Game ends if player reaches end. To start with the coding of this program first we will create a new Maven project with name snake-and-ladder. And inside this Maven project we will create the program to perform Snake and Ladder
  • 5. Create a new package called as com.vishwa.snakeladder and inside this we will create a JAVA Class and will call it as GameMain and within this JAVA Class we will write our public static void main program. Now next step is we need to create positions where Snakes and Ladders exist. We will create a method getSnakePositions. Create a Map entry within this to store Snake Positions. We can create a treemap and return this to store the positions.
  • 6. Same way we will write method to get Ladder positions. After doing above steps we will capture head and tail positions of snakes for which we will write below code :-
  • 7. Same way we will write method to get Ladder positions. Both of the above written code will help us maintaining the positions. Now within our main method will call MAPS using hard coded values. Also we need to capture no. of players or participants by using SCANNER. Scanner(System.in) will allow us to capture the input from the console and we can get the no. of participants and we can just print out the no. of players.
  • 8. Each player of Snake & Ladder game will roll a dice to get random output. So our next step is to write Roll Dice function with the range of 1 to 6. We can use random class which is available in JAVA. Now the logic of the game is to catch a Boolean value which will be false and variable will be set True whenever the game is over, until the game is not over will keep on looping, looping will continue the game. We will also need other things like variable to indicate current participants and collection to store score of each participant. Within the while loop will print the player no where currentPlayer will tell how many players are playing the game currently. For which we need to write below function –
  • 9. Further to that we will require Score of each participant. To get Score we have something called as ARRAY. This score will get stored in COLLECTION which is implemented by Array and we can print it. Also create integer score which capture same number as the no. of participants where we will initialize everything to 0 as an Array starts with 0. Here we need to do score[currentPlayer-1]); because current player starts with 1 while within the array it starts with 0 that’s why we have to do this.
  • 10. We will write code for where user will roll dice. Current Score of the player and roll dice will make participants go to next position. Writing this code will give us random dice. Below that we also create temporary score where participants would reach. This temporary score will take participant to snake mouth or to climb ladder and to determine the same we will use if loop. If temporary score is present there then the user will not go to the location which we found out first but will go to the location which is given by the value of the score.
  • 11. The user will go lower if snake bites and if the case is different if user will go to the location which will be a head due to the ladder. Ladder always go to the higher location so both of these values are captured here. Using else and if conditions we can make participants go ahead or behind. To make it more user friendly will write the statements as snake bite for going down and ladder climb for going ahead.
  • 12. Next step is to declare Boolean Variables to check condition. We have 3 Boolean variables that are as follows – • boolean isSnakeBite • boolean isLadderClimb • boolean isDiceSix =false The Boolean values which we have created we will initialize them to false so when we go to the condition we can come to know whether they are at this location only. We can isSnakeBite = true; , isLadderClimb = true; isdicevalue correct that also we need DiceSix = (dicevalue ==6); If dice value comes six each dice value will become true else it will become false. If player got 6 he can continue to roll the dice. After getting 6 and if he reaches the position where snake bites him so he cannot continue or retry. other cases he will get a retry so we have to check for that. Also we will have to check after the calculation of temp score if temp score 0 then what will happen is we can say the game will be over. Let’s set condition and method for the same in our code.
  • 14. After this we will see retry condition. For example participant is at 97, he rolls the dice and gets 6 then in such he will not get another chance to roll dice. There are many conditions but first two important conditions are Snake should not hit the player and the temp score should be less than or equal to100, it should not be more than 100. Another condition is that Dice Six or Ladder Climb, in this two cases player will get chance to retry so will put this condition also. Else there is no retry so we will have to implies the current players, if we have three current players current player started with 1 next will be 2 and then 3, after 3 again it’s a round robin fashion means other three players will get chance to roll the dice or depending on how many players are in the game other players will get chance to play. And finally we have to capture/store the score of current player driven by temp score. If the player is hit by snake or he climbs ladder, in these cases temp score is reflected if that is not the case then the tempScore will be the value of the current score + dice value.
  • 15. We will also need a roll dice post pressing button for user with the use of Sanner for which you will write below highlighted code lines. One more we have to do is to have an enter option. Use scanner.nextLine(); is capable of taking enter task by participants.
  • 16. At the start of the game we should see two statements as Welcome to snake and ladder tournament – After doing correct coding the output you will get as below –
  • 17. At the start of the game we should see two statements as Welcome to snake and ladder tournament – After doing correct coding the output you will get as below –
  • 18. This was a short demonstration with code snippet on Snake & Ladder game where we coded for Snake Bite, Ladder Climb, Snake Position, Ladder Position, DiceSix, Roll Dice, Temp Score, Starting Point, End game, Enter key. The advantage of writing a program in this manner is that we can extend to any number of players to make it a full tournament as per the expectation of people.
  • 19. CONNECTION POOLING Understand what exactly is Connection Pool in JAVA? Connection pooling is a Data Access Pattern which deals more with data. It maintains a Cache of connections which includes all available connections also the connections which are at use. Its moto is to reduce over head. The arrows in below diagram shows that used connections are given back to the available pool for reuse. We will try to maintain a pool of available connections. This pool will store N number of connections. This connection pooling can be done using any database. In our example we will implement the connection pool using MySQL Database in JAVA.
  • 20. First, in our pom.xml we need to add the dependency of mysql-connector-java to make use of JDBC connector to connect to database. Inside package we have creates new package which we named as com.Vishwa and inside this will create two more new packages “ConnectionPool” and “util”. Within util package we will create a class “Connectionutil” After this the first step we have to do is create method to get a database connection. The jar will be initialized within this package for which we loaded Driver class within try catch block. This driver class is coming with new mysql driver. This is new version of mysql jar which contains “cj” within the entire package. Driver class changes from database to database, you are free to use whatever database driver is available for your particular database. Incase, you are using different database than mysql we have to use drive class of that that database.
  • 21. Next step is to create connection object. Inside DriverManager class we getConnection where we need dbUrl, Username and Password. Also pass an argument for these three functions(dbUrl, Username and Password) and inside try catch we will store it as it will thrown an exception. We will include standard e.printStackTrace(); which is available with exception and we will return connection and this will get replaced with loggers. This try catch block of loading drivers will be placed inside a static block which we will execute only at the time of class loading and it will not get loaded every time and once this code is ready will format the code (Click on Code  Format Code) to make it look good.
  • 23. And utility class helps us to create DB connection. This utility we will use inside our coding class and name this as DbConnectionPool. Now inside this DbConnectionPool we will create public method returning a connection. We can pass list of properties or map of property or simply properties within getDbConnectionPool. To pass these properties we will require dbUrl, we can also pass username as well as password. One more optional attribute which we can pass is “int initialCapacity” , this attribute will tell us how many connections we want to maintain in the pool. DbConnectionPool is public static method and <ListConnection> is we will mark as private method, will name it as availableconnections.
  • 24. We will have to import the corresponding interfaces and packages. get dbConnection instead of making this as static we can keep it private so that it becomes available at variable level and create a private constructor. Within this private constructor we can pass this properties which we have so that it can use it correspondingly in creating object. Now inside initial capacity code will put our try catch block and within this we can create our connections and add it within availableConnections. Due to intial capacity method we can call our ConnectionUtil. We will make this as a static method because it is a utility method. Generally utility methods are generally static, we can say ConnectionUtil.createDbConnection() and pass the dbUrl followed by the username and password. These are the available connections, so we are creating number of connections and adding to the availabelConnections. We can return new DbConnectionPool with all these properties which we passed as a part of the method. DbConnectionPool we will mark as public so it can be called by all and availableConnection is marked private as it can be called by within function only.
  • 25. Then our next step will be to create list of busy/occupied connections.
  • 26. We will need to export a public method for retrieve connection and within retrieve connection we will check if available connections is empty. If the connections are empty will print a message as No connection available or else we can return a connection here. We can add this connection to the occupied Connections and then remove it from the available Connections. After applying this method this will get removed and at final we can return the connection. This “retreieveConnection” method will allow to retrieve the connection. It can throw us an exception or return us null if connections are not available.
  • 27. Next task is to create release method with Boolean datatype. For releasing connection we will require the connection object. availableConnection.add(connection); and again Boolean isRemoved = occupiedConnection.remove() , remove can also take an object so we will pass the connection object and then finally return isRemoved; We will put System.put.println(“connection released “ +isRemoved); Also at the time of getting connection we can say connection received. Below is the code to retrieve the connection and create a release method.
  • 28. By using two list we are able to maintain a list of availableConnections as well as the list of occupiedConnections. The second list i.e. occupiedConnections is optional, we can remove it from the main list and then again add it after use. Here we completes the implementation of Simple DbConnectionPool. Now will run this program, for that we need to create DbConnectionPoolTestClass.
  • 29. Inside this class we will create Public static void main and within this we will create DbConnectionPool and will pass dbUrl. In case of My SQL we can pass dbUrl like this. It indicates database name and ip address at the port. We are using below database which consists of Dogs and Users table.
  • 30. It is followed by the username and the password. In real world you will never give out a password like this(always keep password encryption ON). You will try to encrypt and decrypt the password correspondingly so that it becomes easy to share the code. After username password we will also argument for initial capacity to 10 that means 10 connections will be available in the form of cache and which can be used correspondingly. Create a method to print statistics public void printstacks() Public void printStacks(){ System.out.println(“ Available connections --->”+availableConnections.size()); System.out.println(“ In use connections --->”+occupiedConnections.size());
  • 31. Below is code for retrieving connection and print stacks. Now will run the program to see the output of DbConnectionPool.
  • 32. In the shown output image you will see – The connections were received. 2 in use connections we got out of 10 connections. Available connections were 8. Releasing the connection and print Stacks again the release connection became available in the AvailableConnection and in use connection it is 1. So the advantage of using the Connection Pooling is that it gives choice of how many connections is required and it stores same. There is a method we need to write to increase no. of connections. The loop becomes same and instead of using initial capacity we can use more. When we do this we will also have to pass this parameters because we are not storing it somewhere. If we have stored in the class we need not have to do this so we can again keep it same as earlier one and we can again pass the int more.
  • 33. In real world never use or make a connection pool unless you have some sort of custom requirement. We will make use of connection pools because there are many connection pools already available as third-party dependencies. Some available connection pool are – Apache DPCP , Apache DB connection pool, C3 connection pool and also there is super-fast lite weight connection pooling by Hikari. Third part connection pooling gives us same features that we saw and also many more options and properties. This is a compete working coding example which makes use of connection and use of a connection to store all the available connections.
  • 34. GO DOWN BELOW TO THE DESCRIPTION TO GET MORE DETAILED VIDEO LINK FOR SAME SOLUTIONS OF SNAKES & LADDERS AND CONNECTION POOLING BY THANK YOU FOR WATCHING…………..