Can we overload static method in Java Program - Example

Overloading static method In Java
Yes, we can overload static method in Java. In terms of method overloading static method are just like normal methods and in order to overload static method you need to provide another static method with same name but different method signature. Static overloaded method are resolved using Static Binding during compile time. Overloading method in Java is completely different than overriding method and as discussed in our last article we can not override static method in Java but we can certainly overload static method in Java. Here is an example which confirms that we can overload static method in Java:

Can we override private method in Java - Example program

No, We can not override private method in Java, just like we can not override static method in Java. Like static methods, private method in Java is also bonded during compile time using static binding by Type information and doesn't depends on what kind of object a particular reference variable is holding. Since method overriding works on dynamic binding, its not possible to override private method in Java. private methods are not even visible to Child class, they are only visible and accessible in the class on which they are declared. private keyword provides highest level of Encapsulation in Java. Though you can hide private method in Java by declaring another private method with same name and different method signature.

Top 23 Spring MVC Framework Interview Questions Answers - Java JEE

Spring Interview Questions Answers 
Spring Interview Question is one of the first things Java programmer should prepare before appearing on any Java or Spring interview. With growing popularity of Spring framework in Java world, Interview questions on Spring are getting more important day by day. For those who don't know, Spring framework is one of the most popular Java programming framework, which not only provided dependency Injection and Inversion of Control but also provides useful API to Java programmers. Spring framework is divided into many different modules e.g. Spring MVC, Spring Integration, Spring Batch, Spring LDAP, Spring Security and several other modules. Based on your work experience, Interviewer can ask questions from core Spring or these modules. That's why, while preparing Spring interview question focus on Spring core, Spring Security, and Spring API, these are main areas from where interviewer ask questions.

Difference between Abstraction and Encapsulation in Java - OOPS

Abstraction vs Encapsulation – Java OOPS
Abstraction and Encapsulation in Java are two important Object oriented programming concept and they are completely different to each other. Only similarity between Abstraction and Encapsulation is that they are OOPS concept, other than that they mean two different things. Abstraction represent taking out the behavior from How exactly its implemented, one example of abstraction in Java is interface while Encapsulation means hiding details of implementation from outside world so that when things change no body gets affected. One example of Encapsulation in Java is private methods; clients  don't care about it, You can change, amend or even remove that method  if that method is not encapsulated and it were public all your clients would have been affected. Apart from this main difference in behavior here are couple of more differences between Abstraction and Encapsulation in Java.

Can we override static method in Java - Method Hiding

Can we override static method in Java
No, you cannot override static method in Java because method overriding is based upon dynamic binding at runtime and static methods are bonded using static binding at compile time. Though you can declare a method with same name and method signature in sub class which does look like you can override static method in Java but in reality that is method hiding. Java won't resolve method call at runtime and depending upon type of Object which is used to call static method, corresponding method will be called. It means if you use Parent class's type to call static method, original static will be called from patent class, on ther other hand if you use Child class's type to call static method, method from child class will be called. In short you can not override static method in Java. If you use Java IDE like Eclipse or Netbeans, they will show warning that static method should be called using class name and not by using object becaues static method can not be overridden in Java.

What is method overriding in Java – Example Tutorial

Method overriding in Java
Method overriding in Java is a concept based on polymorphism OOPS concept which allows programmer to create two methods with same name and method signature on interface and its various implementation and actual method is called at runtime depending upon type of object at runtime. Method overriding allows you to write flexible and extensible code in Java because you can introduce new functionality with minimal code change. Method overriding is different than method overloading in Java which we have discussed in last article. In method overloading, Only name of two overloaded methods are same but method signature must be different while in method overriding, method signature must be same. method overriding represent true polymorphic behaviour, where only name needs to be same underlying method logic can be different. In this Java tutorial we will see What is method overriding in Java, Rules to override method in Java and an example of How to override method in Java. We won't discuss difference between method overloading and overriding in Java, may be some other post.

What is method overloading in Java - Example Tutorial

What is method overloading in Java
Method overloading in Java is a programming concept when programmer declares two methods of the same name but with different method signature, e.g. change in the argument list or change in the type of argument. method overloading is a powerful Java programming technique to declare a method which does a similar performance but with a different kind of input. One of the most popular examples of method overloading is System.out.println() method which is overloaded to accept all kinds of data types in Java. You have println() method which takes String, int, float,double or even char in output. All of those methods are collectively referred as an overloaded method in Java. The difference between method overloading and overriding is also a popular Java interview question. In next section, we will some important points about method overloading in Java and then a simple example of how to overload a method in Java.

Difference between String and StringBuffer in Java

String vs StringBuffer in Java
String and StringBuffer are two classes which are most widely used in any Java program. If I say you can not write a program without using String in Java then it would not be an exaggeration. The string is everywhere, the main method accepts String argument, logs are String etc. Though many Java programmers familiar with String, not many are careful while performing operations on String, Since String is final in Java; every operation e.g. converting String into Uppercase, creating SubString,  converting String to Lowercase all result in a separate new String Object, which can take trigger frequent garbage collection and affect your application performance. here comes StringBuffer in Java which is a mutable version of String, though it's not as feature rich as String and you can not use StringBuffer in place of String but StringBuffer should be used whenever you are performing String concatenation instead of String in Java.

10 Things Every Java developer Should Know about Package concept

What is package in Java
package in Java is a way to organize related functionality in single place. If you look at File System package in Java represent a directory where Java source file is stored in compilation and class files are stored after compilation. For example, if you create a class HelloWorld in a package called com.java67.welcome; then it will reside under directory com/java67/welcome in the source tree and you can view that in your IDE like Eclipse or Netbeans or even by navigating to file system. once you compile your Java program either by using your IDE, Ant build Script or maven compile plugin; it creates class files under same package structure. For example, maven will create target/classes/com/java67/welcome directory and place HelloWorld.class inside that. Its mandatory that class files reside on same package or directory as declared in there source file using package keyword, failure to do will result in java.lang.NoClassDefFoundError in Java. In summary answer of the question What is package in Java can be as simple as that package is a keyword in Java which is used to specify directory structure for the particular class file.

What is Thread and Runnable in Java - Example

What is Thread in Java
Thread in Java is an independent path of execution which is used to run two task in parallel. When two Threads run in parallel that is called multi-threading in Java. Java is multithreaded from the start and excellent support of Thread at language level e.g. java.lang.Thread class, synchronized keyword, volatile and final keyword makes writing concurrent programs easier in Java than any other programming language e.g. C++. Being multi-threaded is also a reason of Java's popularity and being number one programming language. On the other hand if your program divides a task between two threads it also brings lot of programming challenges and issues related to synchronization, deadlock, thread-safety and race conditions. In short answer of question What is Thread in Java can be given like "Thread is a class in Java but also a way to execute something in parallel independently in Java". Thread in Java requires a task which is executed by this thread independently and that task can be either Runnable or Callable which we will see in next section along with an example of  How to use multiple Thread in Java. Difference between Thread and Runnable in Java is also a popular thread interview question in Java.

What is class file in Java - How to create Class File

What is class file in Java
Class file in Java is compiled form of Java source file. When we compile Java program which is written in Java source file  ended with .java extension, it produces one more class files depending upon how many classes are declared and defined in that Java source file. One Java source file can only contain one public class and its name must match with name of file e.g. file can contain a public class whose name should be HelloWorld as shown below :

What is transient variable in Java - Serialization Example

What is transient variable in Java
transient variable in Java is a variable whose value is not serialized during Serialization and which is initialized by its default value during de-serialization, for example for object transient variable it would be null. this behavior can be customized by using Custom Serialized form or by using Externalizable interface. transient variable is used to prevent any object from being serialized and you can make any variable transient by using transient keyword. By the way difference between transient and volatile variable in Java is a famous Java interview question but transient variable is completely different than volatile variable which we have discussed in our post What is volatile variable in Java. In next section we will see complete example of serialization where we will first serialize an instance of Book class which implements Serializable and than de-serialize to see What is the value of transient variable after deserialization.

What is volatile variable in Java - When to use

What is Volatile variable in Java
volatile variable in Java is a special variable which is used to signal threads, a compiler that this particular variables value are going to be updated by multiple threads inside Java application. By making a variable volatile using the volatile keyword in Java, application programmer ensures that its value should always be read from main memory and thread should not use cached value of that variable from their own stack. With the introduction of Java memory model from Java 5 onwards along with introduction of CountDownLatch, CyclicBarrier, Semaphore and ConcurrentHashMap, volatile variable also guarantees "happens-before" relationship, which means not only another thread has visibility of latest value of volatile variable but also all the variable is seen by the thread which has updated value of volatile variable before these threads sees it. What is volatile variable and when to use it is always a popular Java threading question.

How to traverse iterate or loop ArrayList in Java

How to Loop ArrayList in Java
Iterating, traversing or Looping ArrayList in Java means accessing every object stored in ArrayList and performing some operations like printing them. There are many ways to iterate, traverse or Loop ArrayList in Java e.g. advanced for loop, traditional for loop with size(), By using Iterator and ListIterator along with while loop etc. All the method of Looping List in Java also applicable to ArrayList because ArrayList is an essentially List. In next section we will see code example of Looping ArrayList in Java.

Difference between HashSet and HashMap in Java

HashSet and HashMap in Java
HashSet vs HashMap is a classical Java Collection interview question which focuses on What are differences between HashSet and HashMap in terms of features, usage, and performance. If you are in Java programming even for a year or so, you are likely to be familiar with What is HashSet in Java and What is HashMap in Java, these two are most popular collection classes. Despite being hash based collection HashSet and HashMap are different to each other because the underlying interface is different. HashSet implements Set interface via extending AbstractSetclass and HashMap implements Map interface. Before seeing differences between let's see what is common between HashSet and HashMap in Java:

5 difference between Hashtable and HashMap in Java

Hashtable vs HashMap in Java
Hashtable and HashMap are two hash based collection in Java and used to store objects as key value pair. Despite being hash based and similar in functionality there are a significant difference between Hashtable and HashMap and without understanding those difference if you use Hashtable in place of HashMap than you may run into series of subtle programs which is hard to find and debug.Unlike Difference between ArrayList and HashMap,  Difference between Hashtable and HashMap are more subtle because both are similar kind of collection. Before seeing difference between HashMap and Hashtable let's see some common things between HashMap and Hashtable in Java.

Difference between HashMap and ConcurrentHashMap in Java Collection

HashMap vs ConcurrentHashMap in Java
ConcurrentHashMap in Java is introduced as an alternative of Hashtable in Java, which is a synchronized collection class, that makes the main difference between HashMap and ConcurrentHashMap which is one is non-synchronized , non-thread safe and not for use in Concurrent multi-threaded environment while ConcurrentHashMap is a thread-safe collection and intended to be used as primary Map implementation especially for multi-threaded and Concurrent environment. Apart from thread-safety, there are some subtle differences between HashMap and ConcurrentHashMap which we will see in this article. By the way, Difference between HashMap and ConcurrentHashMap as well as ConcurrentHashMap vs Hashtable are two popular core Java interview question, mostly asked on senior level Java programmers.

Top 12 Java Thread, Concurrency and Multithreading Interview Questions For experienced

Java concurrency and thread interview questions answers
Multithreading is an important feature of Java programming language, which means threads are also an important part of any Java interview. It's true and in fact at beginners and freshers level Thread interview questions in Java are one of most difficult to answer. One reason for interview question related to multithreading and concurrency being difficult is confusion around how multiple threads works together and second is threads are genuinely a complicated topic to understand and use correctly. Mostly thread interview questions checks Java programmers knowledge on Java Thread API, Java concurrency API, issues related to multi-threading like a race condition, thread-safety, and deadlock. Some time multithreading and concurrency interview question also focus on parallel design patterns like solving the producer-consumer problem, implementing work steal pattern or solving dining philosopher problem in Java. This is especially true while interviewing experienced Java developers with 4 to 6 years of experience.

Top 10 Java Programming Coding Interview Questions Answers for programmers

Java coding interview questions answers
Java coding interview questions are mostly some programming exercises which is asked to be solved in java programming language in limited time during any core Java or J2EE interview. No matter whether you have 2 years of experience or 4 years of experience, There is always some coding interview question in Java programming job you are applying. Actually questions related to Java Coding are increasingly getting popular on Java interviews for two reasons, first its difficult to crack Java coding interview questions than answering fact based questions like Why String is immutable in Java or Why main is static in Java; Second reason of popularity of Coding question in Java interviews is read need of good developers who are required to do lot of coding in projects rather than doing some maintenance works.

10 Advanced core Java interview questions for senior and experienced programmer

Java interview questions for Senior and Experienced programmer
Java is very big and there is no way to prepare completely for any core java interview but there is a level of question depends upon your experience, if you are fresher than questions asked in Java interview are mostly based on fundamentals like Iterator vs Enumeration in Java, Why main is public static and void or may be ArrayList vs LinkedList in Java. Things changes when you apply for senior developer, Technical lead or Team Lead Java positions, questions asked on that level are more advanced and less popular among Java circles, you may be asked questions from design pattern, questions from multi-threading, Collections and even asked to write code, design classes and prepare JUnit tests. In this Java article I will share some advanced Core Java interview questions which is appear in Senior level interviews mostly on 4 to 6 years and 6 to 8 years of experience. One important thing to note is that you can not clear interview by just mugging answers of these question because interviewer is most likely asked you follow-up question based upon your response and only way to get through it is to understand the topic well.

What is PATH and CLASSPATH in Java - Path vs ClassPath

What is PATH and CLASSPATH in Java
The PATH and CLASSPATH are two most important environment variables of Java environment which is used to find the JDK binaries used to compile and run Java in windows and Linux and class files which are compiled Java bytecodes. From my personal experience I can say that PATH and CLASSPATH are two most problematic thing for beginners in Java programming language due to two reasons; first because in most of Java courses nobody tell details of what is a PATH and CLASSPATH, What do PATH and CLASSPATH do, What is meaning of setting PATH and CLASSPATH, What happens if we do not set them, Difference between PATH vs CLASSPATH in Java or simply How Classpath works in Java etc. These basic question which answers most of the details about PATH and CLASSPATH in Java are mostly not answered until Java programmer itself acquire these knowledge, Things may be changed nowadays but important of PATH and CLASSPATH is still high. Most common cause of dreaded error like java.lang.NoClassDefFoundError and java.lang.ClassNotFoundException is either incorrect or misconfigured CLASSPATH in Java.

What is main method in Java ? Why main is public static and void

What is main method in Java
main method in Java is an standard method which is used by JVM to start execution of any Java program. main method is referred as entry point of Java application which is true in case of core java application but in case of container managed environment like Servlet, EJB or MIDlet this is not true as these Java programs have there own life-cycle methods like init(), service() or destory() for Servlet's which is used by container. main method in Java is run by main thread which is a non daemon thread and Java program runs until main method finishes or any other user thread is running. When we start JVM by running java command we also provide name of class which contains main method, which is later invoked by JVM to start Java program execution. for example in below command :

How to sort ArrayList in java - List Sorting - Ascending Descending Order

How to sort ArrayList ascending descending order
Sorting ArrayList in Java is not difficult, by using Collections.sort() method you can sort ArrayList in ascending and descending order in Java. Collections.sort() method optionally accept a Comparator and if provided it uses Comparator's compare method to compare Objects stored in Collection to compare with each other, in case of no explicit Comparator, Comparable interface's compareTo() method is used to compare objects from each other. If object's stored in ArrayList doesn't implements Comparable than they can not be sorted using Collections.sort() method in Java.

What is difference between wait and sleep in Java?

Wait vs sleep in Java
Differences between wait and sleep method in Java multi-threading is one of the very old questions asked in Java interviews. Though both wait and sleep put thread on waiting state, they are completely different in terms of behavior and use cases. Thread.sleep(long millis) is meant for introducing pause, releasing CPU and giving another thread an opportunity to execute while wait is used for inter thread communication in Java. These methods are defined in java.lang.Object class and available to every object in Java. It is based upon object lock, if you remember every object in Java has implicit lock, also known as monitor. When a thread enter into a synchronized method it acquired the lock which is used to protect the critical reason e.g. it acquired lock on current object if it is going inside an instance synchronized method and lock object on class literal if its entering into a static synchronized method. By using wait() and notify() method two threads can communicate with each other which is key to solve many concurrency problems e.g. produce consumer problem, dining philosopher problem, reader and writer problem, and to implement several Concurrency designs.

Difference between List and Set in Java

List vs Set in Java
Main Difference between List and Set is that List is an ordered Collection while Set is an unordered collection. Java collection framework offers several collection classes for various needs but all collection can be divided into broadly three categories : List, Set, and Map. All List, Set, and Map are defined as interfaces and then you have several implementation like ArrayList and Vector are the popular implementation of List interface, while HashSet is a popular implementation of Set interface. In this java tutorial, we will mainly see What are differences between List and Set collection at the top level and How to choose when to use List in java and when to use Set in Java. I believe once you are able to understand the fundamental difference between List and Set you are most likely be well versed on when to use List and when to choose Set.

How Java achieves platform independence

Java is platform independent language How?
Java programming language provides platform independence, what does it mean ? It means same Java program can be run on any platform or operating system e.g. Windows, Linux or Solaris without any change. This is the great benefit for some one coming from platform dependent programming language like C or C++ whose code needs to be ported for every single platform because they use native libraries, which differ in every platform. Now question comes how Java achieve platform independence, what makes Java programs running on every platform without any change ? This is one of the most basis question Java programmer ask when they start learning Java programming language. If you read further you will come to know about class files, bytecode and Java virtual machine which together provides platform independence to Java. One of the simplest analogy I can associate with platform independence is the person taking red carpet with him and instead of walking on floor, he always walks on red carpet, no matter where he is walking. That red carpet is the JVM, your Java program runs on JVM rather on any particular platform or machine. 

How to Make Collection like ArrayList Read Only in Java?

Read only Collection in Java
You can create read-only Collection by using Collections.unmodifiableCollection() utility method. it returns a unmodifiable or read-only view of Collection in which you can not perform any operation which will change the collection like add() , remove() and set() either directly or while iterating using Iterator or ListIterator. It will throw UnsupportedOperationException whenever you try to modify the List. One of the common misconception around read only ArrayList is that, you can create read-only ArrayList by using Arrays.asList(String{[]), which is apparently not true as this method only return a fixed size list on which add() and remove() are not allowed by set() method is still allowed which can change the contents of ArrayList. Collections class also provide a different method to make List and Set read-only. In this Java tutorial, we will learn How to make any collection read only and How to create fixed size List as well.

Difference between yield and sleep in Java

Sleep vs yield in Java
Sleep and yield are two methods which are used to get CPU back from Thread to Thread Scheduler in java but they are completely different than each other. The major difference between Sleep vs yield is that sleep is more reliable than yield and it's advised to use sleep(1) instead of yield to relinquish CPU in multi-threaded Java application to give an opportunity to other threads to execute. In this Java tutorial, we will what are differences between yield and sleep in Java. But before seeing difference between sleep and Yield let's see some similarities between yield and sleep in Java

Difference between yield and wait method in Java

Yield vs wait in Java
Yield and wait method in Java, though both are related to Threads,  are completely different to each other. Main difference between wait and yield in Java is that wait() is used for flow control and inter thread communication while yield is used just to relinquish CPU to offer an opportunity to another thread for running. In this Java tutorial we will what are differences between wait and yield method in Java and when to use wait() and yield(). What is important for a Java programmer is not only understand difference between wait() and yield() method but also know implications using yield method. If your program is depends upon yield method for performance or correctness than its most likely not work perfectly on all platforms because of platform dependent nature of yield method which we will see in this Java article along with wait vs yield comparison.

How to convert Enum to String in Java with Example

Enum to String Conversion Example in Java
There are two ways to convert an Enum to String in Java, first by using name() method of Enum which is implicit method and available to all Enum and second by using toString() method. name() method of Enum returns exact same String which is used to declare a particular Enum instance like in WeekDays Enum if we have MONDAY as one Enum instance than the name() will return String "MONDAY". This method of conversion from Enum to String is useful if String representation of Enum is same as its String name but if you have different String representation then you can use toString() method. Since Enum in Java allows a programmer to override an inherited method and since Enum has access to all Object class method, you can easily override toString() method to provide a custom String implementation for an Enum instance which can further use to convert that Enum instance to String in Java.

String to Enum in Java - Conversion Example

Creating Enum from String
You can create Enum from String by using Enum.valueOf() method. valueOf() is a static method which is added on every Enum class during compile time and it's implicitly available to all Enum along with values(), name() and cardinal() methods. In order to create Enum from String, String must be same as declared Enum otherwise, the code will throw "java.lang.IllegalArgumentException: No enum const class". the same technique can be used to convert String into Enum instance as well. This is the second part of Enum conversion tutorial, in the first part, we have seen how to convert Enum to String in Java. If you have not read that yet, check it out. Also from Java 7 onwards, Java started supporting String constants in switch cases, but you should always prefer Enum over both Integer and String constant because Enum provides type safety. The compiler will ensure that incorrect value is not supplied, but in the case of String and Integer, the compiler will check whether a variable is of the correct type, but it won't check values, which is why you should use Enum to define a well-known fixed number of things. 

How to find GCD of two numbers in Java - Euclid's algorithm

How to find Greatest Common Divisor of two numbers in Java
Simple Java program to find GCD (Greatest common Divisor) or GCF  (Greatest Common Factor) or HCF (Highest common factor). The GCD of two numbers is the largest positive integer that divides both the numbers fully i.e. without any remainder. There are multiple methods to find GCD , GDF or HCF of two numbers but  Euclid's algorithm is very popular and easy to understand, of course, only if you understand how recursion works. Euclid's algorithm is an efficient way to find GCD of two numbers and it's pretty easy to implement using recursion in Java program. According to Euclid's method GCD of two numbers a, b is equal to GCD(b, a mod b) and GCD(a, 0) = a. The later case is the base case of our Java program to find GCD of two numbers using recursion. You can also calculate greatest common divisor in Java without using recursion but that would not be as easy as the recursive version, but still a good exercise from coding interviews point of view.

Difference between CountDownLatch and CyclicBarrier in Java

Difference between CountDownLatch and CyclicBarrier in Java
Both CyclicBarrier and CountDownLatch are used to implement a scenario where one Thread waits for one or more Thread to complete there job before starts processing but there is one Difference between CountDownLatch and CyclicBarrier in Java which separates them apart and that is, you can not reuse same CountDownLatch instance once count reaches to zero and latch is open, on the other hand CyclicBarrier can be reused by resetting Barrier, Once barrier is broken.

Difference between HashMap and LinkedHashMap in Java

Difference between LinkedHashMap and HashMap in Java
HashMap and LinkedHashMap are two of the most common used Map implementation in Java. Main difference between HashMap and LinkedHashMap is that LinkedHashMap maintains insertion order of keys, order in which keys are inserted in to LinkedHashMap. On the other hand HashMap doesn't maintain any order or keys or values. In terms of Performance there is not much difference between HashMap and LinkedHashMap but yes LinkedHashMap has more memory foot print than HashMap to maintain doubly LinkedList which it uses to keep track of insertion order of keys. Some time you notice that HashMap also returns elements in order e.g. before Java 8 when you use Integer key and then iterate over Map, you would see it returning entries in a particular order, but those are not guaranteed. Any code which is dependent upon ordering provided by HashMap will likely to break in future release when those behavior changes.

Difference between TreeMap and TreeSet in Java

Difference between TreeSet and TreeMap in Java
Main Difference between TreeMap and TreeSet is that TreeMap is an implementation of Map interface while TreeSet is an implementation of Set interface. There are some similarities between both TreeMap and TreeSet and few differences as well. In this Java tutorial, we will first see similarities between TreeMap and TreeSet and than you will learn some differences between TreeMap and TreeSet in Java. Key point to remember about TreeMap and TreeSet is that they use compareTo() or compare() method to compare object, So if uses puts a String object in TreeSet of Integers, add() method will throw ClassCastException at runtime prior to Java 5, with Java 5 you can use Generics to avoid this happening by declaring TreeMap and TreeSet with parametrized version. If you want to master Java Collection framework by heart, you can see Java Generics and Collection book by Maurice Naftaline, one of the best work on Java Collections framework.

Video example - Dijkstra's Algorithm shortest path in Graph

Video example - Dijkstra's Algorithm shortest path in Graph

Dijkstra's Algorithm in Graph theory allows you to find least cost path or shortest path between two nodes in directed and weighted graph. Dijkstra's Algorithm is one of the important concept of Graph theory and often asked in Exams and interviews. Frankly speaking Its not easy to understand Dijkstra's Algorithm , at least until you have a good example and this leads me to search for simple and easy to learn example of Dijkstra's Algorithm which landed me on this video. I have earlier shared Graph traversal BFS and DFS algorithm from this same author and when I found his video on Dijkstra's Algorithm, I knew this is going to be another best. By the way Dijkstra's Algorithm has several practical usage like finding shortest path between cities for Air planes route or bus route as cities and driving path between cities fits nicely
as vertices of Graph and directed and weighted path between them. In Dijkstra's Algorithm , path between two nodes which are unreachable directly is assumed as infinity. I suggest watching this video example more than one time if you are unsure how Dijkstra's Algorithm works.