You are on page 1of 12

10/3/2015

30JavaProgrammingTipsandBestPracticesforBeginners|JavaCodeGeeks

KnowledgeBase

ANDROID

JobBoard

JAVA

JoinUs

About

JVM LANGUAGES

SOFTWARE DEVELOPMENT

AGILE

CAREER

COMMUNICATIONS

DEVOPS

Search...

META JCG

HomeJavaCoreJava30JavaProgrammingTipsandBestPracticesforBeginners

ABOUT SHUBHRA GUPTA

30 Java Programming Tips and Best Practices for Beginners


Postedby:ShubhraGupta inCoreJava June14th,2015

JavaisoneofthemostpopularprogramminglanguagesbeitWinapplications,Web
Applications,Mobile,Network,consumerelectronicgoods,settopboxdevices,Javais
everywhere.
Morethan3BilliondevicesrunonJava.AccordingtoOracle,5billionJavaCardsare
inuse.
Morethan9MilliondeveloperschoosetowritetheircodeinJavaanditisvery
popularamongdevelopersaswellasbeingthemostpopulardevelopmentplatform.
ForupcomingbreedofJavadevelopers,thisblogpresentsacollectionofbestpractices
whichhavebeenlearntoveraperiodoftime:

Doyouwanttoknowhowtodevelopyour
skillsettobecomeaJavaRockstar?
SubscribetoournewslettertostartRockingrightnow!
TogetyoustartedwegiveyouourbestsellingeBooksforFREE!
1.JPAMiniBook
2.JVMTroubleshootingGuide
3.JUnitTutorialforUnitTesting
4.JavaAnnotationsTutorial
5.JavaInterviewQuestions
6.SpringInterviewQuestions
7.AndroidUIDesign
andmanymore....

Emailaddress:

NEWSLETTER

133865insidersarealreadyenjoyin
weeklyupdatesandcomplimentary
whitepapers!

Jointhemnowtogain
accesstothelatestnewsintheJava

aswellasinsightsaboutAndroid,Scala,
Groovyandotherrelatedtechnologies.

Emailaddress:
Youremailaddress

Youremailaddress
Signup
Signup

1.PreferreturningEmptyCollectionsinsteadofNull
Ifaprogramisreturningacollectionwhichdoesnothaveanyvalue,makesureanEmptycollectionisreturnedratherthanNullelements.This
savesalotofifelsetestingonNullElements.
1 publicclassgetLocationName{
2 return(null==cityName?"":cityName);
3 }

2.UseStringscarefully
IftwoStringsareconcatenatedusing+operatorinaforloop,thenitcreatesanewStringObject,everytime.Thiscauseswastageof
memoryandincreasesperformancetime.Also,whileinstantiatingaStringObject,constructorsshouldbeavoidedandinstantiationshould

JOIN US

With 1,240,600
uniquevisitorsand
500 authorswe
placedamongthe
relatedsitesaroun
Constantlybeingo
lookoutforpartne
encourageyouto
SoIfyouhaveab
uniqueandinterestingcontentthenyoush
checkoutourJCGpartnersprogram.You
beaguestwriterforJavaCodeGeeksa
yourwritingskills!

http://www.javacodegeeks.com/2015/06/javaprogrammingtipsbestpracticesbeginners.html?utm_content=bufferd71a7&utm_medium=social&utm_so

1/16

10/3/2015

30JavaProgrammingTipsandBestPracticesforBeginners|JavaCodeGeeks

happendirectly.Forexample:
1
2
3
4
5

//SlowerInstantiation
Stringbad=newString("Yetanotherstringobject");

//FasterInstantiation
Stringgood="Yetanotherstringobject"

3.AvoidunnecessaryObjects
Oneofthemostexpensiveoperations(intermsofMemoryUtilization)inJavaisObjectCreation.ThusitisrecommendedthatObjectsshould
onlybecreatedorinitializedifnecessary.Followingcodegivesanexample:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16

importjava.util.ArrayList;
importjava.util.List;

publicclassEmployees{

privateListEmployees;

publicListgetEmployees(){

//initializeonlywhenrequired
if(null==Employees){
Employees=newArrayList();
}
returnEmployees;
}
}

4.DilemmabetweenArrayandArrayList
DevelopersoftenfinditdifficulttodecideiftheyshouldgoforArraytypedatastructureofArrayListtype.Theybothhavetheirstrengthsand
weaknesses.Thechoicereallydependsontherequirements.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

importjava.util.ArrayList;

publicclassarrayVsArrayList{

publicstaticvoidmain(String[]args){
int[]myArray=newint[6];
myArray[7]=10;//ArraysOutOfBoundException

//DeclarationofArrayList.AddandRemoveofelementsiseasy.
ArrayList<Integer>myArrayList=newArrayList<>();
myArrayList.add(1);
myArrayList.add(2);
myArrayList.add(3);
myArrayList.add(4);
myArrayList.add(5);
myArrayList.remove(0);

for(inti=0;i<myArrayList.size();i++){
System.out.println("Element:"+myArrayList.get(i));
}

//MultidimensionalArray
int[][][]multiArray=newint[3][3][3];
}
}

1. ArrayshavefixedsizebutArrayListshavevariablesizes.SincethesizeofArrayisfixed,thememorygetsallocatedatthetimeof
declarationofArraytypevariable.Hence,Arraysareveryfast.Ontheotherhand,ifwearenotawareofthesizeofthedata,then
ArrayListisMoredatawillleadtoArrayOutOfBoundExceptionandlessdatawillcausewastageofstoragespace.

CAREER OPPORTUNITIES
SeniorJavaDeveloperMortgage...
BankofAmericaPlano,TX

ChildInformationTechnologyDeveloper.
HPAustin,TX

JavaSoftwareEngineer
DeloitteReston,VA

SENIORTECHNOLOGYARCHITECT(J
PLATTSNewYork,NY

VPSeniorJavaDeveloper\TechLeadw
CitiTampa,FL

PrincipalSoftwareEngineer
BOEINGAnnapolisJunction,MD

EntryLevelApplicationManagement...
FordMotorCompanyDearborn,MI

J2EEApplicationDeveloper
TAPE,LLCAdelphi,MD

ITApplicationAdministrationAnalyst
CVSHealthRichardson,TX

2. ItismucheasiertoAddorRemoveelementsfromArrayListthanArray

ITAnalystII/JavaApplication...

3. ArraycanbemultidimensionalbutArrayListcanbeonlyonedimension.

StateofUtahSaltLakeCounty,UT

5.WhenFinallydoesnotgetexecutedwithTry
Considerfollowingcodesnippet:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16

publicclassshutDownHooksDemo{
publicstaticvoidmain(String[]args){
for(inti=0;i<5;i++)
{
try{
if(i==4){
System.out.println("InsideTryBlock.ExitingwithoutexecutingFinallyblock.");
System.exit(0);
}
}
finally{
System.out.println("InsideFinallyBlock.");
}
}
}
}

12345678910Next

what:
title,keywords

where:
city,state,orzip

FindJobs

Fromtheprogram,itlookslikeprintlninsidefinallyblockwillbeexecuted5times.Butiftheprogramisexecuted,theuserwillfindthat
finallyblockiscalledonly4times.Inthefifthiteration,exitfunctioniscalledandfinallynevergetscalledthefifthtime.Thereasonis
System.exithaltsexecutionofalltherunningthreadsincludingthecurrentone.Evenfinallyblockdoesnotgetexecutedaftertrywhenexitis
executed.
WhenSystem.exitiscalled,JVMperformstwocleanuptasksbeforeshutdown:
First,itexecutesalltheshutdownhookswhichhavebeenregisteredwithRuntime.addShutdownHook.Thisisveryusefulbecauseitreleases

http://www.javacodegeeks.com/2015/06/javaprogrammingtipsbestpracticesbeginners.html?utm_content=bufferd71a7&utm_medium=social&utm_so

2/16

10/3/2015

30JavaProgrammingTipsandBestPracticesforBeginners|JavaCodeGeeks

theresourcesexternaltoJVM.
SecondisrelatedtoFinalizers.EitherSystem.runFinalizersOnExitorRuntime.runFinalizersOnExit.Theuseoffinalizershasbeendeprecated
fromalongtime.Finalizerscanrunonliveobjectswhiletheyarebeingmanipulatedbyotherthreads.Thisresultsinundesirableresultsor
eveninadeadlock.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

publicclassshutDownHooksDemo{

publicstaticvoidmain(String[]args){
for(inti=0;i<5;i++)
{
finalintfinal_i=i;
try{
Runtime.getRuntime().addShutdownHook(
newThread(){
publicvoidrun(){
if(final_i==4){
System.out.println("InsideTryBlock.Exitingwithoutexecuting
Finallyblock.");
System.exit(0);
}
}
});
}
finally{
System.out.println("InsideFinallyBlock.");
}

}
}
}

6.CheckOddity
HavealookatthelinesofcodebelowanddetermineiftheycanbeusedtopreciselyidentifyifagivennumberisOdd?
1 publicbooleanoddOrNot(intnum){
2 returnnum%2==1;
3 }
Theselinesseemcorrectbuttheywillreturnincorrectresultsoneofeveryfourtimes(Statisticallyspeaking).ConsideranegativeOddnumber,
theremainderofdivisionwith2willnotbe1.So,thereturnedresultwillbefalsewhichisincorrect!
Thiscanbefixedasfollows:
1 publicbooleanoddOrNot(intnum){
2 return(num&1)!=0;
3 }
Usingthiscode,notonlyistheproblemofnegativeoddnumberssolved,butthiscodeisalsohighlyoptimized.Since,ArithmeticandLogical
operationsaremuchfastercomparedtodivisionandmultiplication,theresultsareachievedfastersoinsecondsnippet.

7.Differencebetweensinglequotesanddoublequotes
1
2
3
4
5
6

publicclassHaha{
publicstaticvoidmain(Stringargs[]){
System.out.print("H"+"a");
System.out.print('H'+'a');
}
}

Fromthecode,itwouldseemreturnHaHaisreturned,butitactuallyreturnsHa169.Thereasonisthatifdoublequotesareused,the
charactersaretreatedasastringbutincaseofsinglequotes,thecharvaluedoperands(Handa)tointvaluesthroughaprocessknown
aswideningprimitiveconversion.Afterintegerconversion,thenumbersareaddedandreturn169.

8.AvoidingMemoryleaksbysimpletricks
Memoryleaksoftencauseperformancedegradationofsoftware.Since,Javamanagesmemoryautomatically,thedevelopersdonothave
muchcontrol.Buttherearestillsomestandardpracticeswhichcanbeusedtoprotectfrommemoryleakages.
Alwaysreleasedatabaseconnectionswhenqueryingiscomplete.
TrytouseFinallyblockasoftenpossible.
ReleaseinstancesstoredinStaticTables.

9.AvoidingDeadlocksinJava
Deadlockscanoccurformanydifferentreasons.Thereisnosinglerecipetoavoiddeadlocks.Normallydeadlocksoccurwhenone
synchronizedobjectiswaitingforlockonresourceslockedbyanothersynchronizedobject.
Tryrunningthebelowprogram.ThisprogramdemonstratesaDeadlock.Thisdeadlockarisesbecauseboththethreadsarewaitingforthe
resourceswhicharegrabbedbyotherthread.Theybothkeepwaitingandnoonereleases.
01
02
03
04
05
06
07
08
09

publicclassDeadlockDemo{
publicstaticObjectaddLock=newObject();
publicstaticObjectsubLock=newObject();

publicstaticvoidmain(Stringargs[]){

MyAdditionThreadadd=newMyAdditionThread();
MySubtractionThreadsub=newMySubtractionThread();
add.start();
sub.start();

http://www.javacodegeeks.com/2015/06/javaprogrammingtipsbestpracticesbeginners.html?utm_content=bufferd71a7&utm_medium=social&utm_so

3/16

10/3/2015

30JavaProgrammingTipsandBestPracticesforBeginners|JavaCodeGeeks

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

sub.start();
}
privatestaticclassMyAdditionThreadextendsThread{
publicvoidrun(){
synchronized(addLock){
inta=10,b=3;
intc=a+b;
System.out.println("AdditionThread:"+c);
System.out.println("HoldingFirstLock...");
try{Thread.sleep(10);}
catch(InterruptedExceptione){}
System.out.println("AdditionThread:WaitingforAddLock...");
synchronized(subLock){
System.out.println("Threads:HoldingAddandSubLocks...");
}
}
}
}
privatestaticclassMySubtractionThreadextendsThread{
publicvoidrun(){
synchronized(subLock){
inta=10,b=3;
intc=ab;
System.out.println("SubtractionThread:"+c);
System.out.println("HoldingSecondLock...");
try{Thread.sleep(10);}
catch(InterruptedExceptione){}
System.out.println("SubtractionThread:WaitingforSubLock...");
synchronized(addLock){
System.out.println("Threads:HoldingAddandSubLocks...");
}
}
}
}
}

Output:
1
2
3
4
5
6
7

=====
AdditionThread:13
SubtractionThread:7
HoldingFirstLock...
HoldingSecondLock...
AdditionThread:WaitingforAddLock...
SubtractionThread:WaitingforSubLock...

Butiftheorderinwhichthethreadsarecalledischanged,thedeadlockproblemisresolved.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

publicclassDeadlockSolutionDemo{
publicstaticObjectaddLock=newObject();
publicstaticObjectsubLock=newObject();

publicstaticvoidmain(Stringargs[]){

MyAdditionThreadadd=newMyAdditionThread();
MySubtractionThreadsub=newMySubtractionThread();
add.start();
sub.start();
}

privatestaticclassMyAdditionThreadextendsThread{
publicvoidrun(){
synchronized(addLock){
inta=10,b=3;
intc=a+b;
System.out.println("AdditionThread:"+c);
System.out.println("HoldingFirstLock...");
try{Thread.sleep(10);}
catch(InterruptedExceptione){}
System.out.println("AdditionThread:WaitingforAddLock...");
synchronized(subLock){
System.out.println("Threads:HoldingAddandSubLocks...");
}
}
}
}

privatestaticclassMySubtractionThreadextendsThread{
publicvoidrun(){
synchronized(addLock){
inta=10,b=3;
intc=ab;
System.out.println("SubtractionThread:"+c);
System.out.println("HoldingSecondLock...");
try{Thread.sleep(10);}
catch(InterruptedExceptione){}
System.out.println("SubtractionThread:WaitingforSubLock...");
synchronized(subLock){
System.out.println("Threads:HoldingAddandSubLocks...");
}
}
}
}
}

Output:
1
2
3
4
5
6
7
8
9

=====
AdditionThread:13
HoldingFirstLock...
AdditionThread:WaitingforAddLock...
Threads:HoldingAddandSubLocks...
SubtractionThread:7
HoldingSecondLock...
SubtractionThread:WaitingforSubLock...
Threads:HoldingAddandSubLocks...

10.ReservememoryforJava

http://www.javacodegeeks.com/2015/06/javaprogrammingtipsbestpracticesbeginners.html?utm_content=bufferd71a7&utm_medium=social&utm_so

4/16

10/3/2015

30JavaProgrammingTipsandBestPracticesforBeginners|JavaCodeGeeks

10.ReservememoryforJava
SomeoftheJavaapplicationscanbehighlyCPUintensiveaswellastheyneedalotofRAM.Suchapplicationsgenerallyrunslowbecauseofa
highRAMrequirement.Inordertoimproveperformanceofsuchapplications,RAMisreservedforJava.So,forexample,ifwehaveaTomcat
webserverandithas10GBofRAM.Ifwelike,wecanallocateRAMforJavaonthismachineusingthefollowingcommand:
1 exportJAVA_OPTS="$JAVA_OPTSXms5000mXmx6000mXX:PermSize=1024mXX:MaxPermSize=2048m"
Xms=Minimummemoryallocationpool
Xmx=Maximummemoryallocationpool
XX:PermSize=InitialsizethatwillbeallocatedduringstartupoftheJVM
XX:MaxPermSize=MaximumsizethatcanbeallocatedduringstartupoftheJVM

11.HowtotimeoperationsinJava
TherearetwostandardwaystotimeoperationsinJava:System.currentTimeMillis()andSystem.nanoTime()Thequestionis,whichof
thesetochooseandunderwhatcircumstances.Inprinciple,theybothperformthesameactionbutaredifferentinthefollowingways:
1. System.currentTimeMillistakessomewherebetween1/1000thofasecondto15/1000thofasecond(dependingonthesystem)but
System.nanoTime()takesaround1/1000,000thofasecond(1,000nanos)
2. System.currentTimeMillistakesafewclockcyclestoperformReadOperation.Ontheotherhand,System.nanoTime()takes100+clock
cycles.
3. System.currentTimeMillisreflectsAbsoluteTime(Numberofmillissince1Jan197000:00(EpochTime))butSystem.nanoTime()doesnot
necessarilyrepresentanyreferencepoint.

12.ChoicebetweenFloatandDouble
Datatype

Bytesused

Significantfigures(decimal)

Float

Double

15

Doubleisoftenpreferredoverfloatinsoftwarewhereprecisionisimportantbecauseofthefollowingreasons:
MostprocessorstakenearlythesameamountofprocessingtimetoperformoperationsonFloatandDouble.Doubleoffersfarmoreprecision
inthesameamountofcomputationtime.

13.Computationofpower
Tocomputepower(^),javaperformsExclusiveOR(XOR).Inordertocomputepower,Javaofferstwooptions:
1. Multiplication:
1
2
3
4
5

doublesquare=doublea*doublea;//Optimized
doublecube=doublea*doublea*doublea;//Nonoptimized
doublecube=doublea*doublesquare;//Optimized
doublequad=doublea*doublea*doublea*doublea;//Nonoptimized
doublequad=doublesquare*doublesquare;//Optimized

2. pow(doublebase,doubleexponent):powmethodisusedtocalculatewheremultiplicationisnotpossible(base^exponent)
1 doublecube=Math.pow(base,exponent);
Math.powshouldbeusedONLYwhennecessary.Forexample,exponentisafractionalvalue.ThatisbecauseMath.pow()methodistypically
around300600timesslowerthanamultiplication.

14.HowtohandleNullPointerExceptions
NullPointerExceptionsarequitecommoninJava.ThisexceptionoccurswhenwetrytocallamethodonaNullObjectReference.For
example,
1 intnoOfStudents=school.listStudents().count;
Ifintheaboveexample,ifgetaNullPointerException,theneitherschoolisnullorlistStudents()isNull.ItsagoodideatocheckNullsearlyso
thattheycanbeeliminated.
1
2
3
4

privateintgetListOfStudents(File[]files){
if(files==null)
thrownewNullPointerException("Filelistcannotbenull");
}

15.EncodeinJSON
JSON(JavaScriptObjectNotation)issyntaxforstoringandexchangingdata.JSONisaneasiertousealternativetoXML.Jsonisbecoming
verypopularoverinternetthesedaysbecauseofitspropertiesandlightweight.AnormaldatastructurecanbeencodedintoJSONandshared
acrosswebpageseasily.Beforebeginningtowritecode,aJSONparserhastobeinstalled.Inbelowexamples,wehaveusedjson.simple
(https://code.google.com/p/jsonsimple/).
BelowisabasicexampleofEncodingintoJSON:
01 importorg.json.simple.JSONObject;
02 importorg.json.simple.JSONArray;

http://www.javacodegeeks.com/2015/06/javaprogrammingtipsbestpracticesbeginners.html?utm_content=bufferd71a7&utm_medium=social&utm_so

5/16

10/3/2015

30JavaProgrammingTipsandBestPracticesforBeginners|JavaCodeGeeks

03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21

publicclassJsonEncodeDemo{

publicstaticvoidmain(String[]args){

JSONObjectobj=newJSONObject();
obj.put("NovelName","Godaan");
obj.put("Author","MunshiPremchand");

JSONArraynovelDetails=newJSONArray();
novelDetails.add("Language:Hindi");
novelDetails.add("YearofPublication:1936");
novelDetails.add("Publisher:LokmanyaPress");

obj.put("NovelDetails",novelDetails);

System.out.print(obj);
}
}

Output:
1 {"NovelName":"Godaan","NovelDetails":["Language:Hindi","YearofPublication:1936","Publisher:Lokmanya
Press"],"Author":"MunshiPremchand"}

16.DecodefromJSON
InordertodecodeJSON,thedevelopermustbeawareoftheschema.Thedetailscanbefoundinbelowexample:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

importjava.io.FileNotFoundException;
importjava.io.FileReader;
importjava.io.IOException;
importjava.util.Iterator;

importorg.json.simple.JSONArray;
importorg.json.simple.JSONObject;
importorg.json.simple.parser.JSONParser;
importorg.json.simple.parser.ParseException;

publicclassJsonParseTest{

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

publicstaticvoidmain(String[]args){

try{
//readthejsonfile
FileReaderreader=newFileReader(filePath);
JSONParserjsonParser=newJSONParser();
JSONObjectjsonObject=(JSONObject)jsonParser.parse(reader);

//getanumberfromtheJSONobject
Longid=(Long)jsonObject.get("id");
System.out.println("Theidis:"+id);

//getaStringfromtheJSONobject
Stringtype=(String)jsonObject.get("type");
System.out.println("Thetypeis:"+type);

//getaStringfromtheJSONobject
Stringname=(String)jsonObject.get("name");
System.out.println("Thenameis:"+name);

//getanumberfromtheJSONobject
Doubleppu=(Double)jsonObject.get("ppu");
System.out.println("ThePPUis:"+ppu);

//getanarrayfromtheJSONobject
System.out.println("Batters:");
JSONArraybatterArray=(JSONArray)jsonObject.get("batters");
Iteratori=batterArray.iterator();
//takeeachvaluefromthejsonarrayseparately
while(i.hasNext()){
JSONObjectinnerObj=(JSONObject)i.next();
System.out.println("ID"+innerObj.get("id")+
"type"+innerObj.get("type"));
}

//getanarrayfromtheJSONobject
System.out.println("Topping:");
JSONArraytoppingArray=(JSONArray)jsonObject.get("topping");
Iteratorj=toppingArray.iterator();
//takeeachvaluefromthejsonarrayseparately
while(j.hasNext()){
JSONObjectinnerObj=(JSONObject)j.next();
System.out.println("ID"+innerObj.get("id")+
"type"+innerObj.get("type"));
}

}catch(FileNotFoundExceptionex){
ex.printStackTrace();
}catch(IOExceptionex){
ex.printStackTrace();
}catch(ParseExceptionex){
ex.printStackTrace();
}catch(NullPointerExceptionex){
ex.printStackTrace();
}

jsonDemoFile.json

http://www.javacodegeeks.com/2015/06/javaprogrammingtipsbestpracticesbeginners.html?utm_content=bufferd71a7&utm_medium=social&utm_so

6/16

10/3/2015

30JavaProgrammingTipsandBestPracticesforBeginners|JavaCodeGeeks

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23

{
"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'sFood"}
],
"topping":
[
{"id":5001,"type":"None"},
{"id":5002,"type":"Glazed"},
{"id":5005,"type":"Sugar"},
{"id":5007,"type":"PowderedSugar"},
{"id":5006,"type":"ChocolatewithSprinkles"},
{"id":5003,"type":"Chocolate"},
{"id":5004,"type":"Maple"}
]
}

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17

Theidis:1
Thetypeis:donut
Thenameis:Cake
ThePPUis:0.55
Batters:
ID1001typeRegular
ID1002typeChocolate
ID1003typeBlueberry
ID1004typeDevil'sFood
Topping:
ID5001typeNone
ID5002typeGlazed
ID5005typeSugar
ID5007typePowderedSugar
ID5006typeChocolatewithSprinkles
ID5003typeChocolate
ID5004typeMaple

17.SimpleStringSearch
JavaoffersaLibrarymethodcalledindexOf().ThismethodisusedwithStringObjectanditreturnsthepositionofindexofdesiredstring.If
thestringisnotfoundthen1isreturned.
01
02
03
04
05
06
07
08
09
10
11
12
13

publicclassStringSearch{

publicstaticvoidmain(String[]args){
StringmyString="IamaString!";

if(myString.indexOf("String")==1){
System.out.println("StringnotFound!");
}
else{
System.out.println("Stringfoundat:"+myString.indexOf("String"));
}
}
}

18.Listingcontentofadirectory
Inordertolistthecontentsofadirectory,belowprogramcanbeused.Thisprogramsimplyreceivesthenamesoftheallsubdirectoryand
filesinafolderinanArrayandthenthatarrayissequentiallytraversedtolistallthecontents.
01
02
03
04
05
06
07
08
09
10
11
12
13
14

importjava.io.*;

publicclassListContents{
publicstaticvoidmain(String[]args){
Filefile=newFile("//home//user//Documents/");
String[]files=file.list();

System.out.println("Listingcontentsof"+file.getPath());
for(inti=0;i<files.length;i++)
{
System.out.println(files[i]);
}
}
}

19.ASimpleIO
Inordertoreadfromafileandwritetoafile,JavaoffersFileInputStreamandFileOutputStreamClasses.FileInputStreamsconstructor
acceptsfilepathofInputFileasargumentandcreatesFileInputStream.Similarly,FileOutputStreamsconstructoracceptsfilepathofOutput
FileasargumentandcreatesFileOutputStream.Afterthefilehandlingisdone,itsimportanttoclosethestreams.
01
02
03
04
05
06
07
08
09
10
11
12
13
14

importjava.io.*;

publicclassmyIODemo{
publicstaticvoidmain(Stringargs[])throwsIOException{
FileInputStreamin=null;
FileOutputStreamout=null;

try{
in=newFileInputStream("//home//user//Documents//InputFile.txt");
out=newFileOutputStream("//home//user//Documents//OutputFile.txt");

intc;
while((c=in.read())!=1){
out.write(c);
}

http://www.javacodegeeks.com/2015/06/javaprogrammingtipsbestpracticesbeginners.html?utm_content=bufferd71a7&utm_medium=social&utm_so

7/16

10/3/2015
15
16
17
18
19
20
21
22
23
24
25

30JavaProgrammingTipsandBestPracticesforBeginners|JavaCodeGeeks
}
}finally{
if(in!=null){
in.close();
}
if(out!=null){
out.close();
}
}
}
}

20.ExecutingashellcommandfromJava
JavaoffersRuntimeclasstoexecuteShellCommands.Sincetheseareexternalcommands,exceptionhandlingisreallyimportant.Inbelow
example,weillustratethiswithasimpleexample.WearetryingtoopenaPDFfilefromShellcommand.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

importjava.io.BufferedReader;
importjava.io.InputStream;
importjava.io.InputStreamReader;

publicclassShellCommandExec{

publicstaticvoidmain(String[]args){
StringgnomeOpenCommand="gnomeopen//home//user//Documents//MyDoc.pdf";

try{
Runtimert=Runtime.getRuntime();
ProcessprocessObj=rt.exec(gnomeOpenCommand);

InputStreamstdin=processObj.getErrorStream();
InputStreamReaderisr=newInputStreamReader(stdin);
BufferedReaderbr=newBufferedReader(isr);

Stringmyoutput="";

while((myoutput=br.readLine())!=null){
myoutput=myoutput+"\n";
}
System.out.println(myoutput);
}
catch(Exceptione){
e.printStackTrace();
}
}
}

21.UsingRegex
SummaryofRegularExpressionConstructs(Source:OracleWebsite)
Characters
x

Thecharacterx

\\

Thebackslashcharacter

\0n

Thecharacterwithoctalvalue0n(0<=n<=7)

\0nn

Thecharacterwithoctalvalue0nn(0<=n<=7)

\0mnn

Thecharacterwithoctalvalue0mnn(0<=m<=3,0<=n<=7)

\xhh

Thecharacterwithhexadecimalvalue0xhh

\uhhhh

Thecharacterwithhexadecimalvalue0xhhhh

\x{hh}

Thecharacterwithhexadecimalvalue0xhh(Character.MIN_CODE_POINT<=0xhh<=
Character.MAX_CODE_POINT)

\t

Thetabcharacter(\u0009)

\n

Thenewline(linefeed)character(\u000A)

\r

Thecarriagereturncharacter(\u000D)

\f

Theformfeedcharacter(\u000C)

\a

Thealert(bell)character(\u0007)

\e

Theescapecharacter(\u001B)

\cx

Thecontrolcharactercorrespondingtox

Characterclasses
[abc]

a,b,orc(simpleclass)

[^abc]

Anycharacterexcepta,b,orc(negation)

[azAZ]

athroughzorAthroughZ,inclusive(range)

[ad[mp]]

athroughd,ormthroughp:[admp](union)

[az&&[def]]

d,e,orf(intersection)

[az&&[^bc]]

athroughz,exceptforbandc:[adz](subtraction)

[az&&[^mp]]

athroughz,andnotmthroughp:[alqz](subtraction)

http://www.javacodegeeks.com/2015/06/javaprogrammingtipsbestpracticesbeginners.html?utm_content=bufferd71a7&utm_medium=social&utm_so

8/16

10/3/2015

30JavaProgrammingTipsandBestPracticesforBeginners|JavaCodeGeeks

Predefinedcharacterclasses
.

Anycharacter(mayormaynotmatchlineterminators)

\d

Adigit:[09]

\D

Anondigit:[^09]

\s

Awhitespacecharacter:[\t\n\x0B\f\r]

\S

Anonwhitespacecharacter:[^\s]

\w

Awordcharacter:[azAZ_09]

\W

Anonwordcharacter:[^\w]

Boundarymatchers
^

Thebeginningofaline

Theendofaline

\b

Awordboundary

\B

Anonwordboundary

\A

Thebeginningoftheinput

\G

Theendofthepreviousmatch

\Z

Theendoftheinputbutforthefinalterminator,ifany

\z

Theendoftheinput

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

importjava.util.regex.Matcher;
importjava.util.regex.Pattern;

publicclassRegexMatches
{
privatestaticStringpattern="^[_AZaz09]+(\\.[_AZaz09]+)*@[AZaz09]+(\\.[AZaz09]+)*
(\\.[AZaz]{2,})$";
privatestaticPatternmypattern=Pattern.compile(pattern);

publicstaticvoidmain(Stringargs[]){

StringvalEmail1="testemail@domain.com";
StringinvalEmail1="....@domain.com";
StringinvalEmail2=".$$%%@domain.com";
StringvalEmail2="test.email@domain.com";

System.out.println("IsEmailID1valid?"+validateEMailID(valEmail1));
System.out.println("IsEmailID1valid?"+validateEMailID(invalEmail1));
System.out.println("IsEmailID1valid?"+validateEMailID(invalEmail2));
System.out.println("IsEmailID1valid?"+validateEMailID(valEmail2));

publicstaticbooleanvalidateEMailID(StringemailID){
Matchermtch=mypattern.matcher(emailID);
if(mtch.matches()){
returntrue;
}
returnfalse;
}
}

22.SimpleJavaSwingExample
WiththehelpofJavaSwingGUIcanbecreated.JavaoffersJavaxwhichcontainsswing.TheGUIusingswingbeginwithextendingJFrame.
BoxesareaddedsotheycancontainGUIcomponentslikeButton,RadioButton,Textbox,etc.TheseboxesaresetontopofContainer.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

importjava.awt.*;
importjavax.swing.*;

publicclassSwingsDemoextendsJFrame
{
publicSwingsDemo()
{
Stringpath="//home//user//Documents//images";
ContainercontentPane=getContentPane();
contentPane.setLayout(newFlowLayout());

BoxmyHorizontalBox=Box.createHorizontalBox();
BoxmyVerticleBox=Box.createVerticalBox();

myHorizontalBox.add(newJButton("MyButton1"));
myHorizontalBox.add(newJButton("MyButton2"));
myHorizontalBox.add(newJButton("MyButton3"));

myVerticleBox.add(newJButton(newImageIcon(path+"//Image1.jpg")));
myVerticleBox.add(newJButton(newImageIcon(path+"//Image2.jpg")));
myVerticleBox.add(newJButton(newImageIcon(path+"//Image3.jpg")));

contentPane.add(myHorizontalBox);
contentPane.add(myVerticleBox);

pack();
setVisible(true);
}

publicstaticvoidmain(Stringargs[]){
newSwingsDemo();
}
}

23.PlayasoundwithJava

http://www.javacodegeeks.com/2015/06/javaprogrammingtipsbestpracticesbeginners.html?utm_content=bufferd71a7&utm_medium=social&utm_so

9/16

10/3/2015

30JavaProgrammingTipsandBestPracticesforBeginners|JavaCodeGeeks

23.PlayasoundwithJava
PlayingsoundisacommonrequirementinJava,especiallyalongwithGames.
ThisdemoexplainshowtoplayanAudiofilealongwithJavacode.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

importjava.io.*;
importjava.net.URL;
importjavax.sound.sampled.*;
importjavax.swing.*;

//ToplaysoundusingClip,theprocessneedtobealive.
//Hence,weuseaSwingapplication.
publicclassplaySoundDemoextendsJFrame{

//Constructor
publicplaySoundDemo(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("PlaySoundDemo");
this.setSize(300,200);
this.setVisible(true);

try{
URLurl=this.getClass().getResource("MyAudio.wav");
AudioInputStreamaudioIn=AudioSystem.getAudioInputStream(url);
Clipclip=AudioSystem.getClip();
clip.open(audioIn);
clip.start();
}catch(UnsupportedAudioFileExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}catch(LineUnavailableExceptione){
e.printStackTrace();
}
}

publicstaticvoidmain(String[]args){
newplaySoundDemo();
}
}

24.PDFExport
ExportatabletoPDFisacommonrequirementinJavaprograms.Usingitextpdf,itbecomesreallyeasytoexportPDF.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

importjava.io.FileOutputStream;
importcom.itextpdf.text.Document;
importcom.itextpdf.text.Paragraph;
importcom.itextpdf.text.pdf.PdfPCell;
importcom.itextpdf.text.pdf.PdfPTable;
importcom.itextpdf.text.pdf.PdfWriter;

publicclassDrawPdf{

publicstaticvoidmain(String[]args)throwsException{
Documentdocument=newDocument();
PdfWriter.getInstance(document,newFileOutputStream("Employee.pdf"));
document.open();

Paragraphpara=newParagraph("EmployeeTable");
para.setSpacingAfter(20);
document.add(para);

PdfPTabletable=newPdfPTable(3);
PdfPCellcell=newPdfPCell(newParagraph("FirstName"));

table.addCell(cell);
table.addCell("LastName");
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.SendingEmailfromJavaCode
SendingemailfromJavaissimple.WeneedtoinstallJavaMailJarandsetitspathinourprogramsclasspath.Thebasicpropertiesaresetin
thecodeandwearegoodtosendemailasmentionedinthecodebelow:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15

importjava.util.*;
importjavax.mail.*;
importjavax.mail.internet.*;

publicclassSendEmail
{
publicstaticvoidmain(String[]args)
{
Stringto="recipient@gmail.com";
Stringfrom="sender@gmail.com";
Stringhost="localhost";

Propertiesproperties=System.getProperties();
properties.setProperty("mail.smtp.host",host);
Sessionsession=Session.getDefaultInstance(properties);

http://www.javacodegeeks.com/2015/06/javaprogrammingtipsbestpracticesbeginners.html?utm_content=bufferd71a7&utm_medium=social&utm_s

10/16

10/3/2015
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

30JavaProgrammingTipsandBestPracticesforBeginners|JavaCodeGeeks

try{
MimeMessagemessage=newMimeMessage(session);
message.setFrom(newInternetAddress(from));

message.addRecipient(Message.RecipientType.TO,newInternetAddress(to));

message.setSubject("MyEmailSubject");
message.setText("MyMessageBody");
Transport.send(message);
System.out.println("Sentsuccessfully!");
}
catch(MessagingExceptionex){
ex.printStackTrace();
}
}
}

26.Measuringtime
Manyapplicationsrequireaveryprecisetimemeasurement.Forthispurpose,JavaprovidesstaticmethodsinSystemclass:
1. currentTimeMillis():ReturnscurrenttimeinMilliSecondssinceEpochTime,inLong.
1 longstartTime=System.currentTimeMillis();
2 longestimatedTime=System.currentTimeMillis()startTime;
2. nanoTime():Returnsthecurrentvalueofthemostpreciseavailablesystemtimer,innanoseconds,inlong.nanoTime()ismeantfor
measuringrelativetimeintervalinsteadofprovidingabsolutetiming.
1 longstartTime=System.nanoTime();
2 longestimatedTime=System.nanoTime()startTime;

27.RescaleImage
AnimagecanrescaledusingAffineTransform.Firstofall,ImageBufferofinputimageiscreatedandthenscaledimageisrendered.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16

importjava.awt.Graphics2D;
importjava.awt.geom.AffineTransform;
importjava.awt.image.BufferedImage;
importjava.io.File;
importjavax.imageio.ImageIO;

publicclassRescaleImage{
publicstaticvoidmain(String[]args)throwsException{
BufferedImageimgSource=ImageIO.read(newFile("images//Image3.jpg"));
BufferedImageimgDestination=newBufferedImage(100,100,BufferedImage.TYPE_INT_RGB);
Graphics2Dg=imgDestination.createGraphics();
AffineTransformaffinetransformation=AffineTransform.getScaleInstance(2,2);
g.drawRenderedImage(imgSource,affinetransformation);
ImageIO.write(imgDestination,"JPG",newFile("outImage.jpg"));
}
}

28.CapturingMouseHoverCoordinates
ByimplementingMouseMotionListnerInterface,mouseeventscanbecaptured.WhenthemouseisenteredinaspecificregionMouseMoved
Eventistriggeredandmotioncoordinatescanbecaptured.Thefollowingexampleexplainsit:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

importjava.awt.event.*;
importjavax.swing.*;

publicclassMouseCaptureDemoextendsJFrameimplementsMouseMotionListener
{
publicJLabelmouseHoverStatus;

publicstaticvoidmain(Stringargs[])
{
newMouseCaptureDemo();
}

MouseCaptureDemo()
{
setSize(500,500);
setTitle("FramedisplayingCoordinatesofMouseMotion");

mouseHoverStatus=newJLabel("NoMouseHoverDetected.",JLabel.CENTER);
add(mouseHoverStatus);
addMouseMotionListener(this);
setVisible(true);
}

publicvoidmouseMoved(MouseEvente)
{
mouseHoverStatus.setText("MouseCursorCoordinates=>X:"+e.getX()+"|Y:"+e.getY());
}

publicvoidmouseDragged(MouseEvente)
{}
}

29.FileOutputStreamVs.FileWriter
FilewritinginJavaisdonemainlyintwoways:FileOutputStreamandFileWriter.Sometimes,developersstruggletochooseoneamongthem.
Thisexamplehelpstheminchoosingwhichoneshouldbeusedundergivenrequirements.First,letstakealookattheimplementationpart:

UsingFileOutputStream:
Filefoutput=newFile(file_location_string);

http://www.javacodegeeks.com/2015/06/javaprogrammingtipsbestpracticesbeginners.html?utm_content=bufferd71a7&utm_medium=social&utm_s

11/16

10/3/2015

30JavaProgrammingTipsandBestPracticesforBeginners|JavaCodeGeeks
1
2
3
4

Filefoutput=newFile(file_location_string);
FileOutputStreamfos=newFileOutputStream(foutput);
BufferedWriteroutput=newBufferedWriter(newOutputStreamWriter(fos));
output.write("BufferedContent");

UsingFileWriter:
1 FileWriterfstream=newFileWriter(file_location_string);
2 BufferedWriteroutput=newBufferedWriter(fstream);
3 output.write("BufferedContent");
AccordingtoJavaAPIspecifications:

FileOutputStreamismeantforwritingstreamsofrawbytessuchasimagedata.Forwritingstreamsofcharacters,considerusing
FileWriter.

ThismakesitprettyclearthatforimagetypeofDataFileOutputStreamshouldbeusedandforTexttypeofdataFileWritershouldbeused.

AdditionalSuggestions
1.

UseCollections
Javaisshippedwithafewcollectionclassesforexample,Vector,Stack,Hashtable,Array.Thedevelopersareencouragedtouse
collectionsasextensivelyaspossibleforthefollowingreasons:
1. Useofcollectionsmakesthecodereusableandinteroperable.
2. Collectionsmakethecodemorestructured,easiertounderstandandmaintainable.
3. Outoftheboxcollectionclassesarewelltestedsothequalityofcodeisgood.

2.

1050500Rule
Inbigsoftwarepackages,maintainingcodebecomesverychallenging.Developerswhojoinfreshongoingsupportprojects,oftencomplain
about:MonolithicCode,SpaghettiCode.Thereisaverysimpleruletoavoidthatorkeepthecodecleanandmaintainable:1050500.
1. 10:Nopackagecanhavemorethan10classes.
2. 50:Nomethodcanhavemorethan50linesofcode.
3. 500:Noclasscanhavemorethan500linesofcode.

3.

SOLIDClassDesignPrinciples
SOLID(http://en.wikipedia.org/wiki/SOLID_%28objectoriented_design%29)isanacronymfordesignprinciplescoinedbyRobertMartin.
Accordingtothisrule:

4.

Rule

Description

Singleresponsibilityprinciple

Aclassshouldhaveoneandonlyonetask/responsibility.Ifclassisperformingmorethanone
task,itleadstoconfusion.

Open/closedprinciple

Thedevelopersshouldfocusmoreonextendingthesoftwareentitiesratherthanmodifying
them.

Liskovsubstitutionprinciple

Itshouldbepossibletosubstitutethederivedclasswithbaseclass.

Interfacesegregationprinciple

ItslikeSingleResponsibilityPrinciplebutapplicabletointerfaces.Eachinterfaceshouldbe
responsibleforaspecifictask.Thedevelopersshouldneedtoimplementmethodswhich
he/shedoesntneed.

Dependencyinversionprinciple

DependuponAbstractionsbutnotonconcretions.Thismeansthateachmoduleshouldbe
separatedfromotherusinganabstractlayerwhichbindsthemtogether.

UsageofDesignPatterns
DesignpatternshelpdeveloperstoincorporatebestSoftwareDesignPrinciplesintheirsoftware.Theyalsoprovidecommonplatformfor
developersacrosstheglobe.Theyprovidestandardterminologywhichmakesdeveloperstocollaborateandeasiertocommunicatetoeach
other.

5.

Documentideas
Neverjuststartwritingcode.Strategize,Prepare,Document,ReviewandImplementation.Firstofall,jotdownyourrequirements.Prepare
adesigndocument.Mentionassumptionsproperly.Getthedocumentspeerreviewedandtakeasignoffonthem.

6.

UseEqualsover==
==comparesobjectreferences,itcheckstoseeifthetwooperandspointtothesameobject(notequivalentobjects,thesameobject).On
theotherhand,equalsperformactualcomparisonoftwostrings.

7.

AvoidFloatingPointNumbers
Floatingpointnumbersshouldbeusedonlyiftheyareabsolutelynecessary.Forexample,representingRupeesandPaiseusingFloating
PointnumberscanbeProblematicBigDecimalshouldinsteadbepreferred.Floatingpointnumbersaremoreusefulinmeasurements.

BestResourcestolearnJava

http://www.javacodegeeks.com/2015/06/javaprogrammingtipsbestpracticesbeginners.html?utm_content=bufferd71a7&utm_medium=social&utm_s

12/16

You might also like