Site icon DED9

30 Tips On Java Programming And Best Practices For Beginners

Java

Java

Java is one of the most popular programming languages ​​- Windows applications, web applications, mobile applications, networks, consumer electronics, and configuration box devices – Java is ubiquitous.

More than 3 billion devices work with Java. According to Oracle, 5 billion Java cards are in use. More than 9 million developers have chosen Java to write their code, and it is very popular among developers and is also the most popular development platform.

Here are some suggestions on how to look or get an appointment for Java developers:

1. Use empty return sets instead of Null.

If the program returns a set that has no value, make sure the empty set is returned instead of the Null elements. This causes a large number of “if else” to be removed to test Null elements.

public class getLocationName {

    return (null == cityName? “”: cityName);

}

2- Use the strings carefully.

If two strings are connected in a “for” loop using the “+” operator, a new string object is created in each loop iteration. This wastes memory and increases runtime. Also, when making a prototype of a string object, you should avoid the manufacturers and it should be made directly. for example:

// Slower Instantiation

String bad = new String (“Yet another string object”);

// Faster Instantiation

String good = “Yet another string object”

3. Avoid unnecessary objects.

One of the most expensive operations (in terms of memory usage) in Java is Object Creation. It is therefore recommended that objects be created or initialized only if necessary. The following code provides an example:

import java.util.ArrayList;

import java.util.List;

public class Employees {

    private List Employees;

    public List getEmployees () {

        // initialize only when required

        if (null == Employees) {

            Employees = new ArrayList ();

        }

        return Employees;

    }

}

4- Array between Array and ArrayList

It is often difficult for developers to decide whether to use the ArrayList structure for array data types. Both have their strengths and weaknesses. The choice really depends on the requirements.

import java.util.ArrayList;

public class arrayVsArrayList {

    public static void main (String [] args) {

        int [] myArray = new int [6];

        myArray [7] = 10; // ArraysOutOfBoundException

        // Declaration of ArrayList. Add and Remove of elements is easy.

        ArrayList <Integer> myArrayList = new ArrayList <> ();

        myArrayList.add (1);

        myArrayList.add (2);

        myArrayList.add (3);

        myArrayList.add (4);

        myArrayList.add (5);

        myArrayList.remove (0);

        for (int i = 0; i <myArrayList.size (); i ++) {

        System.out.println (“Element:” + myArrayList.get (i));

        }

        // Multi-dimensional Array

        int [] [] [] multiArray = new int [3] [3] [3];

    }

}

1- Arrays have a fixed size but the size varies in ArrayLists. Because the array size is constant, memory is allocated to the array type variable at the time of its declaration and definition.

 As a result, arrays are very fast.

On the other hand, if the data size is not known, the array for more data leads to an index error outside the array size range, and the less data is wasted storage space.

2- Adding or removing elements from ArrayList is much easier than array.

3- Array can be multidimensional but ArrayList can only have one dimension.

5. When does the Finally code not run in Try?

Consider the following code snippet:

public class shutDownHooksDemo {

    public static void main (String [] args) {

        for (int i = 0; i <5; i ++)

        {

            try {

                if (i == 4) {

                    System.out.println (“Inside Try Block.Exiting without executing Finally block.”);

                    System.exit (0);

                }

            }

            finally {

                System.out.println (“Inside Finally Block.”);

            }

        }

    }

}

In the above program, it appears that “println” is executed 5 times in the finally block. But when running the program, the user notices that the finally block is called only 4 times.

In the fifth iteration, the exit function is called and finally it is never called for the fifth time.

This is because running the System.exit function stops all running threads, including the current stream. Even the finally block after try will not be executed by executing exit.

When System.exit is called, the JVM performs two cleanup tasks before stopping the program:

public class shutDownHooksDemo {

    public static void main (String [] args) {

            for (int i = 0; i <5; i ++)

            {

                    final int final_i = i;

                    try {

                            Runtime.getRuntime (). AddShutdownHook (

                                            new Thread () {

                                            public void run () {

                                            if (final_i == 4) {

                                            System.out.println (“Inside Try Block.Exiting without executing Finally block.”);

                                            System.exit (0);

                                            }

                                            }

                                            });

                    }

                    finally {

                            System.out.println (“Inside Finally Block.”);

                    }

            }

    }

}

6- Checking the individuality of a number

Take a look at the following codes and determine if they can be used to accurately identify an individual number.

public boolean oddOrNot (int num) {

    return num% 2 == 1;

}

These codes look correct but return incorrect results every four times (statistically). Consider a negative person number, the remainder divided by 2 will not be equal to 1. Therefore, the return result will be false, which is incorrect!

It can be fixed as follows:

public boolean oddOrNot (int num) {

    return (num & 1)! = 0;

}

With this code, not only has the problem of negative odd numbers been fixed, but it has been highly optimized. Because arithmetic and logic operations are much faster than division and multiplication, the results obtained in the second part are faster.

7- The difference between quotes with single quotation and double quotation

public class Haha {

    public static void main (String args []) {

    System.out.print (“H” + “a”);

    System.out.print (‘H’ + ‘a’);

    }

}

From the code written, it looks like “HaHa” is returned, but it actually returns 169 Ha. This is because if a quote with two quotation marks is used, the characters are used as a string, but if single quotation marks are used, the operands (‘H’ and ‘a’) are processed. Named “Larger Initial Data Converter” is set to integer values ​​(int). After converting an integer, the numbers are added and the value 169 is returned.

8- Prevent memory loss with simple tricks

Memory loss often disrupts software performance. Because Java automatically manages memory, developers do not have much control over it. But there are still some standard ways to prevent memory loss.

9- Prevent deadlocks in Java

Deadlocks can occur for a variety of reasons. There is no single instruction to avoid a dead end. A deadlock usually occurs when a coordinated object waits for the release of locked resources by another coordinated object.

Run the following program. This app shows a dead end. There is a stalemate here because both trades are waiting for resources taken by another trader. Both are waiting and no source is released.

public class DeadlockDemo {

   public static Object addLock = new Object ();

   public static Object subLock = new Object ();

   public static void main (String args []) {

      MyAdditionThread add = new MyAdditionThread ();

      MySubtractionThread sub = new MySubtractionThread ();

      add.start ();

      sub.start ();

   }

private static class MyAdditionThread extends Thread {

      public void run () {

         synchronized (addLock) {

        int a = 10, b = 3;

        int c = a + b;

            System.out.println (“Addition Thread:” + c);

            System.out.println (“Holding First Lock…”);

            try {Thread.sleep (10); }

            catch (InterruptedException e) {

            System.out.println (“Addition Thread: Waiting for AddLock…”);

            synchronized (subLock) {

               System.out.println (“Threads: Holding Add and Sub Locks…”);

            }

         }

      }

   }

   private static class MySubtractionThread extends Thread {

      public void run () {

         synchronized (subLock) {

        int a = 10, b = 3;

        int c = a – b;

            System.out.println (“Subtraction Thread:” + c);

            System.out.println (“Holding Second Lock…”);

            try {Thread.sleep (10); }

            catch (InterruptedException e) {

            System.out.println (“Subtraction Thread: Waiting for SubLock…”);

            synchronized (addLock) {

               System.out.println (“Threads: Holding Add and Sub Locks…”);

            }

         }

      }

   }

}

Output

=====

Addition Thread: 13

Subtraction Thread: 7

Holding First Lock…

Holding Second Lock…

Addition Thread: Waiting for AddLock…

Subtraction Thread: Waiting for SubLock…

But if the order of calling the threads changes, the deadlock problem will be solved.

public class DeadlockSolutionDemo {

   public static Object addLock = new Object ();

   public static Object subLock = new Object ();

   public static void main (String args []) {

      MyAdditionThread add = new MyAdditionThread ();

      MySubtractionThread sub = new MySubtractionThread ();

      add.start ();

      sub.start ();

   }

private static class MyAdditionThread extends Thread {

      public void run () {

         synchronized (addLock) {

        int a = 10, b = 3;

        int c = a + b;

            System.out.println (“Addition Thread:” + c);

            System.out.println (“Holding First Lock…”);

            try {Thread.sleep (10); }

            catch (InterruptedException e) {

            System.out.println (“Addition Thread: Waiting for AddLock…”);

            synchronized (subLock) {

               System.out.println (“Threads: Holding Add and Sub Locks…”);

            }

         }

      }

   }

   private static class MySubtractionThread extends Thread {

      public void run () {

         synchronized (addLock) {

        int a = 10, b = 3;

        int c = a – b;

            System.out.println (“Subtraction Thread:” + c);

            System.out.println (“Holding Second Lock…”);

            try {Thread.sleep (10); }

            catch (InterruptedException e) {

            System.out.println (“Subtraction Thread: Waiting for SubLock…”);

            synchronized (subLock) {

               System.out.println (“Threads: Holding Add and Sub Locks…”);

            }

         }

      }

   }

}

Output

=====

Addition Thread: 13

Holding First Lock…

Addition Thread: Waiting for AddLock…

Threads: Holding Add and Sub Locks…

Subtraction Thread: 7

Holding Second Lock…

Subtraction Thread: Waiting for SubLock…

Threads: Holding Add and Sub Locks…

10. Reserve memory for Java.

Some Java programs may require a lot of CPU as well as a lot of RAM. Such programs are usually slow due to the need for RAM. RAM can be reserved for Java to improve the performance of such applications. For example, if we have a Tomcat web server and its RAM is 10 GB. If you wish, we can use the following command to allocate RAM for Java on this device:

export JAVA_OPTS = ”$ JAVA_OPTS -Xms5000m -Xmx6000m -XX: PermSize = 1024m -XX: MaxPermSize = 2048m”

11- How to work with time in Java

There are two standard ways to work with time in Java: System.currentTimeMillis () and System.nanoTime ().

The question is which of the two to choose and under what conditions. In principle, both perform the same operations but differ in the following ways:

System.currentTimeMillis is somewhere between 1,000th to 15,000th (system dependent), but System.nanoTime takes approximately 1,000,000ths of a second (1,000 nanoseconds).

2. System.currentTimeMillis has fewer clock cycles for reading operations. System.nanoTime, on the other hand, has more than 100 clock cycles.

3. System.currentTimeMillis indicates absolute time (milliseconds since 00:00 (January 1, 1970) (Epoch time)) but System.nanoTime does not necessarily indicate any starting point.

12. Choose between Float and Double

Decimal digits Used bytes data type
7 4 Float
۱۵ 8 Double

Double is often preferred to float in software.

Most processors have about the same amount of processing time to operate on Float and Double. Double offers much greater accuracy at the same time.

13. Power calculation

To calculate power (^), Java performs a dedicated OR or XOR. To calculate power, Java offers two options:

1- Multiplication:

double square = double a * double a; // Optimized

double cube = double a * double a * double a; // Non-optimized

double cube = double a * double square; // Optimized

double quad = double a * double a * double a * double a; // Non-optimized

double quad = double square * double square; // Optimized

2- (power, base) pow: from the ‘pow’ method to calculate power where multiplication is not possible, (power ^ base);

double cube = Math.pow (base, exponent);

Math.pow should only be used if necessary. For example, power is a fractional value. This is because the Math.pow method is usually about 300 to 600 times slower than multiplication.

14. How to manage the Null exception

Null pointer exceptions are quite common in Java. This exception occurs when we want to call a method by referencing the Null object. For example, the,

int noOfStudents = school.listStudents (). count;

If you received a NullPointerException in the example above, then either school or listStudents () is null. It is a good idea to check Null options as soon as possible to remove them.

private int getListOfStudents (File [] files) {

      if (files == null)

        throw new NullPointerException (“File list cannot be null”);

    }

15. Encryption in JSON

JSON stands for JavaScript Object Notation, a structure for storing and exchanging data. JSON is an easier-to-use alternative to XML. Json has become very popular on the Internet these days due to its features and low volume. A normal data structure can be encrypted in JSON and easily shared on web pages. A JSON parser must be installed before you can start writing code. In the following examples we have used json.simple.

(https://code.google.com/p/json-simple/)

The following is a simple example of JSON encryption:

import org.json.simple.JSONObject;

import org.json.simple.JSONArray;

public class JsonEncodeDemo {

    public static void main (String [] args) {

        JSONObject obj = new JSONObject ();

        obj.put (“Novel Name”, “Godaan”);

        obj.put (“Author”, “Munshi Premchand”);

        JSONArray novelDetails = new JSONArray ();

        novelDetails.add (“Language: Hindi”);

        novelDetails.add (“Year of Publication: 1936”);

        novelDetails.add (“Publisher: Lokmanya Press”);

        obj.put (“Novel Details”, novelDetails);

        System.out.print (obj);

    }

}

Output

Nove “Novel Name”: “Godaan”, “Novel Details”: [“Language: Hindi”, “Year of Publication: 1936 ″,” Publisher: Lokmanya Press “],” Author “:” Munshi Premchand “}

16- Simple string search

Java suggests a library method called indexOf (). This method is used with a string object and returns the index position of the desired string. If the string is not found, the value 1- is returned.

public class StringSearch {

    public static void main (String [] args) {

        String myString = “I am a String!”;

        if (myString.indexOf (“String”) == -1) {

            System.out.println (“String not Found!”);

        }

        else {

            System.out.println (“String found at:” + myString.indexOf (“String”));

        }

    }

}

17. List contents of a directory

In order to list the contents of a list, the following program can be used. The program simply receives the names of all the subdirectories and files of a folder in an array, and then that array is followed sequentially to list all the contents.

import java.io. *;

public class ListContents {

    public static void main (String [] args) {

        File file = new File (“// home // user // Documents /”);

        String [] files = file.list ();

        System.out.println (“Listing contents of” + file.getPath ());

        for (int i = 0; i <files.length; i ++)

        {

            System.out.println (files [i]);

        }

    }

}

18. Simple input and output

In order to read from file and write to file, Java offers the FileInputStream and FileOutputStream classes. The FileInputStream constructor accepts the input file path as an argument and creates the file input stream. Similarly, the FileOutputStream constructor accepts the output file path as an argument and creates the output file stream. It is important to “close” the streams after working with the file.

import java.io. *;

public class myIODemo {

    public static void main (String args []) throws IOException {

        FileInputStream in = null;

        FileOutputStream out = null;

        try {

            in = new FileInputStream (“// home // user // Documents // InputFile.txt”);

            out = new FileOutputStream (“// home // user // Documents // OutputFile.txt”);

            int c;

            while ((c = in.read ())! = -1) {

                out.write (c);

            }

        } finally {

            if (in! = null) {

                in.close ();

            }

            if (out! = null) {

                out.close ();

            }

        }

    }

}

19. Execute the shell command from Java

Java provides the Runtime class for executing Shell commands. Because these are external commands, exception handling is very important. In the following example we show this with a simple example. Here we are trying to open a PDF file with the Shell command.

import java.io.BufferedReader;

import java.io.InputStream;

import java.io.InputStreamReader;

public class ShellCommandExec {

    public static void main (String [] args) {

        String gnomeOpenCommand = “gnome-open //home//user//Documents//MyDoc.pdf”;

        try {

            Runtime rt = Runtime.getRuntime ();

            Process processObj = rt.exec (gnomeOpenCommand);

            InputStream stdin = processObj.getErrorStream ();

            InputStreamReader isr = new InputStreamReader (stdin);

            BufferedReader br = new BufferedReader (isr);

            String myoutput = “”;

            while ((myoutput = br.readLine ())! = null) {

                myoutput = myoutput + ”\ n”;

            }

            System.out.println (myoutput);

        }

        catch (Exception e) {

            e.printStackTrace ();

        }

    }

}

20. Use regular and regular expressions

Summary of Regular Phrase Structures (Source: Oracle Website)

character
Character x

X

Back Slash Character

\\

A character with an octal value or a base of eight 0n (0 <= n <= 7)

\ ۰n

Character with octal value or base of eight 0nn (0 <= n <= 7)

\ 0nn

Character with octal value or base of eight 0mnn (0 <= m <= 3, 0 <= n <= 7)

\ 0mnn

A character with a hexadecimal value or a base of sixteen 0xh

\ xhh

Character with hexadecimal value or base sixteen 0xhhhh

\ uhhhh

Character with hexadecimal value or base sixteen 0xh h(Character.MIN_CODE_POINT <= 0xh… h <= Character.MAX_CODE_POINT)

\ x {h… h}

Tab character (‘\ u0009’)

\ t

New Line Character – Line Swap (‘\ u000A’)

\ n

Return transport character (‘\ u000D’)

\ r

 Form feed character (‘\ u000C’)

\ f

Alarm character (alarm) (‘\ u0007’)

\ a

Skip character (‘\ u001B’)

\ e

Control character related to x

\ cx

 

Character classes
a, b or c (simple class)

[abc]

All characters except a, b or c (contradictory)

[^ abc]

a to z or A to Z, including (range)

[a-zA-Z]

a to d or m to: p [a-dm-p] (community)

[ad [mp]]

d, e or f (subscription)

[az && [def]]

A to z except b and: c [ad-z] (subtraction)

[az && [^ bc]]

a to z and not m to p: [a-lq-z] (subtraction)

[az && [^ mp]]

 

Character classes defined
Each character (may or may not match the endpoint of the line) .
One digit: [9-0]

\ d

Non-numeric character: [9-0%]

\ D

An empty space character: [\ t \ n \ x0B \ f \ r]

\ s

No empty space characters: [S \ ^]

\ S

A word character: [a-zA-Z_0-9]

\ w

A non-verbal character: [w \ ^]

\ W

 

Boundary adapters
The beginning of a line

^

End of a line

$

Word border

\ b

Non-word border

\ B

Start input

\ A

End of previous matching

\ G

Input end but if there is a last end point

\ Z

End of input

\ z

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class RegexMatches

{

    private static String pattern = “^ [_ A-Za-z0-9 -] + (\\. [_ A-Za-z0-9 -] +) * @ [A-Za-z0-9] + (\\. [A-Za-z0-9] +) * (\\. [A-Za-z] {2,}) $ ”;

    private static Pattern mypattern = Pattern.compile (pattern);

    public static void main (String args []) {

        String valEmail1 = “testemail@domain.com”;

        String invalEmail1 = “@. @ Domain.com”;

        String invalEmail2 = “. $$ %% @ domain.com”;

        String valEmail2 = “test.email@domain.com”;

        System.out.println (“Is Email ID1 valid?” + ValidateEMailID (valEmail1));

        System.out.println (“Is Email ID1 valid?” + ValidateEMailID (invalEmail1));

        System.out.println (“Is Email ID1 valid?” + ValidateEMailID (invalEmail2));

        System.out.println (“Is Email ID1 valid?” + ValidateEMailID (valEmail2));

    }

    public static boolean validateEMailID (String emailID) {

        Matcher mtch = mypattern.matcher (emailID);

        if (mtch.matches ()) {

            return true;

        }

        return false;

    }

}

22. Get output in PDF format

Exporting a spreadsheet to PDF is a common demand in Java applications. Using itextpdf makes it very easy to get PDF output.

import java.io.FileOutputStream;

import com.itextpdf.text.Document;

import com.itextpdf.text.Paragraph;

import com.itextpdf.text.pdf.PdfPCell;

import com.itextpdf.text.pdf.PdfPTable;

import com.itextpdf.text.pdf.PdfWriter;

public class DrawPdf {

      public static void main (String [] args) throws Exception {

        Document document = new Document ();

        PdfWriter.getInstance (document, new FileOutputStream (“Employee.pdf”));

        document.open ();

        Paragraph para = new Paragraph (“Employee Table”);

        para.setSpacingAfter (20);

        document.add (para);

        PdfPTable table = new PdfPTable (3);

        PdfPCell cell = new PdfPCell (new Paragraph (“First Name”));

        table.addCell (cell);

        table.addCell (“Last Name”);

        table.addCell (“Gender”);

        table.addCell (“Ram”);

        table.addCell (“Kumar”);

        table.addCell (“Male”);

        table.addCell (“Lakshmi”);

        table.addCell (“Devi”);

        table.addCell (“Female”);

        document.add (table);

        document.close ();

      }

    }

23. Measuring time

Many applications require very accurate time measurements. For this purpose, Java provides static methods in the System class:

1- currentTimeMillis (): Returns the current time to milliseconds of the Epoch time as long as the data.

1. long startTime = System.currentTimeMillis ();

2 ٫ long estimatedTime = System.currentTimeMillis () – startTime;

2- nanoTime (): Converts the current value of the most accurate timer in the system to nanoseconds as long as the data. In contrast to providing absolute timing, nanoTime is for measuring relative time intervals.

1. long startTime = System.nanoTime ();

2 estimated long estimatedTime = System.nanoTime () – startTime;

24. Resize the image

An image can be resized using AffineTransform. First of all, the image buffer is created from the input image and then the image is presented by resizing.

import java.awt.Graphics2D;

import java.awt.geom.AffineTransform;

import java.awt.image.BufferedImage;

import java.io.File;

import javax.imageio.ImageIO;

public class RescaleImage {

  public static void main (String [] args) throws Exception {

    BufferedImage imgSource = ImageIO.read (new File (“images // Image3.jpg”));

    BufferedImage imgDestination = new BufferedImage (100, 100, BufferedImage.TYPE_INT_RGB);

    Graphics2D g = imgDestination.createGraphics ();

    AffineTransform affinetransformation = AffineTransform.getScaleInstance (2, 2);

    g.drawRenderedImage (imgSource, affinetransformation);

    ImageIO.write (imgDestination, “JPG”, new File (“outImage.jpg”));

  }

}

25. Get the floating coordinates of the mouse

You can record mouse events by implementing the MouseMotionListner interface. When the mouse enters a specific area, the MouseMoving event starts and the movement coordinates can be recorded. The following example illustrates this:

import java.awt.event. *;

import javax.swing. *;

public class MouseCaptureDemo extends JFrame implements MouseMotionListener

{

    public JLabel mouseHoverStatus;

    public static void main (String args [])

    {

        new MouseCaptureDemo ();

    }

    MouseCaptureDemo ()

    {

        setSize (500, 500);

        setTitle (“Frame displaying Coordinates of Mouse Motion”);

        mouseHoverStatus = new JLabel (“No Mouse Hover Detected.”, JLabel.CENTER);

        add (mouseHoverStatus);

        addMouseMotionListener (this);

        setVisible (true);

    }

    public void mouseMoved (MouseEvent e)

    {

        mouseHoverStatus.setText (“Mouse Cursor Coordinates => X:” + e.getX () + ”| Y:” + e.getY ());

    }

    public void mouseDragged (MouseEvent e)

    }

}

26. FileOutputStream vs. FileWriter

Writing to a file in Java is often done in two ways: FileOutputStream and FileWriter. Sometimes, developers are challenged to choose one. This example helps them to choose each one under the required conditions. Let’s take a look at the performance:

Use: FileOutputStream

File foutput = new File (file_location_string);

FileOutputStream fos = new FileOutputStream (foutput);

BufferedWriter output = new BufferedWriter (new OutputStreamWriter (fos));

output.write (“Buffered Content”);

Use: FileWriter

FileWriter fstream = new FileWriter (file_location_string);

BufferedWriter output = new BufferedWriter (fstream);

output.write (“Buffered Content”);

According to Java API specifications:

FileOutputStream is for writing raw byte streams like image data. Use FileWriter to write character streams.

It is quite clear that FileOutputStream should be used for image data type and FileWriter for text data type.

More suggestions

1. Use Collections.

Java comes with a number of set classes – for example: vector, stack, hash table, array. Developers are advised to use collections as much as possible for the following reasons:

1- Using the set makes the code reusable and changeable.

2- Collections make the code more structured and easier to understand and maintain.

3- The set classes are well tested from different aspects, so the code quality is good.

2- Law 500-50-10

In large software packages, code retention becomes very challenging. Newcomer developers added during support projects often complain about this: integrated code, spaghetti code. To avoid this problem or to keep the code clean, there is a very simple rule: 500-50-10٫.

3- SOLID class design principles

SOLID is based on design principles developed by Robert Martin. According to this law:

Description Law
A class should have one and only one task or responsibility. If the class does more than one task, it can lead to confusion. Single responsibility principle(Principle of unit responsibility)
Developers need to focus more on expanding software institutions rather than changing them. Open / closed principle(Open / closed principle)
The derived class can be replaced with the base class. Liskov substitution principle(Principle of Liskov replacement)
It is the same as the principle of unit responsibility but runs for interfaces. Each interface must be responsible for a specific task. Developers need to implement methods that they do not need. Interface segregation principle(Interface separation principle)
It depends on the abstraction – but it does not depend on the link. This means that the modules must be separated from each other using the abstract layer that connects them. Dependency inversion principle(Principle of dependence inversion)

4- Using design patterns

Design templates help developers incorporate the best software design principles into their software. They also provide a common platform for developers around the world. They provide standard terms that facilitate collaboration and communication between developers.

5- Documentation ideas

Don’t just start writing code. Strategy, preparation, document, review and implementation. Write down your needs first. Provide a design document. Mention the hypotheses correctly. Examine the documents carefully and verify and complete them.

6- Using two equals ==

The == operator also compares the sources of objects. Checks if two operands point to the same object (not exactly the equivalent of the same object). On the other hand, it makes a real comparison between the two disciplines.

7- Avoid decimal numbers with two decimal places

Decimal numbers with two decimal places should only be used if necessary. For example, the use of decimal numbers in currencies can be problematic – the BigDecimal data type should be preferred instead. Decimal numbers with two decimal places are more useful in measurements.

Exit mobile version