Showing posts sorted by date for query top-10-jdbc-best-practices-for-java. Sort by relevance Show all posts
Showing posts sorted by date for query top-10-jdbc-best-practices-for-java. Sort by relevance Show all posts

Sunday, March 29, 2020

Jdbc Interview Questions Answers Inwards Coffee - Two To Iv Years Experienced Programmer

JDBC Interview inquiry forms 1 of the of import department inwards Java Interviews. Similar to multithreading, Collection framework together with Garbage collection interview question, JDBC inquiry must move prepared past times whatever Java programmer. Most of questions from JDBC or Java database connectivity comes from API together with basic architecture of JDBC which equally good involves JDBC drivers. Influenza A virus subtype H5N1 proficient agreement of JDBC API along with database basics similar transactions equally good assist to do good inwards JDBC interviews. I own got collected some of frequently asked JDBC Interview question for quick reference. This volition assist to revise some of import JDBC concepts together with equally good orbit a peril to explore JDBC API to newcomers. If you lot own got whatever other JDBC interview question, which has been asked to you lot or friends, together with you lot intend it’s proficient to portion alongside Java community thus delight portion with us. Let's run into my eleven questions from JDBC, non thus tough but worth preparing.


12 JDBC Interview Questions with Answers

JDBC Interview inquiry forms 1 of the of import department inwards Java Interviews JDBC Interview questions answers inwards Java - 2 to four years experienced programmerHere is my listing of interview questions from JDBC. This listing contains questions cast JDBC drivers, PreparedStatement, CallableStatement, JDBC Connection pool, SQL Date together with Timestamp API, ResultSet together with RowSet concepts together with couplet of JDBC inquiry from practical experience.




Question 1 : Difference betwixt SQL Date together with java.util.Date inwards Java
Answer : This is 1 of JDBC Questions which I similar to ask, because knowing how to correctly shop together with retrieve appointment inwards a database is often confusing for novel developers together with its rattling critical for whatever application. Main divergence betwixt SQL information i.e. java.sql.Date together with util appointment i.e. java.util.Date is that SQL Date alone contains appointment work together with non fourth dimension work but util appointment contains both appointment together with fourth dimension part. See SQL Date vs Util Date inwards Java for to a greater extent than differences betwixt them.

Question 2: What is do goodness of using PreparedStatement inwards Java
Answer : Another wonderful JDBC interview inquiry which is rattling pop on telephonic equally good equally on early on circular of Java Interviews. There are several benefits of using PreparedStatement piece querying database from Java programme e.g. meliorate surgical operation together with prevents from SQL Injection. I advise to read Why work PreparedStatement inwards Java for to a greater extent than benefits together with details on JDBC PreparedStatement.

Question 3: What is JDBC database Connection Pool? How to setup inwards Java?
Answer : I own got ever seen at to the lowest degree 1 inquiry related to database connecter puddle inwards JDBC Interview e.g. do goodness of using JDBC Connection pool. Well JDBC connecter puddle maintains puddle of JDBC connecter which is used past times application to query database. Since JDBC connecter are expensive it accept fourth dimension to create them which tin orbit notice irksome response fourth dimension of server if created during asking time. Creating them on application start-up together with reusing them number inwards meliorate performance. See How to setup JDBC Connection Pool inwards Java using Spring for to a greater extent than details on JDBC connecter puddle together with benefits it offer.

Question 4: What is divergence betwixt type 2 together with type four JDBC drivers inwards Java
Answer : This JDBC Interview inquiry is equally erstwhile equally Vector vs ArrayList or Hashtable vs HashMap. I recollect questions almost JDBC ODBC drivers asked during almost every fresher aeroplane interview.  Key divergence betwixt type 2 together with type four JDBC driver is that you lot only demand to include JAR file of JDBC driver inwards your classpath to connect database. See this link for to a greater extent than difference betwixt type 2 together with type four JDBC drivers.

Question 5: What is divergence betwixt java.sql.Time together with java.sql.TimeStamp inwards Java
Answer : This JDBC questions is similar to before JDBC interview inquiry java.sql.Date vs java.util.Date. Main divergence is that java.sql.Time degree doesn't comprise whatever appointment information on it piece java.sql.TimeStamp contains appointment information. See 4 divergence betwixt Time together with Timestamp inwards Java JDBC for to a greater extent than differences.

Question 6: What happens if nosotros telephone telephone resultSet.getInt(0) when Select query number only own got 1 column of integer type?
Answer : This is 1 of the tricky Java question which comes from JDBC. you lot may intend that it volition furnish outset column equally integer from Query number laid but unfortunately it doesn't. It throws InvalidColumnIndexException inwards JDBC because index for getXXX() or setXXX() inwards JDBC starts with 1. See How to ready InvalidColumnIndexException inwards JDBC for to a greater extent than details on this JDBC interview question.

Question 7: What is divergence betwixt RowSet together with ResultSet inwards JDBC?
Answer : One of the pop JDBC interview inquiry right away days. RowSet extends ResultSet together with add together back upwards for JDBC API to Java edible bean cistron model. Main divergence of ResultSet together with RowSet is RowSet beingness connected together with disconnected, which is some other follow-up JDBC question. RowSet makes it slowly to work ResultSet but equally I said you lot alone similar to work it to larn do goodness of disconnected together with connected RowSet.


Question 8: What is work of setAutoCommit(false) inwards JDBC ?
Answer : This is 1 of the JDBC Interview inquiry I touched on Top 10 JDBC best practices for Java programmer. making setAutoCommit(false) saves a lot of surgical operation equally it doesn't commit transaction automatically subsequently each query together with nosotros do batch update. It allows you lot to guide hold it using commit() together with rollback(). This has number inwards impressive surgical operation gain inwards DAO layer.


Question 9: How to telephone telephone stored physical care for from JDBC inwards Java?
Answer : This JDBC Interview inquiry is some other 1 you lot tin orbit notice add together on whatever often asked listing together with only can't afford non to prepare. Mostly asked to Java developers with 2 to four years experience. In its simplicity you lot tin orbit notice only say that CallableStatement is used to telephone telephone stored procedure, which may atomic number 82 questions similar how do you lot move past times parameters to stored physical care for from Java or difference betwixt IN together with OUT parameters inwards JDBC etc. It's worth to gear upwards this JDBC inquiry inwards detail. By the agency IN parameter is used to move past times input to stored physical care for together with OUT parameter is used to shop output furnish from stored procedure. IF your stored physical care for furnish multiple values than you lot tin orbit notice equally good work ResultSet to traverse all results.

Question 10: What is divergence betwixt Connected together with disconnected RowSet inwards JDBC?
Answer : I own got seen this JDBC inquiry asked equally a follow-up inquiry of previous JDBC interview inquiry RowSet vs ResultSet.  Main divergence betwixt connected together with disconnected RowSet inwards JDBC is that disconnected RowSet doesn't require JDBC Connection piece it's on disconnected state. This makes disconnected RowSet low-cal together with ideal to work inwards sparse clients, piece connected RowSet is only a wrapper some ResultSet. JDBCRowSet together with WebRowSet are 2 examples of connected RowSet while  a CachedRowSet is an lawsuit of disconnected RowSet which caches information inwards memory. Ideal for pocket-size information laid together with sparse Java clients with pocket-size retentiveness human foot print.

Question 11: What is divergence betwixt Statement, PreparedStatement together with CallableStatement inwards Java?
Answer : One of the classical JDBC interview question. Main divergence betwixt Statement together with PreparedSatement is surgical operation together with avoiding SQL Injection equally nosotros own got seen inwards Benefits of using PreparedStatement inwards Java. While CallableStatement has rattling specific work inwards JDBC together with used to telephone telephone stored physical care for from Java program

That's all on these eleven JDBC Interview questions together with answers article. As I said many times, JDBC questions are of import work of whatever Java interview, allow it substance Java or J2EE Interview together with you lot only can't ignore it. Always gear upwards JDBC good plenty to respond whatever JDBC Interview inquiry to perform good inwards Java interviews.

Further Learning
JSP, Servlets together with JDBC for Beginners: Build a Database App
Complete JDBC Programming Part 1 together with 2
10 Tough substance Java Interview inquiry for practice

Jdbc - How To Convert Java.Sql.Date To Java.Util.Date Inwards Coffee Amongst Example

How to convert java.sql.Date into a java.util.Date in addition to vice-versa is a pop JDBC interview question which is equally good asked equally follow-up interrogation of the difference betwixt java.sql.Date in addition to java.util.Date which nosotros bring saw inwards our final article. Since both SQL appointment in addition to Util appointment stores values equally a long millisecond , it's tardily to convert them dorsum in addition to forth. Both java.sql.Date in addition to java.util.Date provides a convenient method called getTime() which returns long millisecond equivalent of wrapped appointment value. Here is a quick illustration of converting java.util.Date to java.sql.Date in addition to and then dorsum to util Date. This article is inwards side past times side of before post service on Java Date in addition to Time API  like How to convert Date to String in addition to How to honour electrical flow Date in addition to Timestamp inwards Java on whatever timezone. if y'all haven't read them already y'all may honour them useful.



Java Example to convert java.sql.Date to java.util.Date

 Since both SQL appointment in addition to Util appointment stores values equally a long millisecond  JDBC - How to Convert java.sql.Date to java.util.Date inwards Java amongst ExampleAs stated higher upwardly nosotros bring used getTime() method inwards this illustration to transfer long millisecond value shape ane Date type, java.sql.Date to around other e.g. java.util.Date, inwards lodge to convert SQL Date into util Date:





public class DateConverter {

    public static void main(String args[]) throws InterruptedException {
     
        //creating instances of java.util.Date which represents today's appointment in addition to time
        java.util.Date straight off = new java.util.Date();
        System.out.println("Value of java.util.Date : " + now);
     
        //converting java.util.Date to java.sql.Date inwards Java
        java.sql.Date sqlDate = new java.sql.Date(now.getTime());
        System.out.println("Converted value of java.sql.Date : " + sqlDate);
     
        //converting java.sql.Date to java.util.Date back
        java.util.Date utilDate = new java.util.Date(sqlDate.getTime());
        System.out.println("Converted value of java.util.Date : " + utilDate);
    }
 
}

Output:
Value of java.util.Date : Tue April 10 00:12:18 VET 2012
Converted value of java.sql.Date : 2012-04-10
Converted value of java.util.Date : Tue April 10 00:12:18 VET 2012


That's all on how to convert java.sql.Date into a java.util.Date inwards Java. equally y'all bring seen its pretty tardily to convert them past times using getTime() method. There is around other means to convert them using String value of ane Date in addition to and then converting String to java.util.Date merely that's non recommended in addition to using getTime() is to a greater extent than convenient than that.


Further Learning
JSP, Servlets in addition to JDBC for Beginners: Build a Database App
Complete JDBC Programming Part 1 in addition to 2
Top 10 JDBC Best practices for Java developer

Tuesday, December 10, 2019

19 Coffee Method Overloading As Well As Overriding Interview Questions As Well As Answers

Method overloading as well as overriding is i of the tricky concept to original as well as that's why its i of the most pop theme inwards Java Interviews. You volition often come across questions similar what is deviation betwixt overloading as well as overriding? or can yous overload method inwards same class? during start few rounds of interview, mostly at telephonic round. Since its purpose of object oriented fundamentals its also practiced to know equally much close these concepts equally possible. In this article, I am sharing simply about of the basic but oft asked questions which are alone based upon overloading as well as overriding concept as well as their implementation inwards Java programming language. By going through these questions, You volition non only create good on interviews but also it volition improve your agreement of Java as well as OOP fundamentals. BTW, if yous are seriously preparing for Java interviews, simply preparing this theme volition non travel plenty as well as yous demand to fix other of import topics equally good e.g. Java Collection framework, multi-threading, JVM internals as well as garbage collections etc. If yous are inwards hurry, I would advise yous to convey a hold off at Java Programming Interview Exposed yesteryear Wrox publication, i of the meliorate mass on Java interviews.



Overloading as well as Overriding Interview Questions

Ok, let's start on questions. Here is my listing of 17 method overloading as well as overriding interview inquiry which covers basics equally good equally simply about tricky purpose of overloading as well as overriding. You tin also write simply about code to bear witness the concept as well as come across when compiler gives mistake as well as which method is acquire called at run-time.



1) What is method overloading inwards Java?
If yous receive got 2 method which does same matter its meliorate they receive got same name, but 2 method cannot receive got same cite until yous overload them. So overloading is a procedure of declaring 2 methods alongside same cite but dissimilar method signature e.g. System.out which is object of PrintStream aeroplane has several println() method to impress dissimilar information types e.g. byte, short, int, char, float as well as double. All of them are called overloaded method. Overloaded method calls are resolved during compile fourth dimension inwards Java as well as they must receive got dissimilar method signatures. See here to acquire to a greater extent than close method overloading inwards Java.


2) What is method overriding inwards Java?
Method overriding is simply about other way to define method alongside same cite but dissimilar code but it must travel inwards sub class. Overriding is based upon run-time Polymorphism equally method calls are resolved at run-time depending upon actual object.  For instance if a variable of type Parent holds an object of Child aeroplane as well as then method invoked volition travel from tiddler aeroplane as well as non bring upwards class, provides its overridden. In guild to override a method, yous must follow rules of method overriding which agency declaring method alongside same signature inwards sub class. See here to acquire to a greater extent than close method overriding inwards Java.


3) What is method hiding inwards Java?
static method cannot travel overriding inwards Java because their method calls are resolved at compile fourth dimension but it didn't foreclose yous from declaring method alongside same cite inwards sub class. In this instance nosotros say that method inwards sub aeroplane has hided static method from bring upwards class. If yous receive got a instance where variable of Parent aeroplane is pointing to object of Child aeroplane as well as then also static method from Parent aeroplane is called because overloading is resolved at compile time. See here to acquire to a greater extent than close method hiding inwards Java.


4) What are rules of overloading a method inwards Java?
One as well as only dominion of method overloading inwards Java is that method signature of all overloaded method must travel different. Method signature is changed yesteryear changing either seat out of method arguments, or type of method arguments e.g. System.out.println() method is overloaded to convey dissimilar primitive types similar int, short, byte, float etc. They all convey simply i declaration but their type is different. You tin also alter method signature yesteryear changing guild of method declaration but that often leads to ambiguous code so meliorate to travel avoided. See here for amount listing of rules.


5) Difference betwixt method overloading as well as overriding?
Fundamental deviation betwixt overloading as well as overriding is that old took house during compile fourth dimension piece after took house during run-time. Due to this reason, its only possible to overload virtual methods inwards Java. You cannot overload methods which are resolved during compile fourth dimension e.g. private, static as well as in conclusion method cannot travel overridden inwards Java. Also, rules of method overloading as well as overriding are different, for instance inwards guild to overload a method its method signature must travel dissimilar but for overriding method it must travel same. See this image to acquire to a greater extent than deviation betwixt overriding as well as overloading inwards Java.

 Method overloading as well as overriding is i of the tricky concept to original as well as that nineteen Java Method Overloading as well as Overriding Interview Questions as well as Answers


6) Can nosotros overload static method inwards Java?
Yes, its possible to overload static method inwards Java. You tin declare equally many static method alongside same cite equally yous desire until all of them receive got dissimilar method signature. Remember, render type is non purpose of method signature, so they must receive got either dissimilar seat out of arguments, or dissimilar type of argument. There is a 3rd alternative also which changes guild of declaration but I advise non to create that because it often resultant inwards ambiguous method call. It's real of import to follow these best practices piece overloading a static method inwards Java.


7) Can nosotros override static method inwards Java?
No, yous cannot override static method inwards Java because they are resolved as well as bonded during compile time. Since overriding is a run-time activeness as well as if a method telephone telephone is already resolved at compile fourth dimension as well as then it volition non convey house as well as that's why its non possible to override static method inwards Java. But, yous tin define simply about other static method of same signature inwards sub class, this is known equally method hiding. Actual method called volition depends upon the type of aeroplane as well as non on type of object equally its the instance alongside overriding. See here to acquire to a greater extent than close why yous cannot override static method inwards Java.


8) Can yous foreclose overriding a method without using in conclusion modifier?
Yes, in that place are simply about funky ways to foreclose method overriding inwards Java. Though in conclusion modifier is only for that purpose yous tin job someone keyword to foreclose method overriding. How? If yous recollect correctly, inwards guild to override a method, the aeroplane must travel extensible. If yous brand the constructor of bring upwards aeroplane someone as well as then its non possible to extend that aeroplane because its constructor volition non travel accessible inwards sub class, which is automatically invoked yesteryear sub aeroplane constructor, thus its non possible to override whatever method from that class. This technique is used inwards Singleton pattern pattern, where constructor is purposefully made someone as well as a static getInstance() method is provided to access singleton instance. See here to acquire to a greater extent than techniques to foreclose method overriding inwards Java.


9) Can nosotros override a someone method inwards Java?
No, yous cannot override someone method inwards Java. Since someone methods are non visible exterior the class, they are non available inwards sub-class thus they cannot travel overridden. By the way, how close overriding a someone method within an Inner class? Is it possible? See here to acquire to a greater extent than why yous cannot override someone method inwards Java.


10) What is co-variant method overriding?
One of the dominion of method overriding is that render type of overriding method must travel same equally overridden method but this restriction is relaxed footling fleck from Java 1.5 as well as straight off overridden method tin render sub aeroplane of render type of original method. This relaxation is known equally co-variant method overriding as well as it allows yous to withdraw casting at customer end. One of the best instance of this comes when yous override clone() method. Original Object.clone() method returns Object which needs to cast, but alongside co-variant method overriding yous tin direct render relevant type e.g. Date aeroplane returns object of java.util.Date instead of java.lang.Object. See hither to acquire to a greater extent than close co-variant method overriding inwards Java.


11) Can nosotros alter declaration listing of overridden method?
No, yous cannot alter the declaration listing of overridden method inwards Java. An overriding method must receive got same signature equally original method. Only render type tin travel changed that to only to sub type of render type of original method.


12) Can nosotros alter render type of method inwards subclass piece overriding?
No, yous cannot alter the render type of method during overriding. It would travel violation of rules of overriding. Though from Java five onward yous tin supersede the render type alongside sub type e.g. if original method has render type equally java.lang.Object as well as then yous tin alter render type of overridden method equally whatever type e.g. clone() method. This is also known equally co-variant method overriding inwards Java.


13) Can nosotros override a method which throws run-time exception without throws clause?
Yes, yous can. There is no restriction on throwing RuntimeException from overriding method. So if your original method throws NullPointerException than its non necessary to throw NPE from overriding method equally well.


14) How create yous telephone telephone super aeroplane version of an overriding method inwards sub class?
You tin telephone telephone it using super keyword. For instance if yous receive got a method calculate() inwards both bring upwards as well as tiddler aeroplane as well as then from tiddler aeroplane yous tin invoke bring upwards aeroplane method calculate() equally super.calculate(). It's real similar to calling super aeroplane constructor from sub aeroplane equally shown here.


15) What are rules of method overriding inwards Java?
Some rules of method overriding are next :
  • Overriding method cannot throw higher exception than overridden one, but that's only truthful for checked exception.
  • Overriding method cannot limit access of overridden method e.g. if original method is world as well as then overriding method must travel public, but it tin expand access e.g. if original method is protected than overriding method tin travel protected or public.
See here for amount listing of rules of method overriding inwards Java.


16) Can nosotros override a non-static method equally static inwards Java?
No, its non possible to define a non-static method of same cite equally static method inwards bring upwards class, its compile fourth dimension mistake inwards Java. See hither to acquire to a greater extent than close overriding static method inwards Java.


17) Can nosotros override constructor inwards Java?
No, yous cannot override constructor inwards Java because they are non inherited. Remember, nosotros are talking close overriding hither non overloading, yous tin overload create but yous cannot override them. Overriding ever happens at tiddler aeroplane as well as since constructor are non inherited as well as their cite is ever same equally the aeroplane cite its non possible to override them inwards Java, to acquire to a greater extent than close constructor come across here


18) Can nosotros override in conclusion method inwards Java?
No, yous cannot override in conclusion method inwards Java. Trying to override in conclusion method inwards subclass volition resultant inwards compile fourth dimension error. Actually making a method in conclusion is signal to all developer that this method is non for inheritance as well as it should travel job inwards its acquaint form. You mostly brand a method in conclusion due to safety reasons, to acquire to a greater extent than come across here.


19) Can yous overload or override principal method inwards Java?
Since main() is a static method inwards Java, it follows rules associated alongside static method, which agency yous tin overload principal method but yous cannot override it. By the way, fifty-fifty if yous overload a principal method, JVM volition ever telephone telephone the criterion public static void main(String args[]) method to start your program, if yous desire to telephone telephone your overloaded method yous demand to create it explicitly inwards your code equally shown here.


That's all close simply about Java interview questions from method overloading as well as overriding concept. I must acknowledge its a tricky concept to master. I receive got seen fifty-fifty experienced developer struggling to solve quiz as well as multiple alternative questions based upon overloading as well as overriding. So, if yous desire to create good on Java Interviews equally good equally wants to write good, powerful as well as flexible code using object oriented programming technique, spare simply about fourth dimension to sympathise overloading as well as overriding inwards Java. It volition assistance yous to leverage Polymorphism better.


Further Learning
Data Structures as well as Algorithms: Deep Dive Using Java
article]
  • 40 Core Java Questions from Phone Interviews [list]
  • 15 Java Enum Interview Questions alongside Answers as well as Explanations [questions]
  • 18 Java Interview Questions based upon GOF Design Patterns as well as OOP [questions]
  • Top 21 Frequently asked Java interview questions for freshers [article]
  • 12 Java Multithreading as well as Concurrency based Interview Questions [see here]
  • JDBC Interview Questions as well as Answers for 2 to iv years experienced developers [see here]
  • 10 Spring Framework based Interview Questions [article]
  • 10 Must know Java Collection framework Interview Questions as well as Answers [read here]
  • 10 Java Web Services based Questions [list]
  • Top 10 Advanced Java Questions for Experienced as well as Senior Programmers [see here]
  • 22 Array concepts based Interview Questions inwards Java? [answers]
  • Sunday, November 24, 2019

    Sqlserverexception: The Index 58 Is Out Of Make - Jdbc

    I was executing a stored physical care for against SQL SERVER 2008 database from Java program using CallableStatement, simply unfortunately, I was getting next fault "SQLServerException: The index 58 is out of range". Since I am passing a lot of parameters I idea that something is incorrect amongst a release of parameters I was passing to the stored proc. My stored physical care for had 58 INPUT parameters, every bit presently every bit I removed the 58th INPUT parameter the fault goes away, which confirmed my belief that SQL SERVER supports a maximum of 57 INPUT parameters inwards stored physical care for via JDBC. This  seems the actually meaning limitation, peculiarly for big tables in addition to I was thinking that It's to a greater extent than probable that 58 is non the actual bound in addition to I mightiness convey missed something.

    My suspicion was correct fifty-fifty though the fault goes away every bit presently every bit I removed the 58th parameter, it was nix to exercise amongst SQL SERVER bound on stored proc parameters simply it was the release of placeholders I had defined entirely 57 placeholders simply I was setting information for 58th parameter using setString() method in addition to that was causing this exception.  How exercise I acquire to know that? Luckily I in 1 lawsuit again got the same fault simply this time, it was complaining well-nigh 35 beingness out-of-range i.e. com.microsoft.sqlserver.jdbc.SQLServerException: The index 35 is out of range. which confirmed my suspicion that I was missing something.


    com.microsoft.sqlserver.jdbc.SQLServerException: The index 58 is out of range

    You acquire the next fault land executing stored physical care for against SQL SERVER 2008 or whatever other version from Java program:



    Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The index 58 is out of range.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(Unknown Source)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setterGetParam(Unknown Source)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setString(Unknown Source)
    at com.microsoft.sqlserver.jdbc.SQLServerCallableStatement.setString(Unknown Source)
    at org.apache.commons.dbcp.DelegatingCallableStatement.setString(DelegatingCallableStatement.java:219)
    at org.apache.commons.dbcp.DelegatingCallableStatement.setString(DelegatingCallableStatement.java:219)

    or

    Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The index 35 is out of range.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(Unknown Source)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setterGetParam(Unknown Source)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setString(Unknown Source)
    at com.microsoft.sqlserver.jdbc.SQLServerCallableStatement.setString(Unknown Source)

    Reason: 
    As I said, the actual argue was  not the SQL SERVER bound simply it was the release of placeholders. I had defined 34 placeholder simply setting information for the 35th column using setString(), setInt() method in addition to that's why JDBC complaining that index 35 is out of range. Remember, the first column inwards JDBC starts amongst index 1 in addition to non zero.


    Java Example
    This fault tin likewise come upward when you lot are using PreparedStatement or CallableStatement in JDBC. Here is an SQL interrogation to think mass details using ISBN release past times calling a stored physical care for from Java Program using Callable Statement:

    String SQL = "{call Books.dbo.usp_BookDetails_Get(?)}"; CallableStatement cs = con.prepareCall(SQL); cs.setString(1, "978-0132778046"); cs.setString(2, "978-0132778047"); ResultSet rs = cs.executeQuery();

    This code volition throw:

    com.microsoft.sqlserver.jdbc.SQLServerException: The index two is out of range.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setterGetParam(SQLServerPreparedStatement.java:714)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setValue(SQLServerPreparedStatement.java:723)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setString(SQLServerPreparedStatement.java:1048)

    Why? because there is entirely 1 interrogation parameter required past times the stored physical care for "?" in addition to index starts from 1 inwards JDBC rather than zero. Hence, index two is invalid because there is no instant placeholder inwards your SQL query.

    This fault tin likewise come upward when you lot are executing PreparedStatement based SQL interrogation which contains house holders or bind parameters every bit shown below:

    PreparedStatement ps = con.prepareStatement("SELECT * from Books WHERE ISBN=?"); ps.setString(1, "978-0132778047"); ps.setString(3, "1");  ResultSet rs = ps.executeQuery(); 

    This code volition throw, the index three is out of make error, every bit you lot tin run across it below:

    com.microsoft.sqlserver.jdbc.SQLServerException: The index three is out of range.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setterGetParam(SQLServerPreparedStatement.java:714)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setValue(SQLServerPreparedStatement.java:723)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setString(SQLServerPreparedStatement.java:1048)

    Similarly, if you lot run across SQLServerException: The index 1 is out of range, it agency at that topographic point is no placeholder inwards PreparedStatement of CallableStatement simply you lot are notwithstanding setting values past times calling diverse setXXX() methods.


    That's all well-nigh the actual drive of "com.microsoft.sqlserver.jdbc.SQLServerException: The index 35 is out of range" fault in addition to how to cook it. The actual argue was that release of placeholder was 34 simply you lot are calling setXXX() method 35 times i.e. to a greater extent than than hence release of defined placeholders. Once you lot take the extra setXXX() telephone band or increased the release of placeholders, the fault was fixed.

    If you lot are novel inwards JDBC hence you lot tin likewise refer JDBC Recipes: H5N1 Problem-Solution Approach mass to acquire to a greater extent than well-nigh how to connect database from Java application:

     I was executing a stored physical care for against SQL SERVER  SQLServerException: The index 58 is out of make - JDBC


    Related JDBC tutorials in addition to troubleshooting guides
    • Difference betwixt type 1 in addition to type four JDBC drivers inwards Java (answer)
    • Top 10 JDBC Interview Questions for Java programmers (list)
    • How to solve java.lang.classnotfoundexception oracle.jdbc.driver.oracledriver? (solution)
    • Cause in addition to solution of java.lang.ClassNotFoundException: com.mysql.jdbc.Driver (solution)
    • How to connect MySQL database from Java program? (guide)
    • How to convert java.util.Date to java.sql.Date inwards JDBC Java? (solution)
    • Top 10 JDBC Best Practices for Java develoeprs (list)
    • java.sql.SQLException: No suitable driver constitute for jdbc:jtds:sqlserver (solution)
    • java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver (solution)


    Further Learning
    JSP, Servlets in addition to JDBC for Beginners: Build a Database App
    Complete JDBC Programming Part 1 in addition to 2
    Java Platform: Working amongst Databases Using JDBC

    Saturday, November 23, 2019

    10 Reasons Of Java.Lang.Numberformatexception Inward Coffee - Solution

    The NumberFormatException is ane of the most mutual errors inwards Java application along amongst NullPointerException. This mistake comes when yous endeavor to convert a String into numeric information types e.g. int, float, double, long, short, char or byte. The information type conversion methods similar Integer.parseInt(), Float.parseFloat(), Double.parseDoulbe(), as well as Long.parseLong() throws NumberFormatException to signal that input String is non valid numeric value. Even though the origin sweat is ever something which cannot live on converted into a number, in that location are many reasons as well as input due to which NumberFormatException occurs inwards Java application. Most of the fourth dimension I convey faced this mistake acre converting a String to int or Integer inwards Java, but in that location are other scenarios every bit good when this mistake occurs. In this article, I am sharing 10 of the most mutual reasons of java.lang.NumberFormatException inwards Java programs.

    Having noesis of these sweat volition assistance yous to understand, analyze as well as solve this mistake inwards your Java application. In each case, you'll run across an mistake message as well as so I'll explicate the argue behind it. It's hard to embrace all scenarios on which JVM throws this mistake but I convey tried to capture every bit many every bit possible here. If yous detect whatsoever other reasons or faced this mistake inwards your Java projection due to anything mentioned below so delight portion amongst us via comments.




    10 mutual reasons of NumberFormatException 

    Here are 10 reasons which I convey seen causing NumberFormatException inwards Java application. If yous convey whatsoever argue which is non listed hither but yous convey seen them causing this error, experience costless to add together it.


    1. Null Value
    Since String is an object, it's possible that it could live on null as well as if yous overstep a null String to a method similar parseInt(), it volition throw NumberFormatException because nothing is non numeric.

    Integer.parseInt(null); Exception in thread "main" java.lang.NumberFormatException: null at java.lang.Integer.parseInt(Integer.java:454) at java.lang.Integer.parseInt(Integer.java:527)

    You tin sack run across that mistake message too contains the declaration to parseInt() which is nothing as well as that's the argue of this error. Thanks to JDK developers for printing the declaration every bit good as well as a lesson to all Java developers who create their custom Exception class, ever impress the input which failed the process.  If yous desire to larn to a greater extent than almost best practices, read Java Coding Guidelines.

     is ane of the most mutual errors inwards Java application along amongst  10 Reasons of java.lang.NumberFormatException inwards Java  - Solution



    2. Empty String
    Another mutual argue of java.lang.NumberFormatException is an empty String value. Many developers intend empty String is OK as well as parseInt() volition provide null or something, but that's non true. The parseInt(), or parseFloat() both volition throw NumberFormat mistake every bit shown below:

    Integer.parseInt(""); Exception in thread "main" java.lang.NumberFormatException: For input string: "" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:504) at java.lang.Integer.parseInt(Integer.java:527)

    Again yous tin sack run across that this method has printed the input, which is empty String as well as which caused the failure.


    3. Alphanumeric Input
    Another mutual argue for NumberFormatException is the alphanumeric input. No non-numeric missive of the alphabet other than + as well as - is non permitted inwards the input string.

    Short.parseShort("A1"); Exception in thread "main" java.lang.NumberFormatException: For input string: "A1" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:492) at java.lang.Short.parseShort(Short.java:117) at java.lang.Short.parseShort(Short.java:143)

    You tin sack run across that our input contains "A" which is non permitted, thence it caused the error, but yous should recollect that Influenza A virus subtype H5N1 is a valid missive of the alphabet when yous convert String to an integer inwards hexadecimal base. See Java: How to Program yesteryear Dietel as well as Dietel to larn to a greater extent than almost information type conversion inwards Java.



    4. Leading space
    You won't believe but leading as well as trailing spaces are ane of the major reasons of NumberFormatException inwards Java, yous volition intend that input String " 123" is Ok but it's not. It has a leading infinite inwards it.

    Long.parseLong(" 123"); Exception in thread "main" java.lang.NumberFormatException: For input string: " 123" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Long.parseLong(Long.java:430) at java.lang.Long.parseLong(Long.java:483)

    Even though parseLong() method is correctly printing the invalid input, it's hard to location the leading or trailing mistake inwards log files, peculiarly trailing one. So, pay special attending to leading as well as trailing infinite acre converting String to long inwards Java, if possible run trim() before passing String to parseLong() method.


    5. Trailing space
    Similar to higher upwardly issue, trailing infinite is simply about other top dog argue for numerous NumberFormatException inwards Java. Influenza A virus subtype H5N1 trailing white infinite is harder to location than a leading white space, item inwards log files.

    Long.parseLong("1001 "); Exception in thread "main" java.lang.NumberFormatException: For input string: "1001 " at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Long.parseLong(Long.java:441) at java.lang.Long.parseLong(Long.java:483)

    To avoid this mistake yous should trim() the input String before passing it to parse methods e.g. parseInt() or parseFloat().



    6. Null String
    We'have already seen a scenario where parseInt() method throws NumberFormatException if the input is null, but sometimes yous volition run across an mistake message similar Exception inwards thread "main" java.lang.NumberFormatException: "null", this is dissimilar than the kickoff scenario. In the kickoff case, nosotros convey a null value, hither nosotros convey a "null" String i.e. an initialized String object whose value is "null". Since this is too non numeric, parseInt(), or parseFloat() volition throw the NumberFormat exception every bit shown below.

    Float.parseFloat("null"); Exception in thread "main" java.lang.NumberFormatException: For input string: "null" at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1250) at java.lang.Float.parseFloat(Float.java:452)

    If yous are non familiar amongst the concept of nothing inwards Java, delight run across Core Java Volume 1 - Fundamentals yesteryear Cay S. Horstmann to larn more.



    7. Floating quest String
    This is fiddling chip different, fifty-fifty though "1.0" is perfectly valid String i.e. it doesn't comprise whatsoever alphanumeric String but if yous endeavor to convert it into integer values using parseInt(), parseShort(), or parseByte() it volition throw NumberFormatException because "1.0" is a floating quest value as well as cannot live on converted into integral one. These methods don't cast they simply create the conversion.

    Long.parseLong("1.0"); Exception in thread "main" java.lang.NumberFormatException: For input string: "1.0" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Long.parseLong(Long.java:441) at java.lang.Long.parseLong(Long.java:483)

    So, live on careful acre converting floating quest String to numbers, they tin sack exclusively live on converted to float or double, but non on integral types similar byte, short, or int.



    8. Out of hit value
    Another rare argue of java.lang.NumberFormatException is out-of-range value. For example, if yous endeavor to convert String "129" to a byte value it volition throw NumberFormatException because maximum positive number byte tin sack stand upwardly for is 127. Clearly, 129 is out-of-range for a byte variable

    Byte.parseByte("129"); Exception in thread "main" java.lang.NumberFormatException: Value out of range. Value:"129" Radix:10 at java.lang.Byte.parseByte(Byte.java:150) at java.lang.Byte.parseByte(Byte.java:174)

    If yous are non familiar amongst information types as well as their hit inwards Java, delight run across Core Java for the Impatient for to a greater extent than information.



    9. Non-printable character
    While working inwards the software industry, sometimes yous confront an effect where yous intend the calculator is wrong, it has gone mad, the input String looks perfectly OK but withal Java is throwing NumberFormatException, this happens but at the end, yous volition realize that calculator is ever right.

    For example, consider this mistake message:
    java.lang.NumberFormatException: For input string: "1" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source)

    "1" is perfectly Ok for parseInt() as well as it volition run fine so why java.lang.NumberFormatException? It turns out that in that location was a non-printable grapheme inwards front end of 1 which was non displaying inwards the house where yous are seeing. So, sentinel out for the non-printable grapheme if yous are facing weird error.



    10. Similar characters e.g 1 as well as l
    This is the unopen cousin of before error, this fourth dimension too our oculus believes that input String is valid as well as intend that calculator has gone mad, but it wasn't. Only later spending hours yous realize that Java was right, the String yous are trying to convert into number was non numeric ane "1" instead it was little instance missive of the alphabet L i.e. "l". You tin sack run across it's real subtle as well as non obvious from naked oculus unless yous are actually paying attention.

    Integer.parseInt("l"); Exception in thread "main" java.lang.NumberFormatException: For input string: "l" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:492) at java.lang.Integer.parseInt(Integer.java:527)


    From the mistake message, it looks similar the mistake is for numeric String "1". So live on careful amongst this.

    Here is the prissy slide to combine all these reasons into one, which yous tin sack portion every bit good :

     is ane of the most mutual errors inwards Java application along amongst  10 Reasons of java.lang.NumberFormatException inwards Java  - Solution


    That's all almost 10 mutual reasons of java.lang.NumberFormatException as well as how to solve them. It's ane of those errors where yous involve to investigate to a greater extent than almost information than code. You involve to detect the source of invalid information as well as right it. In code, simply brand certain yous choose grip of the NumberFormatException whenever yous convert a String to number inwards Java. Also, if yous acquire input from the user, brand certain yous perform validation. Use Scanner if taking input from dominance work as well as methods similar nextInt() to direct read integer instead of reading String as well as so parsing it to int in ane trial to a greater extent than using parseInt() method, exclusively to live on greeted yesteryear NumberFormatExcpetion.


    Other Java troubleshooting tutorials you may similar to explore
    • How to create "Error: Could non detect or charge top dog class" inwards Eclipse? (guide)
    • How to avoid ConcurrentModificationException inwards Java? (tutorial)
    • How to solve "could non create the Java virtual machine" mistake inwards Java? (solution)
    • How to create "illegal start of expression" compile fourth dimension mistake inwards Java? (tutorial)
    • Fixing java.lang.unsupportedclassversionerror unsupported major.minor version 50.0 (solution)
    • Cause as well as solution of "class, interface, or enum expected" compiler mistake inwards Java? (fix)
    • java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory mistake (solution)
    • How to solve java.lang.ClassNotFoundException: com.mysql.jdbc.Driver error? (hint)
    • How to solve java.lang.classnotfoundexception oracle.jdbc.driver.oracledriver? (solution)
    • Common reasons of java.lang.ArrayIndexOutOfBoundsException inwards Java? (solution)
    • java.lang.ClassNotFoundException : org.Springframework.Web.Context.ContextLoaderListener (solution)
    • How to solve "variable mightiness non convey initialized" compile fourth dimension mistake inwards Java? (answer)
    • How to create 'javac' is non recognized every bit an internal or external command (solution)
    • How to create Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger (solution)
    • How to solve java.lang.OutOfMemoryError: Java Heap Space inwards Eclipse, Tomcat? (solution)


    Further Learning
    Complete Java Masterclass
    Java Fundamentals: The Java Language
    Java In-Depth: Become a Complete Java Engineer!



    Saturday, November 9, 2019

    Top 12 Coffee Thread, Concurrency In Addition To Multithreading Interview Questions For Experienced

    Java concurrency as well as thread interview questions answers
    Multithreading is an of import characteristic of Java programming language, which agency threads are too an of import purpose of whatsoever Java interview. It's truthful as well as inward fact at beginners as well as freshers bird Thread interview questions inward Java are 1 of most hard to answer. One argue for interview query related to multithreading as well as concurrency beingness hard is confusion unopen to how multiple threads plant together as well as minute is threads are really a complicated theme to empathise as well as usage correctly. Mostly thread interview questions checks Java programmers noesis on Java Thread API, Java concurrency API, issues related to multi-threading similar a race condition, thread-safety, as well as deadlock. Some fourth dimension multithreading as well as concurrency interview query too focus on parallel blueprint patterns similar solving the producer-consumer problem, implementing travel bag pattern or solving dining philosopher work inward Java. This is especially truthful spell interviewing experienced Java developers amongst iv to half-dozen years of experience.

    In this article, nosotros volition withdraw maintain a expression at dissimilar kinds of multithreading as well as concurrency questions asked inward diverse interviews e.g. on telephonic or human face upward to human face upward interview, on written test, to both experienced as well as senior Java developers, as well as some tips to reply them correctly.

    Questions asked on telephonic or the first circular of interviews are tend to travel easier as well as you lot must reply them to the betoken amongst a keyword, which interviewer is expecting. On the human face upward to human face upward interview, travel laid upward for dissimilar kinds of follow-up questions.




    Java Interview questions on Concurrency as well as multithreading

    As I said, inward this Java article, non only,  I volition percentage some of the most commonly asked thread interview questions at freshers as well as beginners level, similar upward to 2 to iv years of experience, as well as some tips as well as tricks to reply them correctly.

    By the way, these thread interview questions are as useful for senior Java developers or guys amongst some Java sense inward hand. I withdraw maintain tried to percentage answers to these interview questions on the thread as good but I propose you lot do some enquiry as well as larn the theme good to reply whatsoever follow-up questions, which comes due to your response to these thread questions inward Java.

    Anyway hither is my collection of Java thread interview questions as well as how to answers them inward Java :


    1) What is the departure betwixt start as well as run method inward Java Thread? (answer)
    This thread interview query is too inquire as if start() method eventually telephone phone run() method as well as then why do you lot demand to telephone phone start() method, why non telephone phone run() method directly. well, argue is that because start method creates a novel thread as well as telephone phone the code written within the run method on a novel thread spell calling run method executes that code on the same thread. You tin too come across the article start vs run method inward Java for to a greater extent than details.



    2) Write code to avoid deadlock inward Java where due north threads are accessing due north shared resources? (answer)
    This is a classic Java multithreading interview questions, which appears on almost every listing of Java thread questions. This query is based on jeopardy as well as issues faced past times parallel programs without proper synchronization or wrong synchronization. This query explores the concept of looking as well as best practices on acquiring as well as releasing the lock on shared resource. By the way, it's been covered inward many places as good as well as I propose reading  How to preclude deadlock inward Java, non exclusively for particular reply of this Java multithreading query but too to larn how to preclude deadlock inward Java.



    3) Which 1 is improve to implement thread inward Java ? extending Thread degree or implementing Runnable? (answer)
    Well, this is some other ofttimes asked questions on whatsoever Java thread interview. Essentially these are ii way to implement Thread inward Java, past times extending java.lang.Thread degree or past times implementing java.lang.Runnable interface.

    By extending the degree you lot are using your adventure to extend 1 whatsoever exclusively 1 degree as Java does non back upward multiple inheritances, past times implementing a Runnable interface you lot tin yet extend some other class. So extending Runnable or fifty-fifty Callable is a improve choice. You tin too come across Runnable vs Thread degree inward Java for to a greater extent than answers on this questions.

    Given its simplicity as well as fact-based nature, this query generally appears on either telephonic circular or initial screening rounds. Key points to mention, spell answering this query includes multiple inheritance at the degree bird as well as separation of defining a chore as well as execution of a task. Runnable exclusively stand upward for a task, spell Thread stand upward for both tasks as well as it's execution.




    4) What is Busy Spinning? Why volition you lot usage Busy Spinning as hold off strategy? (answer)
    This is 1 of the advanced concurrency interview questions inward Java as well as exclusively asked to experienced as well as senior Java developers, amongst lots of concurrent coding sense nether the belt. By the way, the concept of busy spinning is non new, but its usage amongst multi-core processor has risen lately (see The Art of Multiprocessor Programming).

    Java concurrency as well as thread interview questions answers Top 12  Java Thread, Concurrency as well as Multithreading Interview Questions For experienced

    The busy waiting is a hold off strategy, where 1 thread hold off for a status to overstep away true, but instead of calling hold off or slumber method as well as releasing CPU, it only spins. This is specially useful if the status is going to travel truthful quite chop-chop i.e. inward a millisecond or microsecond.

    The wages of non releasing CPU is that all cached information as well as teaching stay unaffected, which may travel lost, had this thread is suspended on 1 heart as well as brought dorsum to some other thread. If you lot tin reply this question, that residual assure of a practiced impression.


    5) What is the departure betwixt CountDownLatch and CyclicBarrier in Java? (answer)
    The CountDownLatch and CyclicBarrier inward Java are ii of import concurrency utility which is added on Java v Concurrency API. Both are used to implement scenario, where 1 thread has to hold off for other thread earlier starting processing but at that spot is a departure betwixt them.

    The fundamental betoken to mention, spell answering this query is that CountDownLatch is non reusable in 1 trial the count reaches to zero, spell CyclicBarrier tin travel reused fifty-fifty after the barrier is broken.

    You tin too come across my previous article difference betwixt CyclicBarrier as well as CountDownLatch inward Java for a to a greater extent than detailed reply of this concurrency interview query as well as a existent life trial of where to usage these concurrency utilities.



    6) What is the departure betwixt hold off as well as slumber inward Java? (method)
    One to a greater extent than classic Java multithreading question from the telephonic circular of interviews. The fundamental betoken to advert spell answering this query is to advert that hold off volition release the lock as well as must travel called from the synchronized context, spell slumber volition exclusively intermission the thread for some fourth dimension as well as overstep away on the lock.

    By the way, both methods throw IntrupptedException and tin travel interrupted, which tin Pb to some follow-up questions like, tin nosotros awake a sleeping or waiting for a thread inward Java? You tin too read a detailed reply on my postal service of same championship here.

    Java concurrency as well as thread interview questions answers Top 12  Java Thread, Concurrency as well as Multithreading Interview Questions For experienced



    7) How do you lot solve producer consumer work inward Java? (solution)
    One of my favorite questions during whatsoever Java multithreading interview, Almost one-half of the concurrency problems tin travel categorized inward the producer-consumer pattern. There are basically ii ways to solve this work inward Java, One past times using hold off as well as notify method as well as other past times using BlockingQueue in Java.  later is slow to implement as well as a practiced selection if you lot are coding inward Java 5.

    The fundamental points to mention, spell answering this query is thread-safety and blocking nature of BlockingQueue as well as how that helps, spell writing concurrent code. You tin too expression lots of follow-up questions including, what give off if you lot withdraw maintain multiple producer or multiple consumers, what volition give off if a producer is faster than consumer thread or vice-versa. You tin too come across this link for trial of how to code producer-consumer blueprint inward Java using blocking queue



    8) Why is ConcurrentHashMap faster than Hashtable inward Java? (answer)
    ConcurrentHashMap is introduced as an alternative of Hashtable inward Java 5, it is faster because of its design. ConcurrentHashMap divides the whole map into dissimilar segments as well as exclusively lock a particular segment during the update operation, instead of Hashtable, which locks whole Map.

    The ConcurrentHashMap also provides lock-free read, which is non possible inward Hashtable, because of this as well as lock striping, ConcurrentHashMap is faster than Hashtable, especially when a number of the reader is to a greater extent than than the number of writers.

    In lodge to improve reply this pop Java concurrency interview questions, I propose reading my postal service almost the internal working of ConcurrentHashMap inward Java.




    9) What is the departure betwixt submit() as well as execute() method of Executor as well as ExecutorService inward Java? (answer)
    The primary departure betwixt submit as well as execute method from ExecutorService interface is that one-time render a termination inward the shape of a Future object, spell afterward doesn't render a result. By the way, both are used to submit a chore to thread puddle inward Java but 1 is defined inward Executor interface,while other is added into ExecutorService interface. This multithreading interview query is too asked inward the commencement circular of Java interviews.


    10) How do you lot percentage information betwixt ii threads inward Java? (answer)
    One to a greater extent than Java multithreading query from the telephonic circular of interview. You tin percentage information betwixt thread past times using shared object or shared information structures similar Queue. Depending upon, what you lot are using, you lot demand to render the thread-safety guarantee, as well as 1 way of providing thread-safety is using synchronized keyword.

    If you lot usage concurrent collection classes from Java v e.g. BlockingQueue, you lot tin easily percentage information without beingness bothered almost thread security as well as inter-thread communication. I similar this thread question, because of it's simplicity as well as effectiveness. This too leads farther follow-up questions on issues which arise due to sharing information betwixt threads e.g. race conditions.



    11) What is ReentrantLock inward Java? Have you lot used it before? (answer)
    ReentrantLock is an alternative of synchronized keyword inward Java, it is introduced to handgrip some of the limitations of synchronized keywords. Many concurrency utility classes as well as concurrent collection classes from Java 5, including ConcurrentHashMap uses ReentrantLock, to leverage optimization.

    The ReentrantLock generally uses an atomic variable as well as faster CAS functioning to provides improve performance. Key points to advert are the difference betwixt ReentrantLock as well as synchronized keyword inward Java, which includes the mightiness to acquire lock interruptibly, timeout characteristic spell waiting for lock etc. ReentrantLock too gives the alternative to do fair lock inward Java.Once in 1 trial to a greater extent than a rattling practiced Java concurrency interview query for experienced Java programmers.
    Books similar Java Programming Interview exposed too helps you lot to laid upward improve as well as reply to the point.

    Java concurrency as well as thread interview questions answers Top 12  Java Thread, Concurrency as well as Multithreading Interview Questions For experienced



    12) What is ReadWriteLock inward Java? What is the do goodness of using ReadWriteLock inward Java?(answer)
    This is ordinarily a follow-up query of previous Java concurrency questions. The  ReadWriteLock is in 1 trial to a greater extent than based upon the concept of lock striping, 1 of the advance thread-safety machinery which advocates separating locks for reading as well as writing operations (see Java Concurrency inward Practice Bundle past times Heinz Kabutz for to a greater extent than details).

    If you lot withdraw maintain noticed before, reading functioning tin travel done without locking if at that spot is no author as well as that tin hugely improve the performance of whatsoever application. The ReadWriteLock leverage this thought as well as render policies to allow maximum concurrency level. Java Concurrency API too provides an implementation of this concept as ReentrantReadWriteLock.

    Depending upon Interviewer as well as sense of the candidate, you lot tin fifty-fifty expression to render your ain implementation of ReadWriteLock, thence travel laid upward for that as well.

    Here is a prissy diagram which clearly explains working of read-write lock inward Java:

    Java concurrency as well as thread interview questions answers Top 12  Java Thread, Concurrency as well as Multithreading Interview Questions For experienced



    These were some of my favorite interview questions based on multithreading as well as concurrent inward Java. Threading as well as Concurrency is a big theme inward Java as well as has lots of interesting, tricky as well as tough question but for starters as well as freshers, these questions sure aid to clear whatsoever thread interview inward Java.

    As I said, mentioning the fundamental points are rattling of import spell answering questions on multithreading as well as concurrency.  I too propose farther reading Java Concurrency inward Practice to larn to a greater extent than almost locking, synchronization, concurrent collections as well as concurrency utility classes to do good inward heart Java as well as multithreading interviews.

    Further Learning
    Multithreading as well as Parallel Computing inward Java
    15 Technical Core Java Questions asked to Experienced Programmer on Interviews
    Good Questions on Java Collection as well as Concurrent Collection amongst answers
    Top 10 Java Design Pattern Questions as well as How to reply them
    10 Spring MVC Interview Questions for Java Programmers
    10 Java Enum Interview Questions Answers for beginners
    Top 10 JDBC Interview Questions for Experienced Programmers
    Top 10 RESTful Web Service Interview Questions as well as Answers