Showing posts sorted by relevance for query what-is-static-and-dynamic-binding-in. Sort by date Show all posts
Showing posts sorted by relevance for query what-is-static-and-dynamic-binding-in. Sort by date Show all posts

Thursday, January 27, 2011

Can Yous Brand A Flat Static Inwards Java? Interview Question

This is i of the tricky questions inwards Java because in that place is no straight forward. Yes in addition to No reply here. You cannot brand a top-level aeroplane static inwards Java, but Yes, you tin plow over the sack brand a nested aeroplane static inwards Java. In fact, it is fifty-fifty advised (see Effective Java) to prefer a nested static class inwards Java than normal inner classes. Now, the query comes what is a top-level class, in addition to what is a nested aeroplane inwards Java? Well, you lot tin plow over the sack declare multiple classes inwards a unmarried Java source file. Influenza A virus subtype H5N1 aeroplane is said to survive the exceed aeroplane if it is non within whatever other class, in addition to a aeroplane that is within roughly other aeroplane is known every bit nested class. You tin plow over the sack do a nested aeroplane within roughly other top-level or roughly other nested aeroplane inwards Java. This is the aeroplane that tin plow over the sack survive static inwards Java.

Some of you lot must survive wondering what the do goodness of making a aeroplane static inwards Java is? Why would i brand a aeroplane static? In lodge to reply this question, let's revise the concept of what does static hateful inwards Java? Well, a static keyword tin plow over the sack survive used amongst a class, method or variable inwards Java in addition to anything static belongs to the class, which agency a static method tin plow over the sack survive accessed in addition to called simply past times using aeroplane name, i.e. you lot don't postulate to do an illustration of the aeroplane to telephone telephone this method because it belongs to class.

The same is truthful amongst static fellow member variable every bit well; you lot tin plow over the sack access them without creating an illustration of the class. They tin plow over the sack survive accessed past times using aeroplane name, e.g. Class.variable.

Influenza A virus subtype H5N1 non-static nested class, every bit good known every bit the Inner class on the mitt ever postulate an illustration of enclosing class, which agency you lot cannot do an illustration of the nested aeroplane without start creating an illustration of the outer class.

This challenge tin plow over the sack survive overcome past times declaring the nested aeroplane static inwards Java i.e. you lot tin plow over the sack straight do an illustration of a nested aeroplane without start creating an object of enclosing class.


This is the unmarried most of import argue fhy you lot should brand na ested aeroplane static inwards Java , nd this is what advised past times Joshua Bloch inwards his aall-timeclassic Java book, Effective Java.

Like whatever other inwardness Java question, nosotros should verify if compiler back upwardly theses fact or not. To banking concern fit whether nosotros can brand a aeroplane static inwards Java or not, we'll effort both exceed aeroplane in addition to a nested aeroplane static.


Using static modifier amongst a exceed aeroplane class

Let's effort to role the static modifier amongst a exceed aeroplane storey i.e. a aeroplane which is non within whatever other class. Here is the code to do that, when you lot compile this code inwards Java from the dominance trouble you lot volition meet compile fourth dimension fault because this is non permitted inwards Java:

static aeroplane Top{  ... }

In Eclipse, every bit presently every bit type the code, I have next compiler error "Illegal modifier for the aeroplane Top; solely public, abstract & concluding are permitted". You volition have something similar when you lot compile this aeroplane using javac from the command line.




Using static modifier amongst a nested aeroplane inwards Java

Now, let's effort to role the static modifier amongst a nested aeroplane inwards Java i.e. a aeroplane which is within roughly other class. Here is the code to do that in addition to this fourth dimension you lot won't meet whatever compile fourth dimension error. I'll every bit good exhibit you lot how to do an illustration of the nested static aeroplane inwards Java. Influenza A virus subtype H5N1 nested aeroplane is named past times joining the refer of the top aeroplane class in addition to nested aeroplane amongst a point every bit shown below:

class Top{  static class Nested{  ...... } }  class Test{  public static void main(String args[]){    Top.Nested n = new Top.Nested(); // ok } }

You tin plow over the sack meet that in that place is no compile fourth dimension fault this time, which agency you lot tin plow over the sack brand a nested aeroplane static inwards Java. In fact, it is every bit good a best exercise to prefer nested static aeroplane over a non-static aeroplane inwards Java because of convenience (see Effective Java).

 inwards Java because in that place is no straight forrard Can you lot Make a Class Static inwards Java? Interview Question

As you lot tin plow over the sack see, you lot don't postulate an illustration of enclosing or exceed aeroplane storey to do an illustration of the nested static class. Many Java classes follow this exercise e.g. LinkedList.Node in addition to Map.Entry is 2 pop examples of nested static aeroplane from JDK.


That's all nearly whether you lot tin plow over the sack brand a aeroplane static inwards Java. Influenza A virus subtype H5N1 static aeroplane is possible inwards Java but solely when if it is nested, you lot tin plow over the sack non brand a exceed aeroplane storey static inwards Java. Btw, don't confuse the give-and-take hither amongst a aeroplane amongst simply static methods e.g. java.lang.Math, they are every bit good known every bit a static class but that is the totally dissimilar thing.

All the give-and-take hither nearly whether you lot tin plow over the sack role the static modifier amongst a aeroplane or non in addition to every bit I explained, you lot tin plow over the sack solely role the static modifier amongst a nested aeroplane inwards Java. Trying to role a static modifier amongst a exceed aeroplane storey inwards Java.

Further Learning
Can you lot overload a static method inwards Java?
Can you lot override a static method inwards Java?
Difference betwixt the static in addition to non-static method inwards Java?
How populace static concluding variable plant inwards Java?
Difference betwixt constructor in addition to static manufacturing flora method?
Difference betwixt static in addition to dynamic binding?

Thanks a lot for reading this article thence far. If you lot similar this article thence delight portion amongst your friends in addition to colleagues, if you lot accept whatever query or feedback thence delight driblet a comment. 

Wednesday, December 11, 2019

Top Xl Centre Coffee Interview Questions Answers From Telephonic Round

Here is my to a greater extent than or less other ship nigh preparing for Java Interviews, this fourth dimension nosotros volition receive got a facial expression at 40 meat Java questions from telephonic round of Java Programming interviews. Phone interviews are unremarkably the offset measuring to covert candidate after selecting his resume. Since it's piece of cake to telephone telephone a candidate than to schedule a face-to-face interview, mass rooms in addition to conform for a meeting, telephonic circular of interviews are quite pop right away days. There were days exclusively i telephonic circular of interview was plenty but nowadays, it's almost ii in addition to iii circular of telephone interview alongside different squad members. Key to success inward telephonic interview is to the indicate in addition to concise answer. Since Interviewer wants to encompass lot of things on telephonic round, they appreciate to the indicate reply instead of blah blah in addition to dragging reply for sake of time. Always remember, its your fourth dimension to brand impression equally good therefore brand certain you lot receive got skillful phone, fully charged in addition to usage vocalism modulation technique to live equally clear equally possible. Even if you lot don't know the answer, think a loud, interviewer appreciate powerfulness to think in addition to to a greater extent than or less fourth dimension that proves to live decisive equally well.


40 Core Java Interview Questions alongside Answers

Here is my listing of xl meat Java-based questions which oft appear on telephonic circular of Interview. These questions touch-based of of import meat coffee concepts e.g. String, Thread basics, multi-threading, inter thread communication, Java Collection framework, Serialization, Object-oriented programming concepts in addition to Exception handling. If you lot receive got faced pair of Java interviews, you lot volition certain receive got seen to a greater extent than or less of these questions already. I receive got provided but plenty reply for the sake of telephonic interview, but if you lot desire to know more, you lot tin e'er banking venture check the detailed reply link.



1) Difference betwixt String, StringBuffer in addition to StringBuilder inward Java? (detailed answer)
String is immutable spell both StringBuffer in addition to StringBuilder is mutable, which agency whatsoever alter e.g. converting String to upper instance or trimming white infinite volition gain to a greater extent than or less other instance rather than changing the same instance. On after two, StringBuffer is synchronized spell StringBuilder is not, inward fact its a ditto replacement of StringBuffer added inward Java 1.5.


2) Difference betwixt extends Thread vs implements Runnable inward Java? (detailed answer)
Difference comes from the fact that you lot tin exclusively extend i course of report inward Java, which agency if you lot extend Thread course of report you lot lose your chance to extend to a greater extent than or less other class, on the other mitt if you lot implement Runnable, you lot tin even therefore extend to a greater extent than or less other class.



3) Difference betwixt Runnable in addition to Callable interface inward Java? (detailed answer)
Runnable was the exclusively way to implement a chore inward Java which tin live executed inward parallel earlier JDK 1.5 adds Callable. Just similar Runnable, Callable equally good defines a unmarried call() method but dissimilar run() it tin render values in addition to throw exceptions.


4) Difference betwixt ArrayList in addition to LinkedList inward Java? (detailed answer)
In short, ArrayList is backed past times array inward Java, spell LinkedList is but collection of nodes, similar to linked listing information structure. ArrayList equally good provides random search if you lot know the index, spell LinkedList exclusively allows sequential search. On other hand, adding in addition to removing chemical cistron from catch is efficient inward LinkedList equally compared to ArrayList because it exclusively require to modify links in addition to no other chemical cistron is rearranged.


5) What is deviation betwixt hold off in addition to notify inward Java? (detailed answer)
Both hold off in addition to notify methods are used for inter thread communication, where hold off is used to recess the thread on a status in addition to notify is used to ship notification to waiting threads. Both must live called from synchronized context e.g. synchronized method or block.


6) Difference betwixt HashMap in addition to Hashtable inward Java? (detailed answer)
Though both HashMap in addition to Hashtable are based upon hash tabular array information structure, at that topographic point are subtle deviation betwixt them. HashMap is non synchronized spell Hashtable is synchronized in addition to because of that HashMap is faster than Hashtable, equally at that topographic point is no toll of synchronization associated alongside it. One to a greater extent than pocket-size deviation is that HashMap allows a null key but Hashtable doesn't.


7) Difference betwixt TreeSet in addition to TreeMap inward Java? (detailed answer)
Though both are sorted collection, TreeSet is essentially a Set information construction which doesn't allow duplicate in addition to TreeMap is an implementation of Map interface. In reality, TreeSet is implemented via a TreeMap, much similar how HashSet is implemented using HashMap.


8) Write a Java programme to impress Fibonacci series? (solution)
 Here is my to a greater extent than or less other ship nigh preparing for Java Interviews Top xl Core Java Interview Questions Answers from Telephonic RoundFibonacci series is a series of number on which a number is equal to amount of previous ii numbers i.e. f(n) = f(n-1) + f(n-2). This programme is used to instruct recursion to students but you lot tin equally good solve it without recursion. Check out the solution for both iterative in addition to recursive solution of this problem. In telephonic interview, this enquiry is non that mutual but sometime interviewer equally good wants to banking venture check your employment solving science using such questions.


9) Write a Java programme to banking venture check if a number is Prime or not? (solution)
Influenza A virus subtype H5N1 number is said prime number if it is non divisible past times whatsoever other number except itself. 1 is non considered prime, therefore your banking venture check must start alongside 2. Simplest solution of this to banking venture check every number until the number itself to regard if its divisible or not. When Interviewer volition inquire you lot to improve, you lot tin tell that checking until foursquare root of the number. If you lot tin farther improve the algorithm, you lot volition to a greater extent than impress your interviewer. banking venture check out the solution for how to do this inward Java


10) How to Swap ii numbers without using temp variable? (solution)
This enquiry is ages old. I receive got offset seen this enquiry way dorsum inward 2005 but I am certain its fifty-fifty older than that. Good affair nigh this employment is that except XOR clit a fast i on all solution has to a greater extent than or less flaws, which is used to attempt out whether candidate actually knows his materials or not. Check out the solution for all iii possible solution in addition to drawback of each.


11) How to banking venture check if linked listing contains loop inward Java? (solution)
This is to a greater extent than or less other employment solving enquiry which is real pop inward telephonic in addition to screening  round. This is a swell enquiry to attempt out employment solving science of candidate, peculiarly if he has non seen this enquiry before. It equally good has a dainty trivial followup to respect the starting of the loop. See the solution for a Java programme which finds loop inward singly linked.


12) Write Java programme to contrary String without using API? (solution)
One to a greater extent than enquiry to attempt out employment solving science of candidate. You wouldn't hold off these form of enquiry inward telephonic circular of Java interview but these questions receive got right away acquire norms. All interviewer is looking it for logic, you lot don't demand to write the code but you lot should live able to think of solution.


13) Difference betwixt Serializable in addition to Externalizable inward Java? (detailed answer)
Serializable is a marking interface alongside no methods defined it but Externalizable interface has ii methods defined on it e.g. readExternal() in addition to writeExternal() which allows you lot to command the serialization process. Serializable uses default serialization procedure which tin live real deadening for to a greater extent than or less application.


14) Difference betwixt transient in addition to volatile inward Java? (detailed answer)
transient keyword is used inward Serialization spell volatile is used inward multi-threading. If you lot desire to exclude a variable from serialization procedure therefore grade that variable transient. Similar to static variable, transient variables are non serialized. On the other hand, volatile variables are signal to compiler that multiple threads are interested on this variable in addition to it shouldn't reorder its access. volatile variable equally good follows happens-before relationship, which agency whatsoever write happens earlier whatsoever read inward volatile variable. You tin equally good brand non atomic access of double in addition to long variable atomic using volatile.


15) Difference betwixt abstract course of report in addition to interface? (detailed answer)
From Java 8 onwards deviation betwixt abstract course of report in addition to interface inward Java has minimized, right away fifty-fifty interface tin receive got implementation inward price of default in addition to static method. BTW, inward Java you lot tin even therefore extend but i course of report but tin extend multiple inheritance. Abstract course of report is used to furnish default implementation alongside but something left to customize, spell interface is used heavily inward API to define contract of a class.


16) Difference betwixt Association, Composition in addition to Aggregation? (detailed answer)
Between association, composition in addition to aggregation, composition is strongest. If purpose tin exists without whole than human relationship betwixt ii course of report is known equally aggregation but if purpose cannot exists without whole than human relationship betwixt ii course of report is known equally composition. Between Inheritance in addition to composition, after provides to a greater extent than flexible design.


17) What is deviation betwixt FileInputStream in addition to FileReader inward Java? (detailed answer)
Main deviation betwixt FileInputStream in addition to FileReader is that sometime is used to read binary information spell after is used to read text data, which agency after equally good consider graphic symbol encoding spell converting bytes to text inward Java.


18) How do you lot convert bytes to graphic symbol inward Java? (detailed answer)
Bytes are converted to graphic symbol or text information using graphic symbol encoding. When you lot read binary information from a file or network endpoint, you lot furnish a graphic symbol encoding to convert those bytes to equivalent character. Incorrect alternative of graphic symbol encoding may alter pregnant of message past times interpreting it differently.


19) Can nosotros receive got render disputation inward finally clause? What volition happen? (detailed answer)
Yes, you lot tin usage render disputation inward finally block, but it volition non forestall finally block from existence executed. BTW, if you lot equally good used render disputation inward endeavour block therefore render value from finally block alongside override whatever is returned from endeavour block.


20) Can you lot override static method inward Java? (detailed answer)
No, you lot cannot override static method inward Java because they are resolved at compile fourth dimension rather than runtime. Though you lot tin declare in addition to define static method of same cite in addition to signature inward shaver class, this volition enshroud the static method from parent class, that's why it is equally good known equally method hiding inward Java.


21) Difference betwixt private, public, packet in addition to protected inward Java? (detailed answer)
All 4 are access modifier inward Java but exclusively private, world in addition to protected are modifier keyword. There is no keyword for packet access, its default inward Java. Which agency if you lot don't specify whatsoever access modifier than past times default that volition live accessible within the same package. Private variables are exclusively accessible inward the course of report they are declared, protected are accessible within all classes inward same packet but exclusively on sub course of report exterior packet in addition to world variables e.g. method, course of report or variables are accessible anywhere. This is highest grade of access modifier in addition to furnish lowest shape of encapsulation.


22) v Coding best practices you lot learned inward Java? (detailed answer)
If you lot are developing on a programming linguistic communication for pair of years, you lot certain knows lots of best practices, past times quest pair of them, Interviewer but checking that you lot know your merchandise well. Here are my v Java best practices :
- Always cite your thread, this volition assist immensely inward debugging.
- Use StringBuilder for string concatenation
- Always specify size of Collection, this volition salve lot of fourth dimension spent on resizing
- Always declare variable mortal in addition to lastly unless you lot receive got skillful reason.
- Always code on interfaces instead of implementation
- Provide dependency to method instead they acquire it past times themselves, this volition brand your code unit of measurement testable.


23) Write a Program to respect maximum in addition to minimum number inward array? (solution)
This is to a greater extent than or less other coding enquiry attempt out employment solving powerfulness of candidate. Be prepare for pair of follow upward equally good depending upon how you lot reply this question. Simplest way which comes inward heed is to sort the array in addition to therefore pick the top in addition to bottom element. For a improve reply regard the solution.


24) Write a programme to contrary Array inward place? (solution)
Another employment solving enquiry for Java programmers. Key indicate hither is that you lot demand to contrary the array inward place, which agency you lot cannot usage additional buffer, i or ii variable volition live fine. Note you lot cannot usage whatsoever library code, you lot demand to do your ain logic.


25) Write a programme to contrary a number inward Java? (solution)
This is an interesting programme for a real junior programmer, right from the college but tin sometime puzzle developer alongside pair of years of sense equally well. Most of these developer does real trivial coding therefore they flora these form of questions challenging. Here the clit a fast i on is to acquire the lastly digit of the number past times using modulus operator (%) in addition to reducing number inward each driblet dead past times using partitioning operator (/). See the solution for how to do that inward Java.


26) Write a Program to calculate factorial inward Java? (solution)
Another beginners coding problem, skillful for telephonic interview because you lot tin differentiate a guy who tin write programme to the guy who can't. It's equally good skillful to regard if developer is familiar alongside both recursive in addition to iterative algorithm in addition to pros in addition to cons of each. You tin equally good inquire lots of follow upward e.g. how to improve functioning of algorithm? Since factorial of a number is equal to number multiplied past times factorial of previous number, you lot tin cache those value instead of recalculating them, this volition impress your interviewer a bit. See the solution for total code example.


27) What is deviation betwixt calling start() in addition to run() method of Thread? (detailed answer)
You mightiness receive got heard this enquiry before, if calling start() method calls the run() method eventually therefore why non but telephone telephone the run() method? Well the deviation is, start method equally good starts a novel thread. If you lot telephone telephone the run method straight therefore it volition run on same thread non on different thread, which is what master intention would be.


28) Write a Program to solve Producer Consumer employment inward Java? (solution)
Influenza A virus subtype H5N1 real skillful enquiry to banking venture check if candidate tin write inter thread communication code or not. If a guy tin write producer consumer solution past times mitt in addition to indicate out critical department in addition to how to protect, how to communicate alongside thread therefore he is skillful plenty to write in addition to hold your concurrent Java program. This is the real minimum requirement for a Java developer in addition to that's why I dearest this question, it equally good has several solution e.g. past times using concurrent collections similar blocking queue, past times using hold off in addition to notify in addition to past times using other synchronizers of Java v e.g. semaphores.


29) How to respect catch chemical cistron of linked listing inward i pass? (solution)
Another unproblematic employment solving enquiry for warm up. In a singly linked listing you lot tin exclusively traverse inward i direction in addition to if you lot don't know the size therefore you lot cannot write a loop to exactly respect out catch element, that is the crux of the problem. One solution is past times using ii pointers, fast in addition to slow. Slower pointer moves 1 measuring when faster pointer displace to 2 steps, causing deadening to indicate to catch when fast is pointing to goal of the listing i.e. null. Check out solution for Java code sample.


30) What is equlas() in addition to hashCode() contract inward Java? Where does it used? (detailed answer)
One of the must inquire enquiry inward Java telephonic interview. If a guy doesn't know nigh equals() in addition to hashCode() therefore he is in all probability non worth pursuing farther because its the meat of the Java fundamentals. The key indicate of contract is that if ii objects are equal past times equals() method therefore they must receive got same hashcode, but unequal object tin equally good receive got same hashcode, which is the motility of collision on hash tabular array based collection e.g HashMap. When you lot override equals() you lot must retrieve to override hashCode() method to driblet dead along the contract valid.


31) Why hold off in addition to notify methods are declared inward Object class? (detailed answer)
This enquiry is to a greater extent than to respect out how much sense you lot actually receive got in addition to what is your thinking towards Java API in addition to its blueprint decision. Similar enquiry is why String is immutable inward Java? Well, truthful reply tin exclusively live given past times Java designers but you lot tin argue something. For example, hold off in addition to notify methods are associated alongside locks which is owned past times object non thread, in addition to that's why it brand sense to driblet dead along those method on java.lang.Object class. See the detailed reply for to a greater extent than give-and-take in addition to reasoning.


32) How does HashSet industrial plant inward Java? (detailed answer)
HashSet is internally implemented using HashMap inward Java in addition to this is what your interviewer wants to hear. He could therefore quiz you lot alongside to a greater extent than or less mutual sense based enquiry e.g. how tin you lot usage HashMap because its needs ii object key in addition to value? what is the value inward instance of HashSet? Well, inward instance of HashSet a dummy object is used equally value in addition to key objects are the actual chemical cistron on Set indicate of view. Since HashMap doesn't allow duplicate key it equally good follows contract of laid information construction to non allow duplicates. See detailed reply for to a greater extent than analysis in addition to explanation.


33) What is deviation betwixt synchronize in addition to concurrent Collection inward Java? (detailed answer)
There was time, earlier Java 1.5 when you lot exclusively receive got synchronized collection if you lot demand them inward a multi-threaded Java program. Those classes were plagued alongside several number most importantly functioning because they lock the whole collection or map whenever a thread reads or writes. To address those issue, Java released pair of Concurrent collection classes e.g. ConcurrentHashMap, CopyOnWriteArrayList in addition to BlockingQueue to furnish to a greater extent than scalability in addition to performance.


34) What is deviation betwixt Iterator in addition to Enumeration inward Java? (detailed answer)
Main deviation is that Iterator was introduced inward house of Enumeration. It equally good allows you lot to take elements from collection spell traversing which was non possible alongside Enumeration. The methods of Iterator e.g. hasNext() in addition to next() are equally good to a greater extent than concise therefore corresponding methods inward Enumeration e.g. hasMoreElements(). You should e'er usage Iterator inward your Java code equally Enumeration may acquire deprecated in addition to removed inward futurity Java release.


35) What is deviation betwixt Overloading in addition to Overriding inward Java? (detailed answer)
Another oft asked enquiry from telephonic circular of Java interviews. Though both overloading in addition to overriding are related alongside methods of same names but they receive got different characteristics e.g.overloaded methods must receive got different method signature than master method but overridden method must receive got same signature. Also, overloaded methods are resolved at compiled fourth dimension spell overridden methods are resolved at runtime. See the detailed reply for to a greater extent than analysis in addition to differences.


36) Difference betwixt static in addition to dynamic binding inward Java? (detailed answer)
This is unremarkably asked equally follow-up of previous question, static binding is related to overloaded method in addition to dynamic binding is related to overridden method. Method similar private, lastly in addition to static are resolved using static binding at compile fourth dimension but virtual methods which tin live overridden are resolved using dynamic binding at runtime.


37) Difference betwixt Comparator in addition to Comparable inward Java? (detailed answer)
This is i to a greater extent than basic concept, I hold off every Java candidate to know. You volition bargain alongside them on every Java project. Several meat classes inward Java e.g. String, Integer implements Comparable to define their natural sorting social club in addition to if you lot define a value course of report or a domain object therefore you lot should equally good implement Comparable in addition to define natural ordering of your object. Main deviation betwixt these ii is that, you lot could do multiple Comparator to define multiple sorting social club based upon different attribute of object. Also, In social club to implement Comparable you lot must receive got access of the course of report or code, but you lot tin usage Comparator without having source code of class, all you lot demand is the JAR file of particular object. That's why Comparator is real powerful to implement custom sorting social club in addition to from Java 8 you lot tin do it fifty-fifty to a greater extent than elegantly, equally seen here.


38) How do you lot sort ArrayList inward descending order? (solution)
You tin usage Collections.sort() method alongside contrary Comparator, which tin sort elements inward the contrary social club of their natural social club e.g.
List<String> listOfString = Arrays.asList("London", "Tokyo", "NewYork"); Collections.sort(listOfString, Collections.reverseOrder()); System.out.println(listOfString); //[Tokyo, NewYork, London]


39) What is deviation betwixt PATH in addition to CLASSPATH inward Java? (detailed answer)
PATH is an environs variable which points to Java binary which is used to run Java programs. CLASSPATH is to a greater extent than or less other environs variable which points to Java course of report files or JAR files. If a course of report is non flora inward CLASSPATH therefore Java throws ClassNotFoundException.


40) What is deviation betwixt Checked in addition to Unchecked Exception inward Java? (detailed answer)
Checked exception ensures that treatment of exception is provided in addition to its verified past times compiler also, spell for throwing unchecked exception no special provision is needed e.g. throws clause. Influenza A virus subtype H5N1 method tin throw unchecked exception without whatsoever throw clause.


That's all nigh 40 Core Java Interview Questions from telephonic round. Don't receive got a telephone interview lightly, its your offset conduct chances to impress your perspective employer. Given that you lot are non seeing your interviewer in addition to but communicating alongside your voice, its trivial chip different than face-to-face interview. So e'er live calm, relaxed in addition to reply questions to the indicate in addition to precisely, verbalize piece of cake in addition to brand certain you lot are non inward a house where your audio echoes e.g. on closed stair case. Having a skillful phone, caput laid in addition to existence on skillful reception expanse is equally good real important. I receive got seen it many times where candidate lost on interview because non able to take heed it properly or non able to sympathize enquiry earlier answering them. I know to a greater extent than or less people receive got telephonic interviews on those undercover places but if you lot do brand certain your telephone connectivity is enough.

If you lot similar this tutorial in addition to looking for to a greater extent than or less to a greater extent than interview questions for grooming checkout my amazing collection :
  • 10 Advanced Core Java Interview Questions for Programmers (see here)
  • 15 Java Enum based Interview Questions alongside Answers (check here)
  • 21 Frequently asked Java Questions alongside Answers (see here)
  • Top 10 Linux in addition to UNIX Interview Questions for Java Programmers (check here)
  • Top xx SQL Query Interview Questions (see list)
  • Java Interview Questions for 2 to 3 Years Experienced Programmers (see here)
  • 12 Multithreading in addition to Concurrency Questions for Java Developers (check here)
  • 10 Tough Java Questions from Interviews (see list)
  • Top eleven Coding Questions from Java Interviews alongside Answers (see here)
  • 18 Good Java Design Pattern Questions for Senior Developers (see here)
  • 15 Tricky Questions from Java Interviews alongside Answers (check here)

Sunday, November 24, 2019

What Is Polymorphism Inwards Java? Overriding Or Overloading?

Polymorphism vs Overloading vs Overriding
Someone asked me What are the departure betwixt Polymorphism in addition to Overriding inwards Java in addition to the similar difference betwixt Polymorphism in addition to Overloading. Well, they are non 2 dissimilar things, Polymorphism is an object oriented or OOPS concept similar Abstraction, Encapsulation or Inheritance which facilitate the purpose of the interface in addition to allows Java programme to accept payoff of dynamic binding inwards Java. Polymorphism is every bit good a way through which a Type tin deport differently than expected based upon which variety of Object it is pointing. Overloading in addition to overriding are 2 forms of Polymorphism available inwards Java.


Both overloading in addition to the overriding concept are applied on methods inwards Java. Since polymorphism literally agency taking multiple forms, So fifty-fifty though you lot direct maintain the advert of the method same inwards the instance of overloading in addition to overriding, an actual method called tin endure whatever of those multiple methods amongst the same name. Let's run across but about to a greater extent than details on method overloading in addition to overriding to sympathise how polymorphism relates to overloading in addition to overriding in addition to How they are different.


Polymorphism vs Overriding

Overriding is a cast of polymorphism which is used inwards Java to dynamically bind method from the subclass inwards reply to a method telephone phone from sub cast object referenced past times superclass type. Method overriding is bonded using dynamic binding inwards Java.  


Suppose you lot direct maintain 2 methods size() inwards both base of operations cast in addition to derived cast in addition to Base cast variable is pointing to an object which happens to endure subclass object at runtime thus method from subclass volition endure called, i.e. overridden method volition endure called.

This allows to program for interface than implementation, a pop OOPS pattern principle because Polymorphism guarantees to invoke right method based upon the object. Method overriding is cardinal for much flexible pattern pattern inwards Java.

See What is method overriding inwards Java  and Rules of method Overriding for examples in addition to to a greater extent than details.



Polymorphism vs Overloading

Method overloading is but about other cast of Polymorphism though but about people debate against that. In the instance of overloading, you lot every bit good got multiple methods amongst the same advert but dissimilar method signature but a telephone phone to right method is resolved at compile fourth dimension using static binding inwards Java. Overloading is a compile fourth dimension activity oppose to Overriding which is runtime activity. Because of this argue overloading is faster than method overriding inwards Java. Though beware amongst an overloaded method which creates conflict e.g. methods amongst solely i parameter e.g. int in addition to long etc. See What are method overloading inwards Java for representative in addition to consummate details.

Polymorphism vs Overloading vs Overriding What is  Polymorphism inwards Java? Overriding or Overloading?
An Example of Polymorphism inwards Java


An representative of Polymorphism inwards Java

subclass Dog in addition to Cat.


import java.util.ArrayList;
import java.util.List;

abstract class Pet{
    public abstract void makeSound();
}

class Cat extends Pet{

    @Override
    public void makeSound() {
        System.out.println("Meow");
    }  
}

class Dog extends Pet{

    @Override
    public void makeSound() {
        System.out.println("Woof");
    }
 
}

Let's show How Polymorphism concept function inwards Java:

/**
 *
 * Java programme to demonstrate What is Polymorphism
 * @author Javin Paul
 */

public class PolymorphismDemo{

    public static void main(String args[]) {
        //Now Pet volition present How Polymorphism function inwards Java
        List<Pet> pets = new ArrayList<Pet>();
        pets.add(new Cat());
        pets.add(new Dog());
     
        //pet variable which is type of Pet deport dissimilar based
        //upon whether pet is Cat or Dog
        for(Pet pet : pets){
            pet.makeSound();
        }
   
    }
}

Output:
Meow
Woof

In Summary, you tin non compare Polymorphism amongst method overloading or override. Polymorphism is the mightiness of a variable to deport differently based upon which variety of Object it is referring. They are Java programming language's way to implement polymorphism inwards language.


Other Java in addition to OOPS tutorial for programmers

Tuesday, March 31, 2020

Can Nosotros Override Static Method Inwards Coffee - Method Hiding

Can nosotros override static method inwards Java
No, yous cannot override static method inwards Java because method overriding is based upon dynamic binding at runtime in addition to static methods are bonded using static binding at compile time. Though yous tin sack declare a method alongside same get upwards in addition to method signature inwards sub course of pedagogy which does hold off similar yous tin sack override static method inwards Java exactly inwards reality that is method hiding. Java won't resolve method telephone telephone at runtime in addition to depending upon type of Object which is used to telephone telephone static method, corresponding method volition last called. It agency if yous move Parent class's type to telephone telephone static method, master static volition last called from patent class, on ther other mitt if yous move Child class's type to telephone telephone static method, method from tiddler course of pedagogy volition last called. In curt yous tin sack non override static method inwards Java. If yous move Java IDE similar Eclipse or Netbeans, they volition demo alert that static method should last called using course of pedagogy get upwards in addition to non past times using object becaues static method tin sack non last overridden inwards Java.



Overriding Static method inwards Java - Example

 yous cannot override static method inwards Java because  Can nosotros override static method inwards Java - Method HidingIn terminal department nosotros saw theory that nosotros tin sack non override static methods inwards Java, static method tin sack solely last hidden inwards sub class. Let's run across an instance to examine that theory which says you tin sack non override static method inwards Java




/**
 *
 * Java programme which demonstrate that nosotros can non override static method inwards Java.
 * Had Static method tin sack last overridden, alongside Super course of pedagogy type in addition to sub course of pedagogy object
 * static method from sub course of pedagogy would last called inwards our example, which is non the case.
 * @author
 */

public class CanWeOverrideStaticMethod {
 
    public static void main(String args[]) {
     
        Screen scrn = new ColorScreen();
     
        //if nosotros tin sack  override static , this should telephone telephone method from Child class
        scrn.show(); //IDE volition demo warning, static method should last called from classname
     
    } 
 
}

class Screen{
 
    /*
     * world static method which tin sack non last overridden inwards Java
     */

    public static void show(){
        System.out.printf("Static method from bring upwards class");
    }
}

class ColorScreen extends Screen{
    /*
     * static method of same get upwards in addition to method signature every bit existed inwards super
     * class, this is non method overriding instead this is called
     * method hiding inwards Java
     */

    public static void show(){
        System.err.println("Overridden static method inwards Child Class inwards Java");
    }
}

Output:
Static method from bring upwards class

This output confirms that yous tin sack non override static method inwards Java in addition to static method are bonded based upon type information in addition to non based upon Object. had Static mehtod last overridden, method from Child course of pedagogy or ColorScreen would accept been called.

That's all on give-and-take Can nosotros override static method inwards Java or not. We accept confirmed that no, we tin sack non override static method, nosotros tin sack solely enshroud static method inwards Java. Creating static method alongside same get upwards in addition to mehtod signature is called Method hiding inwards Java.

Further Learning
Data Structures in addition to Algorithms: Deep Dive Using Java
10 Java Coding Interview questions in addition to Answers for Java beginners.

What Is Method Overriding Inwards Coffee – Event Tutorial

Method overriding inward Java
Method overriding inward Java is a concept based on polymorphism OOPS concept which allows programmer to do ii methods amongst same get upwards together with method signature on interface together with its diverse implementation together with actual method is called at runtime depending upon type of object at runtime. Method overriding allows you lot to write flexible together with extensible code inward Java because you lot tin innovate novel functionality amongst minimal code change. Method overriding is dissimilar than method overloading inward Java which nosotros accept discussed inward in conclusion article. In method overloading, Only get upwards of ii overloaded methods are same precisely method signature must last dissimilar spell inward method overriding, method signature must last same. method overriding stand upwards for truthful polymorphic behaviour, where exclusively get upwards needs to last same underlying method logic tin last different. In this Java tutorial nosotros volition see What is method overriding inward Java, Rules to override method inward Java together with an representative of How to override method inward Java. We won't utter over difference betwixt method overloading together with overriding inward Java, may last about other post.

Rules of method overriding inward Java
Method overriding inward Java is a concept based on  What is method overriding inward Java – Example TutorialThere are few rules which needs to last followed spell overriding whatsoever method inward Java, failure to follow these rules termination inward compile fourth dimension mistake inward Java.


1) First together with almost of import dominion regarding method overriding inward Java is that you lot tin exclusively override method inward sub class. You tin non override method inward same class.

2) Second of import dominion of method overriding inward Java that get upwards together with signature of method must last same inward Super class together with Sub class or inward interface together with its implementation.

3) Third dominion to override method inward Java is that overriding method tin non trim back accessibility of overridden method inward Java. For representative if overridden method is populace than overriding method tin non last protected, soul or package-private; But contrary is truthful overriding method tin growth accessibility of method inward Java, i.e. if overridden method is protected than overriding method tin last protected or public.


4) Another worth noting dominion of method overriding inward Java is that overriding  method tin non throw checked Exception which is higher inward hierarchy than overridden method. Which agency if overridden method throws IOException than overriding method tin non throw java.lang.Exception inward its throws clause because java.lang.Exception comes higher than IOException inward Exception hierarchy. This dominion doesn't apply to RuntimeException inward Java, which is non fifty-fifty demand to last declared inward throws clause inward Java.

5) You tin non override private, static together with final method inward Java. soul together with static method are bonded during compile fourth dimension using static binding inward Java  and doesn't resolve during runtime. overriding in conclusion method inward Java is compile fourth dimension error. Though soul together with static method tin last hidden if you lot declare about other method amongst same together with signature inward sub class.

6) Overridden method is called using dynamic binding inward Java at runtime based upon type of Object. As shown inward next representative of method overloading.

7) If you lot are extending abstract class or implementing interface than you lot demand to override all abstract method unless your class is non abstract. abstract method tin exclusively last used yesteryear using method overriding.

8) Always usage @Override annotation spell overriding method inward Java. Though this is non dominion precisely its 1 of the best Java coding do to follow. From Java vi you lot tin usage @Override annotation on method inherited from interface every bit well.


Method Overloading Example inward Java

Now nosotros know what is method overriding inward Java together with rules of method overriding, It's fourth dimension to meet an representative of how to override method inward Java. In this representative nosotros accept used Runnable interface which has an abstract run() method. We accept ii class Task together with PeriodicTask which implements Runnable interface together with override run method. For the purpose of demonstrating how method overriding industrial plant inward Java nosotros are calling run() method inward same thread, which you lot should not, meet difference betwixt run together with starting fourth dimension method to know why. Because run() is overridden inward ii split class, telephone phone to run() method volition last resolved during runtime depending upon type of Object.

/**
 *
 * Java plan to demonstrate how to override method inward Java.
 * Overridden method are resolved during runtime based upon type of object
 *
 * @author Javin
 */

public class CollectionTest {
 
    public static void main(String args[]) {
 
      Runnable chore = new Task();
      task.run(); //call overridden method inward Task
   
      chore = new PeriodicTask();
      task.run(); //calls overridden method inward PeriodicTas

    }
 
 
}

class Task implements Runnable{

    @Override
    public void run() {
        System.out.println("Run method overridden inward Task class");
    }
 
}

class PeriodicTask extends Task{
 
    @Override
    public void run() {
        System.err.println("overridden method run() inward PeriodicTask class");
    }
}

Output:
Run method overridden inward Task class
overridden method run() inward PeriodicTask class


That's all on What is method overriding inward Java, Rules of method overriding inward Java together with an representative of How to override method inward Java. In summary think to override all abstract method spell extending cast abstract class or implementing interface. Overridden method are besides slower every bit compared to static together with in conclusion methods because of dynamic binding precisely it provides you lot flexibility, many popular Object oriented pattern principles are based upon method overriding inward Java.

Further Learning
How to traverse iterate or loop ArrayList inward Java

Wednesday, December 11, 2019

How To Purpose Static Method Inwards Coffee Amongst Example

Static methods are 1 of the of import programming concepts inwards whatever programming linguistic communication but unfortunately it is also most misunderstood as well as misused one. Talking nearly Java, almost all programmers knows that. static methods belong to the shape as well as non-static methods belong to the objects of the class, but hardly all of them sympathise what it means. That's why this is 1 of the pop weed out questions on programming interviews. If a Java programmer doesn't know departure betwixt static as well as non-static method, he is in all likelihood non ready yet, as well as needs to a greater extent than exercise as well as experience. With one-half knowledge, making a method static tin give the sack receive got serious repercussion , specially inwards today's heavily multi-threaded Java application. Today, 1 of my reader message me this inquiry on my Facebook employment concern human relationship of Javarevisited, which prompted me to to write this tutorial cum give-and-take postal service to give a skillful explanation or instance to clarify the concept. What y'all receive got learned is totally find, all nosotros do hither is to elaborate your learning past times agreement fundamental differences betwixt static methods as well as instance methods inwards Java.

Let's start amongst what y'all receive got learned, static methods belong to the class, this agency it tin give the sack hold out called without a specific instance of that class. For example, the java.lang.Math shape contains many static methods as well as y'all commonly telephone band them every bit Math.random() to generate random numbers, or Math.abs() to calculate the absolute value of a number. You don't demand to do an instance of Math shape to utilisation these methods. This is quite convenient if y'all merely desire to utilisation the functionality. Another instance of the static method is top dog method, which is commonly static because it is called start earlier at that topographic point is whatever fourth dimension to instantiate a class. In fact, that is 1 of the reasons why top dog is static inwards Java.



On merely about other hand, non-static methods tin give the sack solely hold out called on an instance of the shape itself, as well as they commonly do something that depends on the private characteristic of the shape (e.g. play amongst variables). They also receive got side trial e.g. calling a move() method on Player object most probable modify its position. H5N1 key departure betwixt static as well as non-static method is that static method affects all object if they are using whatever static variable, but non-static method solely affects the object they are operating upon. Let's run across an instance to sympathise how a static as well as non-static method works.


Static vs Non-Static Method Example

Here is a Java programme to demonstrate as well as explicate departure betwixt an instance method as well as a shape method inwards Java. If y'all are using Eclipse IDE,  you tin give the sack easily run this programme past times merely re-create pasting inwards your Java project, no demand to do Java origin file as well as directories to stand upwards for package, Eclipse volition bring aid of those things. In this programme nosotros receive got 2 players P1 as well as P2, which are instance of Player class. This shape contains a shape variable called "game" as well as 2 instance variable X as well as Y to announce coordinates of Player. We receive got a static method called changeGame() to laid value of static variable "game" as well as non-static method move() to modify value of instance variables X as well as Y.


 Static methods are 1 of the of import programming concepts inwards whatever programming linguistic communication  How to utilisation Static Method inwards Java amongst Example

In start instance of our try program, nosotros telephone band instance method move() on p1 as well as y'all tin give the sack run across that solely its X as well as Y are modified, p2's seat has non changed because instance method solely impact terra firma of methods they were called upon. In side past times side instance nosotros telephone band static method changeGame(), straightaway this volition impact both p1 as well as p2 because static variable "game" is shared betwixt them. You tin give the sack run across the output after invocation of instance method as well as static method to figure out difference.

/**  * Java programme to exhibit departure betwixt static as well as non-static method.  * It explains how calling static method as well as changing static variable  * impact all objects, instead of merely calling object inwards instance of non-static  * method  * @author WINDOWS 8  *  */ public class StaticDemo{      public static void main(String args[]) {         Player p1 = new Player(10, 10);         Player p2 = new Player(20, 20);               // calling non-static method move() on p1         p1.move();               // let's impress seat of p1 as well as p2         // solely p1 should receive got moved, no impact on p2         System.out.println("P1 : " + p1);         System.out.println("P2 : " + p2);               // calling static method on p2         p2.changeGame("Cricket Brian Lara 1997");               // should receive got affected both p1 as well as p2         System.out.println("P1 : " + p1);         System.out.println("P2 : " + p2);           }       } /**  * Simple Java shape to stand upwards for a Player amongst position.  * It has both static as well as non-static method to operate on  * instrumentalist objects.  * @author WINDOWS 8  *  */ class Player{     private static String game = "Super Mario Bros";       private int X;     private int Y;       public Player(int x, int y){         this.X = x;         this.Y = y;     }       public void move(){         X++;         Y++;     }       public static void changeGame(String nextGame){         game = nextGame;     }       @Override     public String toString() {         return String.format("Game: %s, X : %d, Y: %d ", game, X, Y);     } }  Output P1 : Game: Super Mario Bros, X : 11, Y: 11 P2 : Game: Super Mario Bros, X : 20, Y: 20 P1 : Game: Cricket Brian Lara 1997, X : 11, Y: 11 P2 : Game: Cricket Brian Lara 1997, X : 20, Y: 20 



Properties of Static Methods inwards Java

Static is non merely precisely about other keyword it's 1 of most of import programming concept as well as every linguistic communication has merely about specific features related to static variables, methods, as well as classes. Though fundamental departure comes from the fact that static is something which is associated amongst the shape rather than an instance, at that topographic point are many subtle details of static keyword, which y'all should conk on inwards mind. Let's run across merely about of them here.

1) You cannot utilisation this keyword within a static method inwards Java. Since this is associated amongst the electrical flow instance, it's non allowed inwards static context because no instance be that time. Trying to utilisation this variable within static context e.g. static block or method is compile fourth dimension error inwards Java.

2) super keyword is non allowed within the torso of a static method or static block. Just similar this, a super keyword is also used to stand upwards for electrical flow instance of the rear shape as well as since the instance is non valid inwards static context, it's a compile-time error to utilisation super keyword within a static method inwards Java.

3) You cannot utilisation whatever instance variable within a static method, they volition termination inwards compile fourth dimension error e.g. "non-static reference is non allowed within static methods". Why? because instance may non be when the static method gets called. They are non associated amongst whatever instance, y'all tin give the sack telephone band them fifty-fifty on a zero variable without throwing NullPointerException inwards Java. In short, y'all cannot utilisation  non-static members within your static methods inwards Java.

3) H5N1 static method cannot hold out overridden inwards Java, Why? because they are non resolved at runtime, which is the instance amongst overriding. Like a private as well as finally method, static methods are also resolved at compile time. By the way, this doesn't hateful that y'all cannot declare merely about other static method amongst same elevate as well as signature inwards the nipper class, y'all tin give the sack do hence as well as the compiler volition non complain at all, but that would non hold out method overriding, instead that is called method hiding inwards Java. This novel method volition shroud the static method from the rear shape as well as when y'all telephone band it using Child shape only.  See why static method cannot hold out overridden for to a greater extent than details.

4) Static method invocation is to a greater extent than efficient than instance method because the compiler doesn't demand to go past times this reference, dissimilar instance methods. That's why y'all should brand utility method every bit static if they are non using whatever instance variable.

5) Static methods are bonded during compile time, every bit opposed to an instance method, which is resolved during runtime; old is known every bit static binding spell afterward is known every bit dynamic binding inwards Java. See the difference betwixt static as well as dynamic binding for to a greater extent than details.

6) By the way, You tin give the sack overload static methods inwards Java, at that topographic point is no restriction on that from Java linguistic communication perspective. In fact, JDK API itself has lots of overloaded static method e.g. String.valueOf() is overloaded to bring an int, long, float, double, as well as boolean information type. EnumSet.of() is also overloaded to do EnumSet amongst one, 2 or multiple values.

7) You tin give the sack telephone band a static method without creating whatever instance of that class, this is 1 of the biggest argue of making a method static inwards Java. For example, to telephone band Double.valueOf(), y'all don't demand to do an instance of the Double class. You tin give the sack fifty-fifty telephone band static methods amongst reference variable having a zero value as well as to your surprise, those volition non termination inwards a zero pointer, every bit only the classname is used to detect as well as telephone band static methods. For example, next code volition run fine inwards Java.
Double d = null; d.valueOf(2);

8) H5N1 static method tin give the sack hold out synchronized, as well as to a greater extent than importantly, they utilisation different lock than instance synchronized method. Which means, 2 threads tin give the sack simultaneously run a static as well as a non-static method inwards Java. This is a mutual multi-threading error inwards Java as well as y'all should expect for that spell writing Java try involving code as well as multiple threads. To acquire to a greater extent than run across the difference betwixt static as well as non-static synchronized method inwards Java.

9) You cannot declare a static method within the torso of an interface inwards Java.

10) As the elevate implies, instance methods require an instance of a class. Static methods (and fields) are independent of shape instances, every bit they are solely associated amongst class. To utilisation instance methods, you'll receive got to do an instance using new. H5N1 static method is considered to receive got no side trial on the terra firma of an object because of the said reason.


When to utilisation Static method inwards Java

Methods which never demand to access instance variables are skillful candidate to conk static. The functions inwards java.lang.Math are a skillful instance every bit they solely demand input arguments. One rule-of-thumb, if y'all receive got a shape MyClass,  ask yourself  "does it brand feel to telephone band this method, fifty-fifty if no Object of MyClass has been constructed yet?" If so, it should definitely hold out static. Another uncomplicated dominion inwards Java is,  Immutable is good. So if your method does non modify the terra firma of the object as well as if it must non hold out overridden past times a subclass, it should hold out static. Also static methods are easier to inline past times the JIT-Compiler. Let's run across an example, supper y'all receive got a shape Car as well as y'all powerfulness receive got a method double convertMpgToKpl(double mpg) , this is merely about other skillful candidate to become static, because 1 powerfulness desire to know what 45mpg converts to, fifty-fifty if nobody has always built a Car. But void setOdometer(double mi) (which sets the distance-travelled for 1 particular Car) can't hold out static because it's inconceivable to telephone band the method earlier whatever Car has been constructed. In short, If a method within a shape is non using instance variable, as well as hence it's the skillful candidate for making it static, as well as may hold out it powerfulness non belong to that shape itself. Here are yoke of mutual scenarios inwards Java world, where utilisation of static method is considered appropriate :

1) Use static method every bit static mill method for information conversion e.g. Integer.valueOf(), which is used to convert whatever other information type to integer e.g. Integer.valueOf(String str) converts String to Integer inwards Java.

2) Use static method every bit utility methods e.g. methods from Math class or Arrays or Collections e.g. Collections.sort() method.

3) getInstance() method of Singleton pattern pattern is merely about other pop instance of Static method inwards Java

4) Pattern.compile() is merely about other static method, which is instance of static mill method every bit discussed inwards the start example

5) Hmm, how tin give the sack I forget the most pop instance of a static method inwards Java,  yes I am talking nearly public static void main(String[] str). The top dog method is 1 of the most known examples of static methods, inwards fact, why top dog is static inwards Java, is also 1 of the frequently asked Java question on college viva or on Java interviews.


Disadvantage of Using static method inwards Java

There is nix inwards the footing which solely has pros without whatever cons, as well as static methods are no different. Though they are immensely helpful from convenience perspective as well as critical to implement merely about amount Java pattern patterns similar Singleton as well as Factory Pattern, they also receive got merely about serious drawbacks. Here are a yoke of them :

1) No Runtime Polymorphism
First as well as foremost, the static method reduces the flexibility of your system. Once a method is declared static, it's fixed. You cannot furnish an alternate implementation of that method inwards a subclass, every bit the static method cannot hold out overridden, they tin give the sack solely hold out hidden. Even this method hiding tin give the sack displace serious as well as subtle bugs.

2) Potential of Concurrency Bugs
One of the not-so-obvious affair nearly static synchronized method is that it uses different lock than instance synchronized method. which means, If y'all are sharing a resources betwixt a static as well as non-static method, as well as thinking that y'all receive got synchronized their access, y'all are living on a dream. Both methods tin give the sack hold out run inwards parallel at the same fourth dimension as well as potentially displace subtle concurrency bugs.

3) Lose of interface
You cannot declare a static method within interface inwards Java, hence if your pattern has a static method, y'all cannot utilisation interface. You demand to lay your static method solely on implementations, which agency all code, which is written against interface volition non receive got access to that static method. Since programming to interface than implementation is 1 of the pop object-oriented pattern principles, y'all volition run across a lot of code written similar that.


That's all nearly the difference betwixt the static as well as non-static method inwards Java. We receive got learned fundamental points nearly static methods, receive got seen merely about pop examples of them, explored when to utilisation static methods as well as also learned nearly the potential disadvantage of using static methods. This gives y'all a fair thought nearly capability as well as limitation of static methods inwards Java programming language. Careful as well as clever utilisation of this concept tin give the sack termination inwards to a greater extent than readable as well as concise code spell misuse tin give the sack displace a lot of hurting specially inwards areas of concurrency, flexibility, as well as maintainability.

Further Learning
SOLID Principles of Object Oriented Design
Absolute Introduction to Object Oriented Programming inwards Java
Java - Object Oriented Programming [For Absolute Beginners]