Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Java tutorial do's and don'ts of java programming.


Published on

Download this..its very useful especially for Java Developers.. :)


  • Be the first to comment

  • Be the first to like this

Java tutorial do's and don'ts of java programming.

  1. 1. Dr Java Workshop – By Satyarth Gaur We will cover the following areas:  - Top 10 mistakes made by Java programmers – How to avoid them    - Core Java- Best Practices – This covers good and bad practices both - How to prepare for Java Interviews and Sun Java Exams
  2. 2. Top Ten Errors Java Programmers Make SATYARTH GAUR [email_address]
  3. 3. Accessing non-static member variables from static methods (such as main) <ul><li>public class StaticDemo </li></ul><ul><li>{ </li></ul><ul><li>public String my_member_variable = &quot;somedata&quot;; </li></ul><ul><li>public static void main (String args[]) </li></ul><ul><li>{ </li></ul><ul><li>// Access a non-static member from static method </li></ul><ul><li>System.out.println (&quot;This generates a compiler error&quot; + </li></ul><ul><li>my_member_variable ); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  4. 4. Contd.. <ul><li>public class NonStaticDemo </li></ul><ul><li>{ </li></ul><ul><li>public String my_member_variable = &quot;somedata&quot;; </li></ul><ul><li>  </li></ul><ul><li>public static void main (String args[]) </li></ul><ul><li>{ </li></ul><ul><li>NonStaticDemo demo = new NonStaticDemo(); </li></ul><ul><li>  // Access member variable of demo </li></ul><ul><li>System.out.println (&quot;This WON'T generate an error&quot; + </li></ul><ul><li>demo.my_member_variable ); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  5. 5. Mistyping the name of a method when overriding <ul><li>If you mistype the name, you're no longer overriding a method - you're creating an entirely new method, but with the same parameter and return type. </li></ul>
  6. 6. Comparison assignment (  = rather than == ) <ul><li>Fortunately, even if you don't spot this one by looking at code on the screen, your compiler will. Most commonly, it will report an error message like this : &quot;Can't convert xxx to boolean&quot;, where xxx is a Java type that you're assigning instead of comparing. </li></ul>
  7. 7. Comparing two objects ( == instead of .equals) <ul><li>When we use the == operator, we are actually comparing two object references, to see if they point to the same object. We cannot compare, for example, two strings for equality, using the == operator. We must instead use the .equals method, which is a method inherited by all classes from java.lang.Object. </li></ul><ul><li>Ex. String Comparison </li></ul><ul><li>String abc = &quot;abc&quot;; String def = &quot;def&quot;; </li></ul><ul><li>  // Bad way if ( (abc + def) == &quot;abcdef&quot; ) { ….. } </li></ul><ul><li>// Good way if ( (abc + def).equals(&quot;abcdef&quot;) ) { ..... } </li></ul>
  8. 8. Confusion over passing by value, and passing by reference <ul><li>When you pass a primitive data type, such as a char, int, float, or double, to a function then you are passing by value . That means that a copy of the data type is duplicated, and passed to the function. That means that a copy of the data type is duplicated, and passed to the function. If the function chooses to modify that value, it will be modifying the copy only. </li></ul>
  9. 9. Contd.. <ul><li>When you pass a Java object, such as an array, a vector, or a string, to a function then you are passing by reference .So that means that if you pass an object to a function, you are passing a reference to it, not a duplicate. Any changes you make to the object's member variables will be permanent </li></ul>
  10. 10. Writing blank exception handlers <ul><li>public static void main(String args[]) </li></ul><ul><li>{ </li></ul><ul><li>    try { </li></ul><ul><li>// Your code goes here.. </li></ul><ul><li>    } </li></ul><ul><li>    catch (Exception e) </li></ul><ul><li>    { </li></ul><ul><li>System.out.println (&quot;Err - &quot; + e ); </li></ul><ul><li>    } </li></ul><ul><li>} </li></ul>
  11. 11. Forgetting that Java is zero-indexed <ul><li>If you've come from a C/C++ background, you may not find this quite as much a problem as those who have used other languages. In Java, arrays are zero-indexed, meaning that the first element's index is actually 0 </li></ul>
  12. 12. Example Contd.. <ul><li>// Create an array of three strings </li></ul><ul><li>String[] strArray = new String[3]; </li></ul><ul><li>  // First element's index is actually 0 </li></ul><ul><li>strArray[0] = &quot;First string&quot;; </li></ul><ul><li>  // Second element's index is actually 1 </li></ul><ul><li>strArray[1] = &quot;Second string&quot;; </li></ul><ul><li>  // Final element's index is actually 2 </li></ul><ul><li>strArray[2] = &quot;Third and final string&quot;; </li></ul>
  13. 13. Preventing concurrent access to shared variables by threads <ul><li>The simplest method is to make your variables private (but you do that already,  right?) and to use synchronized accessor methods. Accessor methods allow access to private member variables, but in a controlled manner. Take the following accessor methods, which provide a safe way to change the value of a counter. </li></ul>
  14. 14. Contd.. <ul><li>public class MyCounter{ </li></ul><ul><li>private int count = 0; // count starts at zero </li></ul><ul><li>  public synchronized void setCount(int amount) </li></ul><ul><li>{ </li></ul><ul><li>count = amount; </li></ul><ul><li>} </li></ul><ul><li>public synchronized int getCount() </li></ul><ul><li>{ </li></ul><ul><li>return count; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  15. 15. Capitalization errors <ul><li>While there's no silver bullet for detecting this error, you can easily train yourself to make less of them. There's a very simple trick you can learn :- </li></ul><ul><li>all methods and member variables in the Java API begin with lowercase letters </li></ul><ul><li>all methods and member variables use capitalization where a new word begins e.g - getDoubleValue() </li></ul>
  16. 16. Capitalization errors <ul><li>While there's no silver bullet for detecting this error, you can easily train yourself to make less of them. There's a very simple trick you can learn :- </li></ul><ul><li>all methods and member variables in the Java API begin with lowercase letters </li></ul><ul><li>all methods and member variables use capitalization where a new word begins e.g - getDoubleValue() </li></ul>
  17. 17. Null pointers <ul><li>When an attempt to access an object is made, and the reference to that object is null, a NullPointerException will be thrown. </li></ul><ul><li>The cause of null pointers can be varied, but generally it means that either you haven't initialized an object, or you haven't checked the return value of a function. </li></ul>
  18. 18. Java Best Practices Java Fundamentals & Object-Oriented Programming Dr Java Boot Camp – Satyarth Gaur
  19. 19. Bad Practices
  20. 20. Duplicate Code! <ul><li>Every time you need to make a change in the routine, you need to edit it in several places. </li></ul><ul><li>Don’t copy-paste code! </li></ul>
  21. 21. Accessible Fields <ul><li>Fields should always be private except for constants. </li></ul><ul><li>Accessible fields cause tight coupling. </li></ul><ul><li>Accessible fields are corruptible. </li></ul><ul><li>If a field needs to be accessed, use “get” and “set” convention. </li></ul>
  22. 22. Using Magic Numbers <ul><li>Magic numbers are not readable </li></ul><ul><ul><ul><li>for (int i = 1; i =< 52; i++) { </li></ul></ul></ul><ul><ul><ul><ul><li>j = i + randomInt(53 - i) – 1 </li></ul></ul></ul></ul><ul><ul><ul><ul><li>swapEntries(i, j) </li></ul></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><li>Replace with constants. </li></ul><ul><ul><ul><li>final int DECKSIZE = 52; </li></ul></ul></ul><ul><ul><ul><li>for (int i = 1; i =< DECKSIZE; i++) { </li></ul></ul></ul><ul><ul><ul><ul><li>j = i + randomInt(DECKSIZE + 1 - i) – 1 </li></ul></ul></ul></ul><ul><ul><ul><ul><li>swapEntries(i, j) </li></ul></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul>
  23. 23. Temporary Fields <ul><li>If a variable need not be shared across methods, make it local. </li></ul><ul><ul><ul><li>private int x; </li></ul></ul></ul><ul><ul><ul><li>int method() { </li></ul></ul></ul><ul><ul><ul><ul><li>x = 0; // if you forget to initialize, you're dead </li></ul></ul></ul></ul><ul><ul><ul><ul><li>... // do some stuff </li></ul></ul></ul></ul><ul><ul><ul><ul><li>return x; </li></ul></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><ul><li>int method() { </li></ul></ul></ul><ul><ul><ul><ul><li>int x = 0; </li></ul></ul></ul></ul><ul><ul><ul><ul><li>... // do some stuff </li></ul></ul></ul></ul><ul><ul><ul><ul><li>return x; </li></ul></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul>
  24. 24. Initializing Strings with “new” <ul><li>Don’t: </li></ul><ul><li>String str = new String(“This is bad.”); </li></ul><ul><li>Do: </li></ul><ul><ul><li>String str = “This is good.”; </li></ul></ul>
  25. 25. Using floats and doubles for currency calculations <ul><li>Binary numbers cannot exactly represent decimals. </li></ul><ul><li>Use BigDecimal for currency calculations. </li></ul><ul><ul><li>...using the constructor that takes a String as a parameter. </li></ul></ul>
  26. 26. Returning null <ul><li>Causes NullPointerExceptions. </li></ul><ul><li>Instead, return… </li></ul><ul><ul><li>empty objects </li></ul></ul><ul><ul><li>custom-made “Null Objects” </li></ul></ul>
  27. 29. Subclassing for Functionality <ul><li>Implementation inheritance is difficult to debug. </li></ul><ul><li>Ask yourself: “Is this a kind of…?” </li></ul><ul><li>Alternatives: </li></ul><ul><ul><li>Prefer interface inheritance. </li></ul></ul><ul><ul><li>Prefer composition over inheritance. </li></ul></ul>
  28. 30. Empty Catch Block <ul><li>No indication that an exception has occurred! </li></ul>
  29. 31. Using Exceptions Unexceptionally <ul><li>Use exceptions only for exceptional conditions. </li></ul><ul><li>Bad: </li></ul><ul><ul><li>try { </li></ul></ul><ul><ul><li>obj = arr[index]; </li></ul></ul><ul><ul><li>} catch (ArrayIndexOutOfBoundsException) { </li></ul></ul><ul><ul><li>// do something </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>Good: </li></ul><ul><ul><li>if (index < 0 || index >= arr.size()) { </li></ul></ul><ul><ul><li>// do something </li></ul></ul><ul><ul><li>} else { </li></ul></ul><ul><ul><li>obj = arr[index]; </li></ul></ul><ul><ul><li>} </li></ul></ul>
  30. 32. Excessive Use of Switches <ul><li>Use of “if” and “switch” statements usually a sign of a breach of the “One Responsibility Rule”. </li></ul><ul><li>Consider polymorphism instead. </li></ul>
  31. 33. instanceof <ul><li>If you’re using instanceof often, it probably means bad design. </li></ul><ul><li>Consider adding an overridden method in supertype. </li></ul><ul><li>instanceof should only be used </li></ul><ul><ul><li>as validation prior to casting </li></ul></ul><ul><ul><li>when you have to used a poorly-written library </li></ul></ul>
  32. 34. Static Methods <ul><li>Static methods are.. </li></ul><ul><ul><li>...procedural </li></ul></ul><ul><ul><ul><li>They break encapsulation - the method should be part of the object that needs it </li></ul></ul></ul><ul><ul><li>...not polymorphic </li></ul></ul><ul><ul><ul><li>You can't have substitution/pluggability. </li></ul></ul></ul><ul><ul><ul><ul><li>You can't override a static method because the implementation is tied to the class it's defined in. </li></ul></ul></ul></ul><ul><ul><ul><li>Makes your code rigid, difficult to test. </li></ul></ul></ul>
  33. 35. System.exit <ul><li>Only use in stand-alone applications. </li></ul><ul><li>For server applications, this might shut down the whole application container! </li></ul>
  34. 36. Good Practices
  35. 37. Validate Your Parameters <ul><li>The first lines of code in a method should check if the parameters are valid: </li></ul><ul><ul><li>void myMethod(String str, int index, Object[] arr) { </li></ul></ul><ul><ul><li>if (str == null) { </li></ul></ul><ul><ul><li> throw new IllegalArgumentException(“str cannot be null”); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>if (index >= arr.size || index < 0) { </li></ul></ul><ul><ul><li>throw new IllegalArgumentException(“index exceeds </li></ul></ul><ul><ul><ul><ul><li>bounds of array”); </li></ul></ul></ul></ul><ul><ul><li>} … </li></ul></ul><ul><ul><li>} </li></ul></ul>
  36. 38. Create Defensive Copies <ul><li>Create local copies, to prevent corruption. </li></ul><ul><ul><li>void myMethod (List listParameter) { </li></ul></ul><ul><ul><ul><li>List listCopy = new ArrayList(listParameter); </li></ul></ul></ul><ul><ul><ul><li>listCopy.add(somevar); </li></ul></ul></ul><ul><ul><ul><li>... </li></ul></ul></ul><ul><ul><li>} </li></ul></ul>
  37. 39. Modify Strings with StringBuilder <ul><li>String objects are immutable. </li></ul><ul><ul><li>You may think you’re changing a String, but you’re actually creating a new object. </li></ul></ul><ul><ul><li>Danger of OutOfMemoryErrors. </li></ul></ul><ul><ul><li>Poor peformance. </li></ul></ul><ul><li>StringBuilder is mutable. </li></ul><ul><ul><li>All changes are to the same object. </li></ul></ul>
  38. 40. Favor Immutability <ul><li>If your objects don’t change… easier to debug. </li></ul><ul><li>Fields are private and final. </li></ul><ul><li>No setters, only getters. </li></ul>
  39. 41. Prefer “final” for Variables <ul><li>Usually, variables / parameters do not need to change. </li></ul><ul><li>Get into the habit of using final by default, and make a variable not final only when necessary. </li></ul>
  40. 42. Declare Variable Just Before Use <ul><li>Easier to read and refactor. </li></ul>
  41. 43. Initialize Variables Whenever Possible <ul><li>Helpful in debugging, makes it clear what initial value is. </li></ul><ul><li>Makes sure you don’t use the variable before it’s ready for use. </li></ul>
  42. 44. Follow Code Conventions <ul><li>Improves readability </li></ul><ul><ul><li>For other programmers. </li></ul></ul><ul><ul><li>For yourself. </li></ul></ul><ul><li>Readability means… </li></ul><ul><ul><li>… less bugs. </li></ul></ul><ul><ul><li>… easier to debug. </li></ul></ul>
  43. 45. Refer to Objects by Interfaces <ul><li>Maintainability - changes in implementation need only be done at a single point in code </li></ul><ul><li>Polymorphism – implementation can be set at runtime. </li></ul><ul><ul><ul><li>// bad: </li></ul></ul></ul><ul><ul><ul><li>ArrayList list = new ArrayList(); </li></ul></ul></ul><ul><ul><ul><li>list.add(somevar); </li></ul></ul></ul><ul><ul><ul><li>// good: </li></ul></ul></ul><ul><ul><ul><li>List list = new ArrayList(); </li></ul></ul></ul><ul><ul><ul><li>list.add(somevar); </li></ul></ul></ul>
  44. 46. Consider Using Enums instead of Constants <ul><li>Constants: </li></ul><ul><ul><li>Not typesafe </li></ul></ul><ul><ul><li>No namespace </li></ul></ul><ul><ul><ul><li>You often need to prefix constants to avoid collisions </li></ul></ul></ul><ul><ul><li>Brittleness </li></ul></ul><ul><ul><ul><li>When you change the order, you need to change a lot of code. </li></ul></ul></ul><ul><ul><li>Printed values are uninformative </li></ul></ul>
  45. 47. Close Your I/O Streams <ul><li>If you don’t close, other applications may not be able to use the resource. </li></ul><ul><li>Close using the “finally” block in a try-catch. </li></ul>
  46. 48. Design Close to Domain <ul><li>Code is easily traceable if it is close to the business it is working for. </li></ul><ul><li>If possible, name and group your packages according to the use cases. </li></ul><ul><ul><li>Easy to tell client %completion of feature. </li></ul></ul><ul><ul><li>If user reports a bug, easier to find where it is. </li></ul></ul>
  47. 49. If You Override equals() Override hashcode() <ul><li>Always make sure that when equals() returns true, the two object have the same hashcode. </li></ul><ul><li>Otherwise, data structures like Sets and Maps may not work. </li></ul>
  48. 50. Write Self-Documenting Code <ul><li>Comments are important, but… </li></ul><ul><li>… even without comments your code should be easily readable. </li></ul><ul><li>Ask yourself: “If I removed my comments, can someone else still understand my code?” </li></ul>
  49. 51. Use Javadoc Liberally <ul><li>Provide as much documentation about your code as possible. </li></ul>
  50. 52. Bubble-Up Exceptions <ul><li>If code is not part of the user interface, it should not handle its own exceptions. </li></ul><ul><li>It should be bubbled-up to presentation layer… </li></ul><ul><ul><ul><li>Show a popup? </li></ul></ul></ul><ul><ul><ul><li>Show an error page? </li></ul></ul></ul><ul><ul><ul><li>Show a commandline message? </li></ul></ul></ul><ul><ul><ul><li>Just log to an error log? </li></ul></ul></ul>
  51. 53. Best Sites for Java Examples,Code Samples,Tutorials and Interview Preparation <ul><li>www. roseindia .net </li></ul><ul><li>www. vaannila .com </li></ul><ul><li>www. java2s .com </li></ul><ul><li>www. javaprepare .com SCJP </li></ul>
  52. 54. Contd.. <ul><li>www. techinterviews .com </li></ul><ul><li> </li></ul><ul><li> </li></ul><ul><li>SCJP 5 /6 By Kathy Sierra -- E book </li></ul><ul><li> </li></ul>