Вы находитесь на странице: 1из 22

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.

1 public 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
2 String bad = new String("Yet another string object");
3
4 //Faster Instantiation
5 String 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:

01 import java.util.ArrayList;
02 import java.util.List;
03
04 public class Employees {
05
06

private List Employees;

07
08

public List getEmployees() {

09
10
11
12
13
14
15
16 }

//initialize only when required


if(null == Employees) {
Employees = new ArrayList();
}
return Employees;
}

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.

01 import java.util.ArrayList;
02
03 public class arrayVsArrayList {
04

05

public static void main(String[] args) {

06

int[] myArray = new int[6];

07

myArray[7]= 10; // ArraysOutOfBoundException

08
09
10
11
12
13
14
15
16
17

//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);

18

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

19
20
21
22
23
24
25 }

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


}

1.

//Multi-dimensional Array
int[][][] multiArray = new int [3][3][3];
}
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:

01 public class shutDownHooksDemo {


02
public static void main(String[] args) {
03
for(int i=0;i<5;i++)
04
{
05
try {
06
if(i==4) {
System.out.println("Inside Try Block.Exiting without
07
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.

01 public class shutDownHooksDemo {


02
03

public static void main(String[] args) {

04
05
06

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

07
08
09

try {

final int final_i = i;


Runtime.getRuntime().addShutdownHook(
new Thread() {

10
11

public void run() {


if(final_i==4) {
System.out.println("Inside
12
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?

1 public 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:

1 public 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


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

System.out.print('H' + 'a');
}

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.

01 public 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
}
12 private static class MyAdditionThread extends Thread {
13
public void run() {
14

synchronized (addLock) {

15

int a = 10, b = 3;

16

int c = a + b;

17
18
19

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


System.out.println("Holding First Lock...");
try { Thread.sleep(10); }

20

catch (InterruptedException e) {}
System.out.println("Addition Thread: Waiting for
21
AddLock...");
22
synchronized (subLock) {
System.out.println("Threads: Holding Add and Sub
23
Locks...");
24
}
25
}
26
}
27
}
28
private static class MySubtractionThread extends Thread {
29
30

public void run() {


synchronized (subLock) {

31

int a = 10, b = 3;

32

int c = a - b;

33
34
35

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


System.out.println("Holding Second Lock...");
try { Thread.sleep(10); }

36

catch (InterruptedException e) {}
System.out.println("Subtraction Thread: Waiting for
37
SubLock...");
38
synchronized (addLock) {
System.out.println("Threads: Holding Add and Sub
39
Locks...");
40
}
41
}
42
}
43
}
44 }
Output:

1
2
3
4
5
6

=====
Addition Thread: 13
Subtraction Thread: 7
Holding First Lock...
Holding Second Lock...
Addition Thread: Waiting for AddLock...

7 Subtraction

Thread: Waiting for SubLock...

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

01 public 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
09
10

MySubtractionThread sub = new MySubtractionThread();


add.start();
sub.start();

11
12

13
14 private static class MyAdditionThread extends Thread {
15
public void run() {
16

synchronized (addLock) {

17

int a = 10, b = 3;

18

int c = a + b;

19
20
21

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


System.out.println("Holding First Lock...");
try { Thread.sleep(10); }

22

catch (InterruptedException e) {}
System.out.println("Addition Thread: Waiting for
23
AddLock...");
24
synchronized (subLock) {
System.out.println("Threads: Holding Add and Sub
25
Locks...");
26
}
27
}
28
}
29
}
30
31
32
33

private static class MySubtractionThread extends Thread {


public void run() {
synchronized (addLock) {

34

int a = 10, b = 3;

35

int c = a - b;

36
37
38

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


System.out.println("Holding Second Lock...");
try { Thread.sleep(10); }

39

catch (InterruptedException e) {}
System.out.println("Subtraction Thread: Waiting for
40
SubLock...");
41
synchronized (subLock) {
System.out.println("Threads: Holding Add and Sub
42
Locks...");
43
}
44
}
45
}
46
}
47 }
Output:

1
2
3
4
5
6

=====
Addition Thread: 13
Holding First Lock...
Addition Thread: Waiting for AddLock...
Threads: Holding Add and Sub Locks...
Subtraction Thread: 7

7 Holding Second Lock...


8 Subtraction Thread: Waiting for SubLock...
9 Threads: 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:

1 export 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 type

Bytes used

Significant figures (decimal)

Float

Double

15

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:

1
2
3
4
5

double square
Optimized
double cube =
optimized
double cube =
Optimized
double quad =
Non-optimized
double quad =

= double a * double a;

//

double a * double a * double a;

// Non-

double a * double square;

//

double a * double a * double a * double a;


double square * double square;

//
//

Optimized
4.

pow(double base, double exponent):pow method is used to calculate where multiplication is not
possible (base^exponent)

1 double 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,

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


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

1 private int getListOfStudents(File[] files) {


2
if (files == null)
3
4

throw new NullPointerException("File list cannot be null");


}

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:

01 import org.json.simple.JSONObject;
02 import org.json.simple.JSONArray;
03
04 public 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
13
14
15
16
17
18
19
20
21 }
Output:

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);
}

{"Novel Name":"Godaan","Novel Details":["Language: Hindi","Year of


1 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:

01 import java.io.FileNotFoundException;
02 import java.io.FileReader;
03 import java.io.IOException;
04 import java.util.Iterator;
05
06 import org.json.simple.JSONArray;
07 import org.json.simple.JSONObject;
08 import org.json.simple.parser.JSONParser;
09 import org.json.simple.parser.ParseException;
10
11 public class JsonParseTest {
12
13

private static final String filePath


= "//home//user//Documents//jsonDemoFile.json";

14
15

public static void main(String[] args) {

16
17
18
19

try {
// read the json file
FileReader reader = new FileReader(filePath);

20

JSONParser jsonParser = new JSONParser();


JSONObject jsonObject =
21
(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
28
29

// get a String from the JSON object


String type = (String) jsonObject.get("type");

30
31
32
33

// get a String from the JSON object


String name = (String) jsonObject.get("name");

34
35
36
37

// get a number from the JSON object


Double ppu = (Double) jsonObject.get("ppu");

38

System.out.println("The type is: " + type);

System.out.println("The name is: " + name);

System.out.println("The PPU is: " + ppu);

39
40

// get an array from the JSON object


System.out.println("Batters:");
JSONArray batterArray= (JSONArray)
41
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:");
JSONArray toppingArray= (JSONArray)
52
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
63
64
65
66
67
68
69
70
71
72
73
74 }

} catch (FileNotFoundException ex) {


ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ParseException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}

jsonDemoFile.json

01 {
02

"id": 0001,

03

"type": "donut",

04

"name": "Cake",

05
06
07
08

"ppu": 0.55,
"batters":
[
{ "id": 1001, "type": "Regular" },

09

{ "id": 1002, "type": "Chocolate" },

10

{ "id": 1003, "type": "Blueberry" },

11

{ "id": 1004, "type": "Devil's Food" }

12
13
14
15

],
"topping":
[
{ "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 }
01 The id is: 1
02 The type is: donut
03 The name is: Cake
04 The PPU is: 0.55
05 Batters:
06 ID 1001 type Regular
07 ID 1002 type
08 ID 1003 type
09 ID 1004 type
10 Topping:
11 ID 5001 type

Chocolate
Blueberry
Devil's Food
None

12 ID 5002 type Glazed


13 ID 5005 type Sugar
14 ID 5007 type Powdered Sugar
15 ID 5006 type Chocolate with Sprinkles
16 ID 5003 type Chocolate
17 ID 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.

01 public class StringSearch {


02
03

public static void main(String[] args) {

04

String myString = "I am a String!";

05
06
07
08
09

if(myString.indexOf("String") == -1) {
System.out.println("String not Found!");
}
else {

System.out.println("String found at: " +


myString.indexOf("String"));
11
}
12
}
13 }
10

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.

01 import java.io.*;
02
03 public 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
10
11
12
13
14 }

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


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

19. A Simple IO
In order to read from a file and write to a file, Java offers FileInputStream and FileOutputStream Classes.
FileInputStreams constructor accepts filepath of Input File as argument and creates File Input Stream. Similarly,
FileOutputStreams constructor accepts filepath of Output File as argument and creates File Output Stream.After
the file handling is done, its important to close the streams.

01 import java.io.*;
02
03 public class myIODemo {
04
public static void main(String args[]) throws IOException {
05
FileInputStream in = null;
06

FileOutputStream out = null;

07
08

try {
in
09
= new FileInputStream("//home//user//Documents//InputFile.txt");
out
10
= new FileOutputStream("//home//user//Documents//OutputFile.txt");
11
12
13
14
15
16
17
18
19
20
21

int c;
while((c = in.read()) != -1) {
out.write(c);
}
} finally {
if(in != null) {
in.close();
}
if(out != null) {
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.

01 import java.io.BufferedReader;
02 import java.io.InputStream;
03 import java.io.InputStreamReader;
04
05 public class ShellCommandExec {
06
07
08

public static void main(String[] args) {


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

09
10
11
12
13
14
15

try {
Runtime rt = Runtime.getRuntime();
Process processObj = rt.exec(gnomeOpenCommand);

16

BufferedReader br = new BufferedReader(isr);

InputStream stdin = processObj.getErrorStream();


InputStreamReader isr = new InputStreamReader(stdin);

17
18

String myoutput = "";

19
20
21
22
23
24
25
26
27
28
29 }

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


myoutput = myoutput+"\n";
}
System.out.println(myoutput);
}
catch (Exception e) {
e.printStackTrace();
}
}

21. Using Regex


Summary of Regular Expression Constructs (Source: Oracle Website)
Characters
x

The character x

\\

The backslash character

\0n

The character with octal value 0n (0 <= n <= 7)

\0nn

The character with octal value 0nn (0 <= n <= 7)

\0mnn

The character with octal value 0mnn (0 <= m <= 3, 0 <= n <= 7)

\xhh

The character with hexadecimal value 0xhh

\uhhhh

The character with hexadecimal value 0xhhhh

\x{hh}

The character with hexadecimal value 0xhh (Character.MIN_CODE_POINT <= 0xhh <=
Character.MAX_CODE_POINT)

\t

The tab character (\u0009)

\n

The newline (line feed) character (\u000A)

\r

The carriage-return character (\u000D)

\f

The form-feed character (\u000C)

\a

The alert (bell) character (\u0007)

\e

The escape character (\u001B)

\cx

The 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)

\d

A digit: [0-9]

\D

A non-digit: [^0-9]

\s

A whitespace character: [ \t\n\x0B\f\r]

\S

A non-whitespace character: [^\s]

\w

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

\W

A non-word character: [^\w]

Boundary matchers
^

The beginning of a line

The end of a line

\b

A word boundary

\B

A non-word boundary

\A

The beginning of the input

\G

The end of the previous match

\Z

The end of the input but for the final terminator, if any

\z

The end of the input

01 import java.util.regex.Matcher;
02 import java.util.regex.Pattern;
03
04 public 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
System.out.println("Is Email
"+validateEMailID(valEmail1));
System.out.println("Is Email
17
"+validateEMailID(invalEmail1));
System.out.println("Is Email
18
"+validateEMailID(invalEmail2));
System.out.println("Is Email
19
"+validateEMailID(valEmail2));
20
21
}
22
16

23
24
25
26
27
28
29
30 }

ID1 valid?
ID1 valid?
ID1 valid?
ID1 valid?

public static boolean validateEMailID(String emailID) {


Matcher mtch = mypattern.matcher(emailID);
if(mtch.matches()){
return true;
}
return false;
}

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.

01 import java.awt.*;
02 import javax.swing.*;
03
04 public class SwingsDemo extends JFrame
05 {
06
public SwingsDemo()
07
{
08
String path = "//home//user//Documents//images";

09
10

Container contentPane = getContentPane();


contentPane.setLayout(new FlowLayout());

11
12
13
14

Box myHorizontalBox = Box. createHorizontalBox();


Box myVerticleBox = Box. createVerticalBox();

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
24
25
26
27
28
29

contentPane.add(myHorizontalBox);
contentPane.add(myVerticleBox);
pack();
setVisible(true);
}

30

public static void main(String args[]) {

31
32
33 }

new SwingsDemo();

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.

01 import java.io.*;
02 import java.net.URL;
03 import javax.sound.sampled.*;
04 import javax.swing.*;
05
06 // To play sound using Clip, the process need to be alive.
07 // Hence, we use a Swing application.
08 public class playSoundDemo extends JFrame {
09
10
11
12
13
14
15

// Constructor
public playSoundDemo() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Play Sound Demo");
this.setSize(300, 200);
this.setVisible(true);

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

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();
}
}

32

public static void main(String[] args) {

33
34
35 }

new playSoundDemo();
}

24. PDF Export


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

01 import java.io.FileOutputStream;
02 import com.itextpdf.text.Document;
03 import com.itextpdf.text.Paragraph;
04 import com.itextpdf.text.pdf.PdfPCell;
05 import com.itextpdf.text.pdf.PdfPTable;
06 import com.itextpdf.text.pdf.PdfWriter;
07
08 public class DrawPdf {
09
10

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

11
12

Document document = new Document();


PdfWriter.getInstance(document, new FileOutputStream("Employee.pd
f"));

13
14

document.open();

15
16
17
18

Paragraph para = new Paragraph("Employee Table");


para.setSpacingAfter(20);
document.add(para);

19

PdfPTable table = new PdfPTable(3);

20

PdfPCell cell = new PdfPCell(new Paragraph("First Name"));

21

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

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();
}
}

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 programs classpath.
The basic properties are set in the code and we are good to send email as mentioned in the code below:

01 import java.util.*;
02 import javax.mail.*;
03 import javax.mail.internet.*;
04
05 public 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
14
15
16
17
18

Properties properties = System.getProperties();


properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);

19

message.setFrom(new InternetAddress(from));

20
21
22
23
24
25
26
27
28
29

ress(to));

message.addRecipient(Message.RecipientType.TO,new InternetAdd

message.setSubject("My Email Subject");


message.setText("My Message Body");
Transport.send(message);
System.out.println("Sent successfully!");
}
catch (MessagingException ex) {
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.

1 long startTime = System.currentTimeMillis();


2 long 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.

1 long startTime = System.nanoTime();


2 long 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.

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

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:

01 import java.awt.event.*;
02 import javax.swing.*;
03
04 public class MouseCaptureDemo extends JFrame implements MouseMotionListener
05 {

06

public JLabel mouseHoverStatus;

07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23

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);
}

24
25

public void mouseMoved(MouseEvent e)


{
mouseHoverStatus.setText("Mouse Cursor Coordinates =>
26
X:"+e.getX()+" | Y:"+e.getY());
27
}
28
29
30
31 }

public void mouseDragged(MouseEvent e)


{}

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, lets take a look at the implementation part:

Using FileOutputStream:
view sourceprint?

1 File foutput = new File(file_location_string);


2 FileOutputStream fos = new FileOutputStream(foutput);
3 BufferedWriter output = new BufferedWriter(new OutputStreamWriter(fos));
4 output.write("Buffered Content");
Using FileWriter:

1 FileWriter fstream = new FileWriter(file_location_string);


2 BufferedWriter output = new BufferedWriter(fstream);
3 output.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
o

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 Code, Spaghetti Code. There is a very simple rule to avoid
o

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.

2.

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:

3.

Rule

Description

Single responsibility principle

A class should have one and only one task/responsibility. If class is performing more than one
task, it leads to confusion.

Open/closed principle

The developers should focus more on extending the software entities rather than modifying
them.

Liskov substitution principle

It should be possible to substitute the derived class with base class.

Interface segregation principle

Its 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
doesnt need.

Dependency inversion principle

Depend upon Abstractions- but not on concretions. This means that each module should be
separated from other using an abstract layer which binds them together.

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.

4.

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.

5.

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.

6.

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.

1) Example 1: Talks about empty collections, but the example is about returning (supposedly) a String
2) Example 1: Does not compile. Method returns String. class is not a valid return type and the method has no braces.
3) Example 1: Testing null == someObject is confusing. Its more useful in a String context: No.equals(anwser)
4) Example 2: increases performance time is confusing: it either decreases performance, or increases time.
5) Example 3: You have a class Employees and a variable Employees. This is extremely confusing. The Java convention says
variables always start with lowercase (except static finals).
6) Example 3: This is premature optimization. Dont do that. Especially your targeted audience beginners should not worry
about this kind of micro optimizations.
7) Example 4: For day to day use, an ArrayList wins, hands down. There are almost no reasons to replace an ArrayList by an
array. (Think beginner tips!)
8) Example 5: How is this mess a beginners tip?
9) Example 8: How does using a finally-block help in avoiding memoryleaks?
10) Example 8: Explain instances in a static table?
11) Example 9: You dont change order in which the Thread are called, as your comment suggests. You are using different object
to synchronize on. That is fundamentally different.
12) Example 9: Using Objects to hold locks is old and deprecated. There are way better mechanisms to do this.
(http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Lock.html) If you want beginners to learn something from
this, create an example using the mechanisms that are made for it.
13) Example 10: Its noteworthy to mention this is only available on 64-bit JVMs.
14) Example 10: This answer is straight from StackOverflow. (http://stackoverflow.com/questions/8356416/xxmaxpermsize-withor-without-xxpermsize). PermSize and MaxPermSize requires a little more thought than just slapping 1 and 2 GB in there.
15) Example 14: Your second code fragment does not solve the problem in the first code fragement. This is confusing. It even
CAUSES a NullPointerException instead of preventing one.
16) Example 16: The path on line 13 is escaped in some weird way. Slashes dont need to be escaped. BACKslashes ofcourse
do.
17) Example 17: Confusing: Java offers a Library method called indexOf(). This method is used with String Object. Library
methods do not exist in Java. Better would be: The String class has a method indexOf() that returns the position.
18) Example 18: See comment 16
19) Example 19: Note that list() can return null if the given file is invalid.
20) Example 20: You say: exception handling is really important, and your code fragment only has e.printStackTrace()?
21) Example 21: Just a side note: Validating an emailaddress using a regex is near impossible. There are numerous interesting
discussions about that on StackOverflow. Just for fun, see a valid regex here: http://ex-parrot.com/~pdw/Mail-RFC822Address.html
22) Example 22: The technology is called Swing not Swings.

Вам также может понравиться