public class HelloWorld
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
    }
}

 

이 코드를 실행하면 뭐가 나올까?

 

Console 창에 Hello World! 라고 나온다.

 

혹시 Hello World!를 보고 나도 모르게 웃음이 나온 기억이 있다면, 혹은 지금 그랬다면

 

당신은 좋은 개발자가 될 것이다.

1. Prefer returning Empty Collections instead of Null

If a program is returning a collection which does not have any value, make sure an Empty collection is returned rather than Null elements. This saves a lot of “if else” testing on Null Elements.

1public class getLocationName {
2    return (null==cityName ? "": cityName);
3}

2. Use Strings carefully

If two Strings are concatenated using “+” operator in a “for” loop, then it creates a new String Object, every time. This causes wastage of memory and increases performance time. Also, while instantiating a String Object, constructors should be avoided and instantiation should happen directly. For example:

1//Slower Instantiation
2String bad = new String("Yet another string object");
3      
4//Faster Instantiation
5String good = "Yet another string object"

3. Avoid unnecessary Objects

One of the most expensive operations (in terms of Memory Utilization) in Java is Object Creation. Thus it is recommended that Objects should only be created or initialized if necessary. Following code gives an example:

01import java.util.ArrayList;
02import java.util.List;
03 
04public class Employees {
05 
06    private List Employees;
07 
08    public List getEmployees() {
09 
10        //initialize only when required
11        if(null == Employees) {
12            Employees = new ArrayList();
13        }
14        return Employees;
15    }
16}

4. Dilemma between Array and ArrayList

Developers often find it difficult to decide if they should go for Array type data structure of ArrayList type. They both have their strengths and weaknesses. The choice really depends on the requirements.

01import java.util.ArrayList;
02 
03public class arrayVsArrayList {
04 
05    public static void main(String[] args) {
06        int[] myArray = new int[6];
07        myArray[7]= 10// ArraysOutOfBoundException
08 
09        //Declaration of ArrayList. Add and Remove of elements is easy.
10        ArrayList<Integer> myArrayList = new ArrayList<>();
11        myArrayList.add(1);
12        myArrayList.add(2);
13        myArrayList.add(3);
14        myArrayList.add(4);
15        myArrayList.add(5);
16        myArrayList.remove(0);
17         
18        for(int i = 0; i < myArrayList.size(); i++) {
19        System.out.println("Element: " + myArrayList.get(i));
20        }
21         
22        //Multi-dimensional Array
23        int[][][] multiArray = new int [3][3][3];
24    }
25}
  1. Arrays have fixed size but ArrayLists have variable sizes. Since the size of Array is fixed, the memory gets allocated at the time of declaration of Array type variable. Hence, Arrays are very fast. On the other hand, if we are not aware of the size of the data, then ArrayList is More data will lead to ArrayOutOfBoundException and less data will cause wastage of storage space.
  2. It is much easier to Add or Remove elements from ArrayList than Array
  3. Array can be multi-dimensional but ArrayList can be only one dimension.

5. When Finally does not get executed with Try

Consider following code snippet:

01public class shutDownHooksDemo {
02    public static void main(String[] args) {
03        for(int i=0;i<5;i++)
04        {
05            try {
06                if(i==4) {
07                    System.out.println("Inside Try Block.Exiting without executing Finally block.");
08                    System.exit(0);
09                }
10            }
11            finally {
12                System.out.println("Inside Finally Block.");
13            }
14        }
15    }
16}

From the program, it looks like “println” inside finally block will be executed 5 times. But if the program is executed, the user will find that finally block is called only 4 times. In the fifth iteration, exit function is called and finally never gets called the fifth time. The reason is- System.exit halts execution of all the running threads including the current one. Even finally block does not get executed after try when exit is executed.

When System.exit is called, JVM performs two cleanup tasks before shut down:

First, it executes all the shutdown hooks which have been registered with Runtime.addShutdownHook. This is very useful because it releases the resources external to JVM.

Second is related to Finalizers. Either System.runFinalizersOnExit or Runtime.runFinalizersOnExit. The use of finalizers has been deprecated from a long time. Finalizers can run on live objects while they are being manipulated by other threads.This results in undesirable results or even in a deadlock.

01public class shutDownHooksDemo {
02 
03    public static void main(String[] args) {
04            for(int i=0;i<5;i++)
05            {
06                    final int final_i = i;
07                    try {
08                            Runtime.getRuntime().addShutdownHook(
09                                            new Thread() {
10                                            public void run() {
11                                            if(final_i==4) {
12                                            System.out.println("Inside Try Block.Exiting without executing Finally block.");
13                                            System.exit(0);
14                                            }
15                                            }
16                                            });
17                    }
18                    finally {
19                            System.out.println("Inside Finally Block.");
20                    }
21 
22            }
23    }
24}

6. Check Oddity

Have a look at the lines of code below and determine if they can be used to precisely identify if a given number is Odd?

1public boolean oddOrNot(int num) {
2    return num % 2 == 1;
3}

These lines seem correct but they will return incorrect results one of every four times (Statistically speaking). Consider a negative Odd number, the remainder of division with 2 will not be 1. So, the returned result will be false which is incorrect!

This can be fixed as follows:

1public boolean oddOrNot(int num) {
2    return (num & 1) != 0;
3}

Using this code, not only is the problem of negative odd numbers solved, but this code is also highly optimized. Since, Arithmetic and Logical operations are much faster compared to division and multiplication, the results are achieved faster so in second snippet.

7. Difference between single quotes and double quotes

1public class Haha {
2    public static void main(String args[]) {
3    System.out.print("H" "a");
4    System.out.print('H' 'a');
5    }
6}

From the code, it would seem return “HaHa” is returned, but it actually returns Ha169. The reason is that if double quotes are used, the characters are treated as a string but in case of single quotes, the char -valued operands ( ‘H’ and ‘a’ ) to int values through a process known as widening primitive conversion. After integer conversion, the numbers are added and return 169.

8. Avoiding Memory leaks by simple tricks

Memory leaks often cause performance degradation of software. Since, Java manages memory automatically, the developers do not have much control. But there are still some standard practices which can be used to protect from memory leakages.

  • Always release database connections when querying is complete.
  • Try to use Finally block as often possible.
  • Release instances stored in Static Tables.

9. Avoiding Deadlocks in Java

Deadlocks can occur for many different reasons. There is no single recipe to avoid deadlocks. Normally deadlocks occur when one synchronized object is waiting for lock on resources locked by another synchronized object.

Try running the below program. This program demonstrates a Deadlock. This deadlock arises because both the threads are waiting for the resources which are grabbed by other thread. They both keep waiting and no one releases.

01public class DeadlockDemo {
02   public static Object addLock = new Object();
03   public static Object subLock = new Object();
04 
05   public static void main(String args[]) {
06 
07      MyAdditionThread add = new MyAdditionThread();
08      MySubtractionThread sub = new MySubtractionThread();
09      add.start();
10      sub.start();
11   }
12private static class MyAdditionThread extends Thread {
13      public void run() {
14         synchronized (addLock) {
15        int a = 10, b = 3;
16        int c = a + b;
17            System.out.println("Addition Thread: " + c);
18            System.out.println("Holding First Lock...");
19            try { Thread.sleep(10); }
20            catch (InterruptedException e) {}
21            System.out.println("Addition Thread: Waiting for AddLock...");
22            synchronized (subLock) {
23               System.out.println("Threads: Holding Add and Sub Locks...");
24            }
25         }
26      }
27   }
28   private static class MySubtractionThread extends Thread {
29      public void run() {
30         synchronized (subLock) {
31        int a = 10, b = 3;
32        int c = a - b;
33            System.out.println("Subtraction Thread: " + c);
34            System.out.println("Holding Second Lock...");
35            try { Thread.sleep(10); }
36            catch (InterruptedException e) {}
37            System.out.println("Subtraction  Thread: Waiting for SubLock...");
38            synchronized (addLock) {
39               System.out.println("Threads: Holding Add and Sub Locks...");
40            }
41         }
42      }
43   }
44}

Output:

1=====
2Addition Thread: 13
3Subtraction Thread: 7
4Holding First Lock...
5Holding Second Lock...
6Addition Thread: Waiting for AddLock...
7Subtraction  Thread: Waiting for SubLock...

But if the order in which the threads are called is changed, the deadlock problem is resolved.

01public class DeadlockSolutionDemo {
02   public static Object addLock = new Object();
03   public static Object subLock = new Object();
04 
05   public static void main(String args[]) {
06 
07      MyAdditionThread add = new MyAdditionThread();
08      MySubtractionThread sub = new MySubtractionThread();
09      add.start();
10      sub.start();
11   }
12 
13 
14private static class MyAdditionThread extends Thread {
15      public void run() {
16         synchronized (addLock) {
17        int a = 10, b = 3;
18        int c = a + b;
19            System.out.println("Addition Thread: " + c);
20            System.out.println("Holding First Lock...");
21            try { Thread.sleep(10); }
22            catch (InterruptedException e) {}
23            System.out.println("Addition Thread: Waiting for AddLock...");
24            synchronized (subLock) {
25               System.out.println("Threads: Holding Add and Sub Locks...");
26            }
27         }
28      }
29   }
30    
31   private static class MySubtractionThread extends Thread {
32      public void run() {
33         synchronized (addLock) {
34        int a = 10, b = 3;
35        int c = a - b;
36            System.out.println("Subtraction Thread: " + c);
37            System.out.println("Holding Second Lock...");
38            try { Thread.sleep(10); }
39            catch (InterruptedException e) {}
40            System.out.println("Subtraction  Thread: Waiting for SubLock...");
41            synchronized (subLock) {
42               System.out.println("Threads: Holding Add and Sub Locks...");
43            }
44         }
45      }
46   }
47}

Output:

1=====
2Addition Thread: 13
3Holding First Lock...
4Addition Thread: Waiting for AddLock...
5Threads: Holding Add and Sub Locks...
6Subtraction Thread: 7
7Holding Second Lock...
8Subtraction  Thread: Waiting for SubLock...
9Threads: Holding Add and Sub Locks...

10. Reserve memory for Java

Some of the Java applications can be highly CPU intensive as well as they need a lot of RAM. Such applications generally run slow because of a high RAM requirement. In order to improve performance of such applications, RAM is reserved for Java. So, for example, if we have a Tomcat webserver and it has 10 GB of RAM. If we like, we can allocate RAM for Java on this machine using the following command:

1export JAVA_OPTS="$JAVA_OPTS -Xms5000m -Xmx6000m -XX:PermSize=1024m -XX:MaxPermSize=2048m"
  • Xms = Minimum memory allocation pool
  • Xmx = Maximum memory allocation pool
  • XX:PermSize = Initial size that will be allocated during startup of the JVM
  • XX:MaxPermSize = Maximum size that can be allocated during startup of the JVM

11. How to time operations in Java

There are two standard ways to time operations in Java: System.currentTimeMillis() and System.nanoTime() The question is, which of these to choose and under what circumstances. In principle, they both perform the same action but are different in the following ways:

  1. System.currentTimeMillis takes somewhere between 1/1000th of a second to 15/1000th of a second (depending on the system) but System.nanoTime() takes around 1/1000,000th of a second (1,000 nanos)
  2. System.currentTimeMillis takes a few clock cycles to perform Read Operation. On the other hand, System.nanoTime() takes 100+ clock cycles.
  3. System.currentTimeMillis reflects Absolute Time (Number of millis since 1 Jan 1970 00:00 (Epoch Time)) but System.nanoTime() does not necessarily represent any reference point.

12. Choice between Float and Double

Data typeBytes usedSignificant figures (decimal)
Float47
Double815

Double is often preferred over float in software where precision is important because of the following reasons:

Most processors take nearly the same amount of processing time to perform operations on Float and Double. Double offers far more precision in the same amount of computation time.

13. Computation of power

To compute power (^), java performs Exclusive OR (XOR). In order to compute power, Java offers two options:

  1. Multiplication:
    1double square = double a * double a;                            // Optimized
    2double cube = double a * double a * double a;                   // Non-optimized
    3double cube = double a * double square;                         // Optimized
    4double quad = double a * double a * double a * double a;            // Non-optimized
    5double quad = double square * double square;                    // Optimized
  2. pow(double base, double exponent):‘pow’ method is used to calculate where multiplication is not possible (base^exponent)
    1double cube = Math.pow(base, exponent);

Math.pow should be used ONLY when necessary. For example, exponent is a fractional value. That is because Math.pow() method is typically around 300-600 times slower than a multiplication.

14. How to handle Null Pointer Exceptions

Null Pointer Exceptions are quite common in Java. This exception occurs when we try to call a method on a Null Object Reference. For example,

1int noOfStudents = school.listStudents().count;

If in the above example, if get a NullPointerException, then either school is null or listStudents() is Null. It’s a good idea to check Nulls early so that they can be eliminated.

1private int getListOfStudents(File[] files) {
2      if (files == null)
3        throw new NullPointerException("File list cannot be null");
4    }

15. Encode in JSON

JSON (JavaScript Object Notation) is syntax for storing and exchanging data. JSON is an easier-to-use alternative to XML. Json is becoming very popular over internet these days because of its properties and light weight. A normal data structure can be encoded into JSON and shared across web pages easily. Before beginning to write code, a JSON parser has to be installed. In below examples, we have used json.simple (https://code.google.com/p/json-simple/).

Below is a basic example of Encoding into JSON:

01import org.json.simple.JSONObject;
02import org.json.simple.JSONArray;
03 
04public class JsonEncodeDemo {
05     
06    public static void main(String[] args) {
07         
08        JSONObject obj = new JSONObject();
09        obj.put("Novel Name""Godaan");
10        obj.put("Author""Munshi Premchand");
11  
12        JSONArray novelDetails = new JSONArray();
13        novelDetails.add("Language: Hindi");
14        novelDetails.add("Year of Publication: 1936");
15        novelDetails.add("Publisher: Lokmanya Press");
16         
17        obj.put("Novel Details", novelDetails);
18         
19        System.out.print(obj);
20    }
21}

Output:

1{"Novel Name":"Godaan","Novel Details":["Language: Hindi","Year of Publication: 1936","Publisher: Lokmanya Press"],"Author":"Munshi Premchand"}

16. Decode from JSON

In order to decode JSON, the developer must be aware of the schema. The details can be found in below example:

01import java.io.FileNotFoundException;
02import java.io.FileReader;
03import java.io.IOException;
04import java.util.Iterator;
05 
06import org.json.simple.JSONArray;
07import org.json.simple.JSONObject;
08import org.json.simple.parser.JSONParser;
09import org.json.simple.parser.ParseException;
10 
11public class JsonParseTest {
12 
13    private static final String filePath = "//home//user//Documents//jsonDemoFile.json";
14     
15    public static void main(String[] args) {
16 
17        try {
18            // read the json file
19            FileReader reader = new FileReader(filePath);
20            JSONParser jsonParser = new JSONParser();
21            JSONObject jsonObject = (JSONObject)jsonParser.parse(reader);
22             
23            // get a number from the JSON object
24            Long id =  (Long) jsonObject.get("id");
25            System.out.println("The id is: " + id);        
26 
27            // get a String from the JSON object
28            String  type = (String) jsonObject.get("type");
29            System.out.println("The type is: " + type);
30 
31            // get a String from the JSON object
32            String  name = (String) jsonObject.get("name");
33            System.out.println("The name is: " + name);
34 
35            // get a number from the JSON object
36            Double ppu =  (Double) jsonObject.get("ppu");
37            System.out.println("The PPU is: " + ppu);
38             
39            // get an array from the JSON object
40            System.out.println("Batters:");
41            JSONArray batterArray= (JSONArray) jsonObject.get("batters");
42            Iterator i = batterArray.iterator();
43            // take each value from the json array separately
44            while (i.hasNext()) {
45                JSONObject innerObj = (JSONObject) i.next();
46                System.out.println("ID "+ innerObj.get("id") +
47                        " type " + innerObj.get("type"));
48            }
49 
50            // get an array from the JSON object
51            System.out.println("Topping:");
52            JSONArray toppingArray= (JSONArray) jsonObject.get("topping");
53            Iterator j = toppingArray.iterator();
54            // take each value from the json array separately
55            while (j.hasNext()) {
56                JSONObject innerObj = (JSONObject) j.next();
57                System.out.println("ID "+ innerObj.get("id") +
58                        " type " + innerObj.get("type"));
59            }
60             
61 
62        catch (FileNotFoundException ex) {
63            ex.printStackTrace();
64        catch (IOException ex) {
65            ex.printStackTrace();
66        catch (ParseException ex) {
67            ex.printStackTrace();
68        catch (NullPointerException ex) {
69            ex.printStackTrace();
70        }
71 
72    }
73 
74}

jsonDemoFile.json

01{
02    "id"0001,
03    "type""donut",
04    "name""Cake",
05    "ppu"0.55,
06    "batters":
07        [
08            "id"1001"type""Regular" },
09            "id"1002"type""Chocolate" },
10            "id"1003"type""Blueberry" },
11            "id"1004"type""Devil's Food" }
12        ],
13    "topping":
14        [
15            "id"5001"type""None" },
16            "id"5002"type""Glazed" },
17            "id"5005"type""Sugar" },
18            "id"5007"type""Powdered Sugar" },
19            "id"5006"type""Chocolate with Sprinkles" },
20            "id"5003"type""Chocolate" },
21            "id"5004"type""Maple" }
22        ]
23}
01The id is: 1
02The type is: donut
03The name is: Cake
04The PPU is: 0.55
05Batters:
06ID 1001 type Regular
07ID 1002 type Chocolate
08ID 1003 type Blueberry
09ID 1004 type Devil's Food
10Topping:
11ID 5001 type None
12ID 5002 type Glazed
13ID 5005 type Sugar
14ID 5007 type Powdered Sugar
15ID 5006 type Chocolate with Sprinkles
16ID 5003 type Chocolate
17ID 5004 type Maple

17. Simple String Search

Java offers a Library method called indexOf(). This method is used with String Object and it returns the position of index of desired string. If the string is not found then -1 is returned.

01public class StringSearch {
02 
03    public static void main(String[] args) {
04        String myString = "I am a String!";
05         
06        if(myString.indexOf("String") == -1) {
07            System.out.println("String not Found!");
08        }
09        else {
10            System.out.println("String found at: " + myString.indexOf("String"));
11        }
12    }
13}

18. Listing content of a directory

In order to list the contents of a directory, below program can be used. This program simply receives the names of the all sub-directory and files in a folder in an Array and then that array is sequentially traversed to list all the contents.

01import java.io.*;
02 
03public class ListContents {
04    public static void main(String[] args) {
05        File file = new File("//home//user//Documents/");
06        String[] files = file.list();
07 
08        System.out.println("Listing contents of " + file.getPath());
09        for(int i=0 ; i < files.length ; i++)
10        {
11            System.out.println(files[i]);
12        }
13    }
14}

19. A Simple IO

In order to read from a file and write to a file, Java offers FileInputStream and FileOutputStream Classes. FileInputStream’s constructor accepts filepath of Input File as argument and creates File Input Stream. Similarly, FileOutputStream’s constructor accepts filepath of Output File as argument and creates File Output Stream.After the file handling is done, it’s important to “close” the streams.

01import java.io.*;
02 
03public class myIODemo {
04    public static void main(String args[]) throws IOException {
05        FileInputStream in = null;
06        FileOutputStream out = null;
07         
08        try {
09            in = new FileInputStream("//home//user//Documents//InputFile.txt");
10            out = new FileOutputStream("//home//user//Documents//OutputFile.txt");
11             
12            int c;
13            while((c = in.read()) != -1) {
14                out.write(c);
15            }
16        finally {
17            if(in != null) {
18                in.close();
19            }
20            if(out != null) {
21                out.close();
22            }
23        }
24    }
25}

20. Executing a shell command from Java

Java offers Runtime class to execute Shell Commands. Since these are external commands, exception handling is really important. In below example, we illustrate this with a simple example. We are trying to open a PDF file from Shell command.

01import java.io.BufferedReader;
02import java.io.InputStream;
03import java.io.InputStreamReader;
04 
05public class ShellCommandExec {
06 
07    public static void main(String[] args) {
08        String gnomeOpenCommand = "gnome-open //home//user//Documents//MyDoc.pdf";
09 
10        try {
11            Runtime rt = Runtime.getRuntime();
12            Process processObj = rt.exec(gnomeOpenCommand);
13 
14            InputStream stdin = processObj.getErrorStream();
15            InputStreamReader isr = new InputStreamReader(stdin);
16            BufferedReader br = new BufferedReader(isr);
17 
18            String myoutput = "";
19 
20            while ((myoutput=br.readLine()) != null) {
21                myoutput = myoutput+"\n";
22            }
23            System.out.println(myoutput);
24        }
25        catch (Exception e) {
26            e.printStackTrace();
27        }
28    }
29}

21. Using Regex

Summary of Regular Expression Constructs (Source: Oracle Website)

Characters
xThe character x
\\The backslash character
\0nThe character with octal value 0n (0 <= n <= 7)
\0nnThe character with octal value 0nn (0 <= n <= 7)
\0mnnThe character with octal value 0mnn (0 <= m <= 3, 0 <= n <= 7)
\xhhThe character with hexadecimal value 0xhh
\uhhhhThe character with hexadecimal value 0xhhhh
\x{h…h}The character with hexadecimal value 0xh…h (Character.MIN_CODE_POINT <= 0xh…h <= Character.MAX_CODE_POINT)
\tThe tab character (‘\u0009’)
\nThe newline (line feed) character (‘\u000A’)
\rThe carriage-return character (‘\u000D’)
\fThe form-feed character (‘\u000C’)
\aThe alert (bell) character (‘\u0007’)
\eThe escape character (‘\u001B’)
\cxThe control character corresponding to x

 

Character classes
[abc]a, b, or c (simple class)
[^abc]Any character except a, b, or c (negation)
[a-zA-Z]a through z or A through Z, inclusive (range)
[a-d[m-p]]a through d, or m through p: [a-dm-p] (union)
[a-z&&[def]]d, e, or f (intersection)
[a-z&&[^bc]]a through z, except for b and c: [ad-z] (subtraction)
[a-z&&[^m-p]]a through z, and not m through p: [a-lq-z](subtraction)

 

Predefined character classes
.Any character (may or may not match line terminators)
\dA digit: [0-9]
\DA non-digit: [^0-9]
\sA whitespace character: [ \t\n\x0B\f\r]
\SA non-whitespace character: [^\s]
\wA word character: [a-zA-Z_0-9]
\WA non-word character: [^\w]

 

Boundary matchers
^The beginning of a line
$The end of a line
\bA word boundary
\BA non-word boundary
\AThe beginning of the input
\GThe end of the previous match
\ZThe end of the input but for the final terminator, if any
\zThe end of the input
01import java.util.regex.Matcher;
02import java.util.regex.Pattern;
03 
04public class RegexMatches
05{
06    private static String pattern =  "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
07    private static Pattern mypattern = Pattern.compile(pattern);
08     
09    public static void main( String args[] ){
10 
11        String valEmail1 = "testemail@domain.com";
12        String invalEmail1 = "....@domain.com";
13        String invalEmail2 = ".$$%%@domain.com";
14        String valEmail2 = "test.email@domain.com";
15 
16        System.out.println("Is Email ID1 valid? "+validateEMailID(valEmail1));
17        System.out.println("Is Email ID1 valid? "+validateEMailID(invalEmail1));
18        System.out.println("Is Email ID1 valid? "+validateEMailID(invalEmail2));
19        System.out.println("Is Email ID1 valid? "+validateEMailID(valEmail2));
20 
21    }
22     
23    public static boolean validateEMailID(String emailID) {
24        Matcher mtch = mypattern.matcher(emailID);
25        if(mtch.matches()){
26            return true;
27        }
28        return false;
29    }  
30}

22. Simple Java Swing Example

With the help of Java Swing GUI can be created. Java offers Javax which contains “swing”. The GUI using swing begin with extending JFrame. Boxes are added so they can contain GUI components like Button, Radio Button, Text box, etc. These boxes are set on top of Container.

01import java.awt.*;
02import javax.swing.*; 
03 
04public class SwingsDemo extends JFrame
05{
06    public SwingsDemo()
07    {
08        String path = "//home//user//Documents//images";
09        Container contentPane = getContentPane();
10        contentPane.setLayout(new FlowLayout());  
11         
12        Box myHorizontalBox = Box. createHorizontalBox(); 
13        Box myVerticleBox = Box. createVerticalBox();  
14         
15        myHorizontalBox.add(new JButton("My Button 1"));
16        myHorizontalBox.add(new JButton("My Button 2"));
17        myHorizontalBox.add(new JButton("My Button 3"));  
18 
19        myVerticleBox.add(new JButton(new ImageIcon(path + "//Image1.jpg")));
20        myVerticleBox.add(new JButton(new ImageIcon(path + "//Image2.jpg")));
21        myVerticleBox.add(new JButton(new ImageIcon(path + "//Image3.jpg")));  
22         
23        contentPane.add(myHorizontalBox);
24        contentPane.add(myVerticleBox);  
25         
26        pack();
27        setVisible(true);
28    }
29     
30    public static void main(String args[]) {
31        new SwingsDemo();
32    
33}

23. Play a sound with Java

Playing sound is a common requirement in Java, especially along with Games.

This demo explains how to play an Audio file along with Java code.

01import java.io.*;
02import java.net.URL;
03import javax.sound.sampled.*;
04import javax.swing.*;
05 
06// To play sound using Clip, the process need to be alive.
07// Hence, we use a Swing application.
08public class playSoundDemo extends JFrame {
09 
10   // Constructor
11   public playSoundDemo() {
12      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
13      this.setTitle("Play Sound Demo");
14      this.setSize(300200);
15      this.setVisible(true);
16 
17      try {
18         URL url = this.getClass().getResource("MyAudio.wav");
19         AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
20         Clip clip = AudioSystem.getClip();
21         clip.open(audioIn);
22         clip.start();
23      catch (UnsupportedAudioFileException e) {
24         e.printStackTrace();
25      catch (IOException e) {
26         e.printStackTrace();
27      catch (LineUnavailableException e) {
28         e.printStackTrace();
29      }
30   }
31 
32   public static void main(String[] args) {
33      new playSoundDemo();
34   }
35}

24. PDF Export

Export a table to PDF is a common requirement in Java programs. Using itextpdf, it becomes really easy to export PDF.

01import java.io.FileOutputStream;
02import com.itextpdf.text.Document;
03import com.itextpdf.text.Paragraph;
04import com.itextpdf.text.pdf.PdfPCell;
05import com.itextpdf.text.pdf.PdfPTable;
06import com.itextpdf.text.pdf.PdfWriter;
07 
08public class DrawPdf {
09 
10      public static void main(String[] args) throws Exception {
11        Document document = new Document();
12        PdfWriter.getInstance(document, new FileOutputStream("Employee.pdf"));
13        document.open();
14         
15        Paragraph para = new Paragraph("Employee Table");
16        para.setSpacingAfter(20);
17        document.add(para);
18         
19        PdfPTable table = new PdfPTable(3);
20        PdfPCell cell = new PdfPCell(new Paragraph("First Name"));
21 
22        table.addCell(cell);
23        table.addCell("Last Name");
24        table.addCell("Gender");
25        table.addCell("Ram");
26        table.addCell("Kumar");
27        table.addCell("Male");
28        table.addCell("Lakshmi");
29        table.addCell("Devi");
30        table.addCell("Female");
31 
32        document.add(table);
33         
34        document.close();
35      }
36    }

25. Sending Email from Java Code

Sending email from Java is simple. We need to install Java Mail Jar and set its path in our program’s classpath. The basic properties are set in the code and we are good to send email as mentioned in the code below:

01import java.util.*;
02import javax.mail.*;
03import javax.mail.internet.*;
04 
05public class SendEmail
06{
07    public static void main(String [] args)
08    {   
09        String to = "recipient@gmail.com";
10        String from = "sender@gmail.com";
11        String host = "localhost";
12 
13        Properties properties = System.getProperties();
14        properties.setProperty("mail.smtp.host", host);
15        Session session = Session.getDefaultInstance(properties);
16 
17        try{
18            MimeMessage message = new MimeMessage(session);
19            message.setFrom(new InternetAddress(from));
20 
21            message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
22 
23            message.setSubject("My Email Subject");
24            message.setText("My Message Body");
25            Transport.send(message);
26            System.out.println("Sent successfully!");
27        }
28        catch (MessagingException ex) {
29            ex.printStackTrace();
30        }
31    }
32}

26. Measuring time

Many applications require a very precise time measurement. For this purpose, Java provides static methods in System class:

  1. currentTimeMillis(): Returns current time in MilliSeconds since Epoch Time, in Long.
    1long startTime = System.currentTimeMillis();
    2long estimatedTime = System.currentTimeMillis() - startTime;
  2. nanoTime(): Returns the current value of the most precise available system timer, in nanoseconds, in long. nanoTime() is meant for measuring relative time interval instead of providing absolute timing.
    1long startTime = System.nanoTime();
    2long estimatedTime = System.nanoTime() - startTime;

27. Rescale Image

An image can rescaled usingAffineTransform. First of all, Image Buffer of input image is created and then scaled image is rendered.

01import java.awt.Graphics2D;
02import java.awt.geom.AffineTransform;
03import java.awt.image.BufferedImage;
04import java.io.File;
05import javax.imageio.ImageIO;
06 
07public class RescaleImage {
08  public static void main(String[] args) throws Exception {
09    BufferedImage imgSource = ImageIO.read(new File("images//Image3.jpg"));
10    BufferedImage imgDestination = new BufferedImage(100100, BufferedImage.TYPE_INT_RGB);
11    Graphics2D g = imgDestination.createGraphics();
12    AffineTransform affinetransformation = AffineTransform.getScaleInstance(22);
13    g.drawRenderedImage(imgSource, affinetransformation);
14    ImageIO.write(imgDestination, "JPG"new File("outImage.jpg"));
15  }
16}

28. Capturing Mouse Hover Coordinates

By implementing MouseMotionListner Interface, mouse events can be captured. When the mouse is entered in a specific region MouseMoved Event is triggered and motion coordinates can be captured. The following example explains it:

01import java.awt.event.*;
02import javax.swing.*;
03 
04public class MouseCaptureDemo extends JFrame implements MouseMotionListener
05{
06    public JLabel mouseHoverStatus;
07 
08    public static void main(String args[])
09    {
10        new MouseCaptureDemo();
11    }
12 
13    MouseCaptureDemo()
14    {
15        setSize(500500);
16        setTitle("Frame displaying Coordinates of Mouse Motion");
17 
18        mouseHoverStatus = new JLabel("No Mouse Hover Detected.", JLabel.CENTER);
19        add(mouseHoverStatus);
20        addMouseMotionListener(this);
21        setVisible(true);
22    }
23 
24    public void mouseMoved(MouseEvent e)
25    {
26        mouseHoverStatus.setText("Mouse Cursor Coordinates => X:"+e.getX()+" | Y:"+e.getY());
27    }
28 
29    public void mouseDragged(MouseEvent e)
30    {}
31}

29. FileOutputStream Vs. FileWriter

File writing in Java is done mainly in two ways: FileOutputStream and FileWriter. Sometimes, developers struggle to choose one among them. This example helps them in choosing which one should be used under given requirements. First, let’s take a look at the implementation part:

Using FileOutputStream:

1File foutput = new File(file_location_string);
2FileOutputStream fos = new FileOutputStream(foutput);
3BufferedWriter output = new BufferedWriter(new OutputStreamWriter(fos));
4output.write("Buffered Content");

Using FileWriter:

1FileWriter fstream = new FileWriter(file_location_string);
2BufferedWriter output = new BufferedWriter(fstream);
3output.write("Buffered Content");

According to Java API specifications:

FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter.

This makes it pretty clear that for image type of Data FileOutputStream should be used and for Text type of data FileWriter should be used.

Additional Suggestions

  1. Use Collections

    Java is shipped with a few collection classes – for example, Vector, Stack, Hashtable, Array. The developers are encouraged to use collections as extensively as possible for the following reasons:

    • Use of collections makes the code reusable and interoperable.
    • Collections make the code more structured, easier to understand and maintainable.
    • Out of the box collection classes are well tested so the quality of code is good.
  2. 10-50-500 Rule

    In big software packages, maintaining code becomes very challenging. Developers who join fresh ongoing support projects, often complain about: Monolithic CodeSpaghetti Code. There is a very simple rule to avoid that or keep the code clean and maintainable: 10-50-500.

    • 10: No package can have more than 10 classes.
    • 50: No method can have more than 50 lines of code.
    • 500: No class can have more than 500 lines of code.
  3. SOLID Class Design Principles

    SOLID (http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29) is an acronym for design principles coined by Robert Martin. According to this rule:

    RuleDescription
    Single responsibility principleA class should have one and only one task/responsibility. If class is performing more than one task, it leads to confusion.
    Open/closed principleThe developers should focus more on extending the software entities rather than modifying them.
    Liskov substitution principleIt should be possible to substitute the derived class with base class.
    Interface segregation principleIt’s like Single Responsibility Principle but applicable to interfaces. Each interface should be responsible for a specific task. The developers should need to implement methods which he/she doesn’t need.
    Dependency inversion principleDepend upon Abstractions- but not on concretions. This means that each module should be separated from other using an abstract layer which binds them together.
  4. Usage of Design Patterns

    Design patterns help developers to incorporate best Software Design Principles in their software. They also provide common platform for developers across the globe. They provide standard terminology which makes developers to collaborate and easier to communicate to each other.

  5. Document ideas

    Never just start writing code. Strategize, Prepare, Document, Review and Implementation. First of all, jot down your requirements. Prepare a design document. Mention assumptions properly. Get the documents peer reviewed and take a sign off on them.

  6. Use Equals over ==

    == compares object references, it checks to see if the two operands point to the same object (not equivalent objects, the same object).On the other hand, “equals” perform actual comparison of two strings.

  7. Avoid Floating Point Numbers

    Floating point numbers should be used only if they are absolutely necessary. For example, representing Rupees and Paise using Floating Point numbers can be Problematic – BigDecimal should instead be preferred. Floating point numbers are more useful in measurements.

Best Resources to learn Java



출처 - https://www.javacodegeeks.com/2015/06/java-programming-tips-best-practices-beginners.html

'Information Technology > JAVA' 카테고리의 다른 글

Hello World  (0) 2020.01.13

+ Recent posts