Monday, September 21, 2009

Exception propagation : Propagation of Uncaught exceptions

There are many important things to remember to catch an exception.Fir instance one must use catch or finally to catch the thrown exceptions in try block.Also remember that try will never work without either a catch or finally.This is a must follow condition.

So what happens to a exception which is not caught by any of the catch block, of course they keep looking for its handler (its always good to catch 'em) and if they failed to find one they just propagate from one method to the other and end up crashing the program.Whenever an exception is not caught by any catch block in the method then method is said to be ducking the exception.It also means that method passes its course of work to other method to handle the exception.The exception propagation follows call stack.I think you are now grown up and must know what a call stack means.Lets rewind the stack concept that a call stack is a stack where methods are placed in LIFO order based on method call.For example if yo have called method abc() from main() then main() method will be placed at bottom of the stack and the called method abc() will be on top.After the abc finish execution the abc() will be popped from the stack and main() will take pole position.

The above call stack concept also applies to the Exception propagation.Consider we have two methods a() and b().main() calls a() and after that a() calls method b().Now suppose the called method b() is facing heat from JVM and it resulted in exception then the exception will look for specific handler,if it failed to either specific handler or a superclass handler then it start to look in the calling method that is a().Here also it will follow the same procedure and if it again failed it will go to main() method and in the end if it again failed at the bottom of the stack then mate its ultimate law of nature that it has to die a horrible death,or it will produce a complete stack trace of the exception.Following figure shows how call stack woks and exception propagate"-




Make it even more clear by considering the following example:-

public class Exceptionpropagation{
public static void main(String[] a){
domore();
}
public void domore(){
doevenmore();
}
public void doevenmore(){
int x=10/0;
}
}

The produced will be in the order of stack call that is from code it is clear that the exception is generated from doevenmore() so it will be listed on top of stack trace and following the stack trace you can find out where actually the exception has happened.

The resulting exception would be and its stack trace :-
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at Exceptionpropagation.doevenmore(Exceptionpropagation.java:13)
at Exceptionpropagation.domore(Exceptionpropagation.java:10)
at Exceptionpropagation.main(Exceptionpropagation.java:7)
Process Exit...

Suggested Reading:-

Exception Handling Basics
Exceptions: try-catch part 1
Exceptions: try-catch part 2
Use of Finally
Exception Hierarchy
User defined exceptions
Exception Matching

Sponsored Listings:-

Play free trivia and test your skill

Read more...

Friday, September 18, 2009

Most Common Scoping errors commited by Novice Java Programmers

Scoping errors comes in various sizes and shapes.Novice Java programmers most often commit some silly mistakes which are undesirable.The most common mistake novice programmers commit is scoping errors which comes in many ways.One is happens when the variable is shadowed and two scopes overlap.It becomes very much difficult to identify the problem.The reason why scoping errors comes into effect is when programmer attempts to access a variable not in scope or visibility.There are few common mistakes which are explained below.Lets take a look:-

1.Attempting to access an instance variable from a static context (i.e. from main() method)

Since static variable can only be accessed from static context thus there is no way you can access the non-static instance variable in static context without a reference.For example:-

Class Scopetest{
int x=10;
public static void main(String a[]){
System.out.println(x++);
}
}

This will result in an error
Scopetest.java:4: non-static variable x cannot be referenced from a static context
System.out.println(x++);

Despite this you can use the instance of Scopetest class to access the variable as shown below:-

class Scopetest{
int x=10;
public static void main(String a[]){
System.out.println(new Scopetest().x++);
}
}

This will produce output as 10.
So,remember you can never ever access a non-static instance variable within a static context alone.You have to use the enclosing class instance.

2.Attempting to use a block variable after the code block is completed.
How often we commit this error,I guess everyone of us has faced it.So remember never ever try to invoke a variable which is ended its life.That is block variable lifetime is until the code block completes.As block finished execution the variable will also perish from memory,thus any reference out of this block result in a compiler slap!!!
Lets take a look at following example:-

class Scopetest{
public static void main(String a[]){
for(i=0;i<2;i++) style="font-style: italic;">.java:5: cannot find symbol
symbol : variable i
location: class Scopetest
if(i<3)>

3.Attempting to access a local variable from nested method.
When a method invokes another method then the calling method does not have access to the called methods variables and vice versa.For example:-If we have a method do1() which called by another method do2() then do1() cannot access the variables local to do2().It is evident from the following example:-

class Scopetest{
public static void main(String[] a){
Scopetest s = new Scopetest();
s.do2();
}
public void do2(){
int x = 4;
do1();
++x;
}
public void do1(){
x++;
}
}

The error which appears is:-
Scopetest.java:12: cannot find symbol
symbol : variable x
location: class Scopetest
x++;

So next time you go to the battlefield(programming) keep yourself armed with better knowledge and strategies of course here is to reduce the bug and make your program more readable.Keep in mind above mentioned errors and be a good programmer,and keep firing on the COMPILER!!!.

Suggested Links:-

Why Java does not support Multiple Inheritance
Why Java classes are not marked final
Variable Shadowing Complexities

Sponsored Link:-

Are you Intelligent Check!!

Read more...

Wednesday, September 9, 2009

Java Thread Basics || Learn Java Threads

Most of the functions in a computer needs various things to be done simultaneously.Like if we are playing a computer game then there are various things going on at the same time,like graphics,sound,gameplay,commands,scoring etc.Do you ever imagine how all this happens? The answer is it is done with the help of Threads.Threads are the sequence of computer instructions which carry out specific tasks.Now you will say that "wait this is the definition of a computer process isn't it".Yes you are absolutely right,but since the Threads are small unit of execution and they also have start and end and they complete a specific task so this definition also applies to Threads.A process is a larger unit of sequence of instructions.A thread is not a process on its own but it exists within a Thread.A Thread has no unique existence.Every process has atleast a Thread called primary Thread,you can create as many as you want.The Microprocessor divides the memory among the processes that we execute.Each process occupies that address space and the Threads within the process share same address space.That is why I said "Thread cannot exist on their own".It is clear from the following figure:-



Threads are very useful when you have large computations at your side.Threads divides the task into multiple threads and each on finishes its task.This way Threads accomplish a faster execution time and complete utilisation of Computer resources.

The resources like memory,devices and data of program and context of program are also available to the Threads of the program.A Thread is also known as a "Lightweight process" or "execution context".This is because there are fewer overloads on the processor when it switches from one Thread to the other,than when it switches from one Process to the other.The above diagram also shows the relationship between a Process and a Thread.

SingleThreaded and MultiThreded Application


A Process in general are of two types

1.Single Threaded
2.Multi Threaded

A process which is made up of single thread is known as single threaded process.It is like performing a task at a particular time.No other simultaneous thread can execute.The next thread can only execute on the completion of previous Threads completion.You can understand more from figure see below.


Single Thread within a process which runs serially and perform tasks



A Process having more than one thread is known as MultiThreaded Process.In MultiThreaded process multiple threads can run and perform various tasks at the same time for Example:-In a computer game we have a lot of things going on at the same time like Gameplay,Scoring,Sound,Controlling and so on.These all are handled by individual threads which works with each other or execute at the same time to produce the results.More understanding from figure see below.




Thread Input(two thread running simultaneously within a process independently)


Are you Intelligent Compete with world to prove

Suggested Reading:-

Thread Life cycle
Ways to create Threads

Read more...

Friday, September 4, 2009

Memory Management In Java

Java provides automatic garbage collection,sometimes you will want to know how large the object heap is and how much of it is left.You can use this result to know about the efficiency of your application or program,that is you may come to know how many more objects you can instantiate.To obtain these values use totalMemory() and freeMemory() methods.

Since Java Garbage Collector runs periodically to check the dangling object references and empty Strings and to recycle these unused objects.However on the other hand we can let the garbage collector run whenever we want.Garbage collector runs on random times ,you never know when will be the next appointment of Garbage Collector.So,if you think you are running out of memory you can enforce Garbage Collector to Sweep unused memory.You can run the Garbage Collector on demand by calling gc() method.gc() is called as "System.gc()".A good practice is to first call gc() method then call freeMemory() to get the base memory usage.Next execute your code and now see how much memory code is occupying by again calling freeMemory() method.

NOTE:-The methods gc(),totalMemory(),freeMemory() are part of Runtime class(For more on Runtime refer its Runtime API).The gc() method is also available in System class and is marked static in it.

Lets understand by example:-

public class Memoryusage{
public static void main(String a[]){
Runtime rt = Runtime.getRuntime();
long mem1,mem2;
String toomuch[] = new String[20000];
System.out.println("Total memory is : "+rt.totalMemory());
mem1=rt.freeMemory();
System.out.println("Initial Free Memory : "+mem1);
rt.gc();
mem1=rt.freeMemory();
System.out.println("Memory after Garbage Collection :"+mem1);
for(int i=0;i<20000;i++)
toomuch[i] = new String("String Array");

mem2=rt.freeMemory();
System.out.println("Memory after allocation :"+mem2);
System.out.println("Memory used by alocation : "+(mem1-mem2));

for(int i=0;i<1000;i++)
toomuch[i] = null;
rt.gc();
mem2=rt.freeMemory();
System.out.println("Memory after deacllocating memory : "+mem2);
}
}

Output:-

Total memory is : 5177344
Initial Free Memory : 4898608
Memory after Garbage Collection :4986512
Memory after allocation :4505976
Memory used by allocation : 480536
Memory after deacllocation memory : 4530512

Output is Machine specific and may vary on your machine.

Now you can see that how these methods work gc(),freeMemory() and totalMemory().Runtime class is an abstract class thus it cannot be used to create instances but despite we can all methods to do the same.Like here we have called method getRuntime().

Other Suggested Reading

Loading Image on JFrame
Compute any day in calendar
How to Create Pop Up menus
Date and Time in your specified Format

Sponsored Listings

Are you Intelligent!!!
Get your SCJP Kit free

Read more...

Thursday, September 3, 2009

Why use StringBuilder instead of StringBuffer?

The String class is just not sufficient to perform all the String related tasks.That is why the classes like StringBuffer and StringBuilder is added.StringBuffer class is added in Java 5 .It has exactly the same API as StringBuffer except (the twist in the story) ,the methods in StringBuilder class are not Thread safe.We can also say that the methods in StringBuilder class are not synchronized.The recommendation of many experienced programmers and Sun itself is that use StringBuilder instead of StringBuffer because the StringBuilder will run faster than StringBuffer.

Apart from this huge difference between StringBuilder and StringBuffer, everything which is true for StringBuffer holds true for StringBuilder class.

NOTE:-If you want to give SCJP examination then you must clearly know the distinction between the String,StringBuffer and StringBuilder class.The questions may be on how well you know the API of these classes and implementation of these classes.So there may be questions on StringBuilder or StringBuffer which may contain some piece of Thread code.Don't be panic by watching the Thread code.Just Rehearse the use of StringBuilder and StringBuffer in Threads.It is not that tough.

Suggested Reading:-

How JVM handles Strings
Method Chaining in Java Strings
Important String Methods
Simple twisting questions on Strings
StringBuffer class explained

Sponsored Listings
Get your SCJP kit freee
Are you Intelligent!!!!!

Read more...

StringBuffer class in Java

StringBuffer is the class included in java.lang and is mostly used when we have to make a lot of modifications to Strings of characters.As String class does not support string mutability that is when we use Java Strings class our strings becomes Immutable and can never be changed.It has a crucial impact on the memory of the program.If we use String class we are left with numerous dangling strings in the memory which not only waste the memory but could also cause the memory overflow at some stage.Objects of StringBuffer class can be modified a number of times and even you don't need a reference to the object to assign.Simply use the method on the object and change will reflect on the object.StringBuffer class modifies strings over and over again without leaving behind a great effluence of discarded String objects.

The main use of StringBuffer class is in File I/O where large stream of data keeps on coming with constantly changing values.Thus making StringBuffer class use handy.Here the loss of memory never happens.In these cases, large block of characters are handled as units ,and StringBuffer objects are the ideal way to handle a block of data,pass it on and then reuse the memory block to handle the next stream of data.

Constructors:-

StringBuffer() //Creates a StringBuffer with initial capacity of 16 characters.

StringBuffer(String s) //Creates StringBuffer which contains same no of characters as in the String argument.

StringBuffer(int length) //Creates StringBuffer with specified number of characters.

lets see an example on StringBuffer

// don't forget to import the StringBuffer class(java.lang.StringBuffer.*;)
StringBuffer x = new StringBuffer("ABCDE");
x.append("FGH");
System.out.println(x);

Output would be :- ABCDEFGH

The main feature of StringBuffer methods are as follows :-

The main feature of this StringBuffer class is that all methods are thread safe that is marked as synchronized.With synchronized marking StringBuffer comes with a disadvantage that it works slower that every String API.To overcome the problem of this Thread safe and slow execution we use StringBuilder class.More on StringBuilder Later.

Suggested Reading:-

How JVM handles Java Strings
Method Chaining in Java Strings
Important String Class Methods
Simple twisting questions on Strings
Why use StringBuilder instead of StringBuffer?

Sponsored Listings
Get Your SCJP kit free
Are you Intelligent!!!!

Read more...

About This Blog

This Blog is all about Java and programming.This blog is written by Vaibhav Pandey .He is a Computer Science Graduate .You can contact the author at javatute@gmail.com for any suggestion or Query.You can also contact the author for advertising on this blog.All the material presented here is the property of author and its reproduction in any form is strictly prohibited.

Disclaimer:-Download links provided here are not of author in any means.These are found over the Internet.
Page copy protected against web site content infringement by Copyscape

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP