Website-Icon DED9

30 Tips On Java Programming And Best Practices For Beginners

Java is one of the most popular programming languages. It is used in Windows applications, web applications, mobile applications, networks, Consumer electronics, and configuration box devices, and 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 the most popular Development platform.

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

1. Use empty return sets instead of Null.

If the program returns a set with no value, ensure the empty set is returned instead of the Null elements. This causes many “if-else” statements 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. AlRuntimen is making a prototype of a String object; you should avoid the manufacturer and make it 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.

Object Creation is one of Java’s most expensive operations (in terms of memory usage). 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 strengths and weaknesses, and the choice 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 its declaration and definition.

As a result, arrays are high-speed.

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

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

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

5. When does the finally code not run, TryTry?

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 five times in the finally block. However, when running the program, the user notices that the finally block is called only four times.

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

This is because running the System. The exit function stops all running threads, including the current stream. Executing the exit will not perform the finally block after the Try.

W Try System. Exit Trycalled, 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

Please review the following codes and determine if they can 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 equal 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;

}

This highly optimized code fixes the problem of negative odd numbers. Because arithmetic and logic operations are much faster than division and multiplication, the results obtained in the second part are more rapid.

7- The difference between single quotation marks and double quotation marks

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 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. The “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. However, 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 another coordinated object to release locked resources.

Run the following program. This app shows a dead end. There is a stalemate here because both traders are waiting for resources taken by the other 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 and RAM. Because of this, they are usually slow. 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,000ths and 15,000ths (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. The nanotime System, the other System, has over 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 the same 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 pretty standard 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 school or listStudents () is null. It is a good idea to check the 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. It is an easier-to-use alternative to XML. Due to its features and low volume, JSON has become very popular on the Internet these days.
A typical 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.

(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 one 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 the contents of a directory

The following program can be used to list the contents of a list. The program receives the names of all the subdirectories and files of a folder in an array, which is then 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

Java offers the FileInputStream and FileOutputStream classes for reading from and writing to files. The FileInputStream constructor accepts the input File path as an argument and creates the File input stream. Similarly, the FileOutputStream constructor agrees with the output File path as an argument and creates the output File stream. After working with the File, it is essential to “close” the streams.

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 critical. 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 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 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 requirement in Java applications. Using iTextPDF makes it easy to obtain 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 time in milliseconds of the Epoch time as a long.

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 measures 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, the image buffer is created from the input image, and then the image is resized.

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 MouseMotionListener 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 select 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.

FileOutputStream should be used for image data type, and FileWriter for text data type.

More suggestions

1. Use Collections.

Java has several built-in classes, such as vector, stack, hash table, and 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

Code retention becomes very challenging in large software packages. Newcomer developers added during support projects often complain about integrated or spaghetti code. To avoid this problem or to keep the code clean, there is a straightforward 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 it applies to 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 abstration,t it does not rely 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 worldwide and 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. Scrub the documents, 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, using 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.

Die mobile Version verlassen