Summary of java development novice problems
Java is one of the most popular programming languages & mdash& mdash; It can be used to write windows programs or web applications, mobile applications, network programs, consumer electronics, set-top box devices. It is everywhere.
More than 3 billion devices are running on Java. According to Oracle statistics, there are 5 billion Java cards in use alone.
More than 9 million programmers choose to use Java for development. It is not only the most popular language for developers, but also the most popular development platform.
This article has prepared a series of widely circulated Java best programming practices for prospective Java programmers:
Returns an empty collection first rather than null
If the program is going to return a collection that does not contain any values, make sure to return an empty collection instead of null. This saves a lot of "if else" checking.
public class getLocationName { return (null==cityName ? "": cityName); }
Caution strings
If two strings are spliced using the + operator in a for loop, a new string object will be generated each time. This not only wastes memory space, but also affects performance. Similarly, if initializing a string object, try not to use a constructor, but should initialize it directly. For example:
//Slower Instantiation String bad = new String("Yet another string object"); //Faster Instantiation String good = "Yet another string object"
Avoid useless objects
Creating objects is one of the most expensive operations in Java. Therefore, it is best to create / initialize objects when necessary. As follows:
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; } }
Array versus ArrayList
Developers often find it difficult to choose between arrays and ArrayLists. They both have advantages and disadvantages. How to choose should depend on the situation.
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]; } }
Look at the following code:
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."); } } } }
From the code point of view, it seems that the println statement in the finally block should be executed five times. But when the program runs, you will find that the finally block is executed only four times. The fifth iteration will trigger the call of exit function, so the fifth finally will never be triggered. The reason is & mdash& mdash; System. Exit suspends the execution of all threads, including the current thread. Even the finally block after the try statement cannot be returned as long as exit is executed.
Calling system When exit, the JVM performs two end tasks before closing:
First of all, it will complete all the execution through the runtime Addshutdownhook registers the terminated hook program. This is critical because it frees up resources outside the JVM.
The next step is finalizer. It could be system Runfinalizesonexit may also be runtime runFinalizersOnExit。 The use of finalizer has been abandoned for a long time. Finalizer can be called on living objects, even if they are still being used by other threads. This can lead to unexpected results or even deadlock.
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."); } } } }
Judge odd numbers
Look at these lines of code to see if they can be used to accurately determine whether a number is odd?
public boolean oddOrNot(int num) { return num % 2 == 1; }
It seems to be right, but there will be an error result every four execution (speaking in data). Considering the case of negative odd number, the result of dividing it by 2 will not be 1. Therefore, the return value is false, which is wrong.
The code can be modified as follows:
public boolean oddOrNot(int num) { return (num & 1) != 0; }
This is not only the problem of negative odd numbers has been solved, but also fully optimized. Because arithmetic and logic operations are more efficient than multiplication and division, the calculation results will be faster.
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'); } }
It looks like this code will return "haha", but it actually returns ha169. The reason is that when double quotation marks are used, characters will be treated as strings, while if single quotation marks are used, character values will be converted into integer values through an operation called base type widening. Then add the values to get 169.
Some tips to prevent memory leakage
Memory leaks can degrade software performance. Because Java manages memory automatically, there are not many ways for developers to intervene. However, there are some ways to prevent memory leaks.
There are many reasons for deadlock. Avoiding deadlocks can't be solved in one sentence. Generally speaking, a deadlock occurs when a synchronization object is waiting for a lock on a resource owned by another synchronization object.
Try running the following program. It will tell you what a deadlock is. This deadlock occurs because both threads are waiting for resources owned by each other. They will wait and no one will let go first.
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...
However, if the order of calls is changed, the deadlock problem is 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...
Save some memory for Java
Some Java programs are CPU intensive, but they require a lot of memory. Such programs usually run slowly because they require a lot of memory. In order to improve the performance of these applications, you have to leave more memory for them. Therefore, suppose we have a Tomcat server with 10g memory. On this machine, we can allocate memory with the following command:
export JAVA_OPTS="$JAVA_OPTS -Xms5000m -Xmx6000m -XX:PermSize=1024m -XX:MaxPermSize=2048m"
There are two standard methods for timing operations in Java: system Currenttimemillis() and system nanoTime()。 The question is, under what circumstances, which one to use. In essence, their functions are the same, but there are the following differences:
In scenarios with high precision requirements, double type is more popular than float for the following reasons:
Most processors take about the same amount of time to process float and double. On the premise of the same calculation time, the double type can provide higher accuracy.
Power operation
Java performs power operation through XOR operation. Java has two processing methods for power operation:
Product:
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
POW method: the pow method can be used when the product cannot be used.
double cube = Math.pow(base, exponent);
Don't use math until you have to pow。 For example, when the exponent is a decimal. Because of math POW is about 300-600 times slower than the product.
How to handle null pointer exceptions
Null pointer exception is a very common exception in Java. This exception is thrown when you try to call a method on a null object. For example:
int noOfStudents = school.listStudents().count;
In the above example, null pointerexception may be thrown if school is empty or liststudents() is empty. Therefore, it is best to check whether the object is empty to avoid similar situations.
private int getListOfStudents(File[] files) { if (files == null) throw new NullPointerException("File list cannot be null"); }
JSON encoding
JSON is a protocol for data storage and transmission. It is easier to use than XML. Because of its very lightweight and some of its own characteristics, JSON is becoming more and more popular on the network. Common data structures can be encoded into JSON and then transmitted freely among various web pages. But before you start coding, you have to install a JSON parser. In the following example, we will use JSON Simple library to do this( https://code.google.com/p/json-simple/ )。
The following is a simple example of encoding into a JSON string.
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:
{"Novel Name":"Godaan","Novel Details":["Language: Hindi","Year of Publication: 1936","Publisher: Lokmanya Press"],"Author":"Munshi Premchand"}
JSON parsing
If a developer wants to parse a JSON string, first you have to know its format. The following examples will help you understand this:
import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class JsonParseTest { private static final String filePath = "//home//user//Documents//jsonDemoFile.json"; public static void main(String[] args) { try { // read the json file FileReader reader = new FileReader(filePath); JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject)jsonParser.parse(reader); // get a number from the JSON object Long id = (Long) jsonObject.get("id"); System.out.println("The id is: " + id); // get a String from the JSON object String type = (String) jsonObject.get("type"); System.out.println("The type is: " + type); // get a String from the JSON object String name = (String) jsonObject.get("name"); System.out.println("The name is: " + name); // get a number from the JSON object Double ppu = (Double) jsonObject.get("ppu"); System.out.println("The PPU is: " + ppu); // get an array from the JSON object System.out.println("Batters:"); JSONArray batterArray= (JSONArray) jsonObject.get("batters"); Iterator i = batterArray.iterator(); // take each value from the json array separately while (i.hasNext()) { JSONObject innerObj = (JSONObject) i.next(); System.out.println("ID "+ innerObj.get("id") + " type " + innerObj.get("type")); } // get an array from the JSON object System.out.println("Topping:"); JSONArray toppingArray= (JSONArray) jsonObject.get("topping"); Iterator j = toppingArray.iterator(); // take each value from the json array separately while (j.hasNext()) { JSONObject innerObj = (JSONObject) j.next(); System.out.println("ID "+ innerObj.get("id") + " type " + innerObj.get("type")); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } catch (ParseException ex) { ex.printStackTrace(); } catch (NullPointerException ex) { ex.printStackTrace(); } } }
jsonDemoFile. json
{ "id": 0001, "type": "donut", "name": "Cake", "ppu": 0.55, "batters": [ { "id": 1001, "type": "Regular" }, { "id": 1002, "type": "Chocolate" }, { "id": 1003, "type": "BlueBerry" }, { "id": 1004, "type": "Devil's Food" } ], "topping": [ { "id": 5001, "type": "None" }, { "id": 5002, "type": "Glazed" }, { "id": 5005, "type": "Sugar" }, { "id": 5007, "type": "Powdered Sugar" }, { "id": 5006, "type": "Chocolate with Sprinkles" }, { "id": 5003, { "id": 5004, "type": "Maple" } ] }
The id is: 1 The type is: donut The name is: Cake The PPU is: 0.55 Batters: ID 1001 type Regular ID 1002 type Chocolate ID 1003 type BlueBerry ID 1004 type Devil's Food Topping: ID 5001 type None ID 5002 type Glazed ID 5005 type Sugar ID 5007 type Powdered Sugar ID 5006 type Chocolate with Sprinkles ID 5003 type Chocolate ID 5004 type Maple
Simple string lookup
Java provides a library function called indexof (). This method can be used on a string object. It returns the sequence number of the position of the string to be searched. If not found, - 1 is returned.
List the files in the directory
You can use the following code to list the files in the directory. This program will traverse all subdirectories and files in a directory, store them in an array, and then list all files by traversing the array.
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]); } } }
A simple IO program
Java provides FileInputStream and fileoutputstream classes to read and write files. The construction method of FileInputStream will receive the path of the input file as the input parameter, and then create an input stream of the file. Similarly, the construction method of fileoutputstream will also receive a file path as an input parameter, and then create the output stream of the file. After processing the file, a very important operation is to remember to "close" these 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(); } } } }
Execute a shell command in Java
Java provides runtime classes to execute shell commands. Because these are external commands, exception handling is very important. In the following example, we will demonstrate it with a simple example. We will open a PDF file on the shell command line.
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(); } } }
Use regular
The structure of regular expressions is excerpted as follows (source: Oracle official website)
Character
Character classification
Predefined characters
Boundary matching
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; } }
A simple example of Java Swing
With Java swing, you can write GUI applications. The javax package provided by java contains swing. To write GUI programs using swing, you first need to inherit the JFrame. Then add @ r in it_ 671_ 2419 @, and then you can add controls such as buttons, multi-choice buttons, text boxes and so on. These @ r_ 671_ 2419 @ is placed on the outermost layer of the container.
import java.awt.*; import javax.swing.*; public class SwingsDemo extends JFrame { public SwingsDemo() { String path = "//home//user//Documents//images"; Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); @R_671_2419@ myHorizontal@R_671_2419@ = @R_671_2419@. createHorizontal@R_671_2419@(); @R_671_2419@ myVerticle@R_671_2419@ = @R_671_2419@. createVertical@R_671_2419@(); myHorizontal@R_671_2419@.add(new JButton("My Button 1")); myHorizontal@R_671_2419@.add(new JButton("My Button 2")); myHorizontal@R_671_2419@.add(new JButton("My Button 3")); myVerticle@R_671_2419@.add(new JButton(new ImageIcon(path + "//Image1.jpg"))); myVerticle@R_671_2419@.add(new JButton(new ImageIcon(path + "//Image2.jpg"))); myVerticle@R_671_2419@.add(new JButton(new ImageIcon(path + "//Image3.jpg"))); contentPane.add(myHorizontal@R_671_2419@); contentPane.add(myVerticle@R_671_2419@); pack(); setVisible(true); } public static void main(String args[]) { new SwingsDemo(); } }
Play audio using java
In Java, playing audio is a very common requirement, especially in game development.
The demo below demonstrates how to play audio in Java.
import java.io.*; import java.net.URL; import javax.sound.sampled.*; import javax.swing.*; // To play sound using Clip, the process need to be alive. // Hence, we use a Swing application. public class playSoundDemo extends JFrame { // Constructor public playSoundDemo() { this.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE); this.setTitle("Play Sound Demo"); this.setSize(300, 200); this.setVisible(true); try { URL url = this.getClass().getResource("MyAudio.wav"); AudioInputStream audioIn = AudioSystem.getAudioInputStream(url); Clip clip = AudioSystem.getClip(); clip.open(audioIn); clip.start(); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (LineUnavailableException e) { e.printStackTrace(); } } public static void main(String[] args) { new playSoundDemo(); } }
Export PDF file
Exporting tables to PDF is also a common requirement. It is not difficult to export PDF through itextpdf.
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(); } }
Mail sending
Sending mail in Java is also simple. You just need to install the java mail jar package and put it in your classpath. In the following code, we set several basic properties, and then we can send mail:
import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class SendEmail { public static void main(String [] args) { String to = "recipient@gmail.com"; String from = "sender@gmail.com"; String host = "localhost"; Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); Session session = Session.getDefaultInstance(properties); try{ MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO,new InternetAddress(to)); message.setSubject("My Email Subject"); message.setText("My Message Body"); Transport.send(message); System.out.println("Sent successfully!"); } catch (MessagingException ex) { ex.printStackTrace(); } } }
Calculation time
Many programs require accurate time measurement. Java provides a system static method to support this function:
Currenttimemillis(): returns the millisecond value of the current time since the new era, of type long.
long startTime = System.currentTimeMillis(); long estimatedTime = System.currentTimeMillis() - startTime;
Nanotime(): returns the current precise time of the system timer, nanosecond value, which is also of type long. Nanotime () is mainly used to calculate relative time rather than absolute time.
long startTime = System.nanoTime(); long estimatedTime = System.nanoTime() - startTime;
Picture zoom
Image scaling can be done through affinetransform. First, we need to generate a picture buffer for the input picture, and then use it to render the scaled picture.
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")); } }
Capture mouse action
After implementing the mousemotionlistner interface, you can capture mouse events. When the mouse enters a specific area, the mousemoved event will be triggered, and you can capture the moving action. As an example:
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) {} }
FileOutputStream Vs. FileWriter
There are two ways to write files in Java: fileoutputstream and filewriter. Developers often hesitate between them. The following example can help you better understand which scheme to choose in different scenarios. First, let's look at the implementation:
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");
Using filewriter:
FileWriter fstream = new FileWriter(file_location_string); BufferedWriter output = new BufferedWriter(fstream); output.write("Buffered Content");
According to java interface specification:
Fileoutputstream is used to write original byte stream, such as picture stream data. If you are writing to a character stream, you should consider using filewriter.
This makes it clear that you should use fileoutputstream to write pictures and filewriter to write text.
Additional recommendations
Use of collections
Java provides many collection classes & mdash& mdash; For example, vector, stack, hashtable, etc. Therefore, developers are encouraged to use these collection classes as much as possible for the following reasons:
1-50-500 rule
In large software systems, code maintainability is a very challenging work. New developers often complain about these situations: monolithic code and spaghetti code, which are often used to describe classes and methods that are tied together and have low cohesion. There is a very simple rule to keep the code clean and maintainable:
Use of design patterns
Design patterns can help developers better apply software design criteria in software. It also provides developers with a common cross language platform. Standard terminology in design patterns makes it easier for developers to communicate.
About documents
Don't come up and start writing code. Plan, prepare, document, check, and then implement. First, write down the requirements. Then prepare the design documents. Make reasonable assumptions and provide evidence. Review the scheme with each other and confirm it.
Use equals instead of==
= = is used to compare object references. It checks whether the two operands point to the same object (not the same object, but the same object). While "equals" compares whether the two strings are the same (assuming a string object).
Avoid floating point numbers
Floating point numbers are used only when necessary. For example, using floating-point numbers to represent rupees or pies can easily cause problems & mdash& mdash; BigDecimal should be used in this case. Floating point numbers are more used for measurement.