Wednesday, August 26, 2009

How to call constructor of SuperClass

Inheritance is the core concept of Object oriented programing and Java programming Language.Since every subclass has exclusive rights to use the every resource of its superclass.Constructor of superclass holds important position in this regard.There are many functions a subclass can import by calling the constructor of its superclass.The call to the Superclass constructors can be made by using the ' super ' keyword.The main points to remembered in case of using super keyword are as follows:-

1.The default Constructor of the superclass is invoked even if the super() method is not called in the subclass.It is also invoked if you do not pass any arguments to super().If the default constrictor is not available,compiler generates an error.

2.You can invoke a special constructor of the superclass by passing arguments to the super method,if the constructor is overloaded in the superclass.

3.The super() method must be the first statement in the constructor of the subclass.

Lets take a look at following example:- The example illustrates how you can call a super class constructor.

The Superclass

class Car
{
Strring Name;
int seats=4;

Car(){
.....
}

Car(int seats,String Name){
....
}
}

Subclass which invokes the superclass constructor

public class Subaru extends Car{
int wheels;

public Subaru(){
super(4,"Subaru Impreza");
wheels=4;
}
}

Here the constructor of superclass is invoked by the method call super(4,"Subaru Impreza") and you can call the default constructor by placing your call super().By following the way you can invoke the superclass constructor which can be helpful in many tasks in your application.

Useful Links:-
Why Java Classes not marked final
Why code reuse is exclusive feature of Java
Polymorphism in Java
Why Java not support multiple inheritance
Inheritance Complete explanation
Is a and Has-a relationship

Sponsored Links:-

Are you Intelligent Check here
Get your Copy of SCJP kit Free !!!!!

Read more...

Tuesday, August 25, 2009

Simple Twisters on Java Strings

Java Stings is a relatively easy topic in Java to understand.But until you master any topic you cannot answer even the simplest questions on that topic.These twisters are interesting and will test your Strings knowledge.In the previous tutorials on Java Strings you have learned following topics:-

1.How JVM Handles Strings
2.Important Java Strings methods
3.Method Chaining in Strings

if you wish to answer the following questions i recommend you to look back the previous tutorials to make your Java String Concepts more strong.

Get Java Books Free!!!!! Hurry answer these questions correctly and you can win a chance to download Java books for free.Just answer these questions and mail me javatute@gmail.com within 2 days of its publish.First five winner will get exclusive Java ebooks for free.Hurry !!!

1.In Java Strings are immutable and Cannot be changed
a)True
b)False

2.What would be the output of following code:-

String a="abcdefgh";
a.concat(" i don't know buddy!!");
System.out.println(a);

a)abcdefgh i don't know buddy!!
b)abcdefgh
c)Compilation fails
d)Runtime Exception

3.How many Strings are created in the String constant pool upon compilation of following code segment:-

String a="abcdefgh";
a=a.concat(" i don't know buddy!!");
System.out.println(a);

a) 1
b) 2
c) 3
d) 4

4.What would be the output of following code:-

String a="abcdefgh";
a=a.concat(" i don't know buddy!!");
System.out.println(a);

a)abcdefgh i don't know buddy!!
b)abcdefgh
c)Compilation fails
d)Runtime Exception

5.What would be the output of following code segment:-

String a ="abcdefgh";
a.toString();
a.concat("Its not a joke dude!!!");
System.out.println(a.concat("Its amazing"));
System.out.println(b.toUpperCase());

a)abcdefgh Its amazing
ABCDEFGH

b)abcdefgh
ABCDEFGH

c)ABCDEFGH
d)Compilation fails

6.What would be the output of following code segment:-

String s="abcdefgh";
System.out.println(s.length);
System.out.print(s+="ijk");

a) 8abcdefgh
b) 8abcdefghijk
c) Compilation fails
d) Rintime Exception

7.What would be the output of following code segment:-

String s="abcd";
String r=s.toUpperCase().concat("efgh").replace('A','Z');
System.out.println(r);

a)abcdefgh
b)ABCDEFGH
c)Zabcdefgh
d)ZBCDEFGH


8.What happens when Strings having no reference reside in String constant pool?
(select all that apply)

a)JVM repeatedly search for Strings with no reference and sweeps them to recollect the memory in String Constant pool.
b)String continues to reside in the memory and JVM doesnot do anything.
c)JVM keeps them in constant pool for some time then eliminates them.
d)The String Constant pool memory Overflows.

Useful Links:-

Java Interview questions on Utilities and Strings
Java Interview Questions
Best Java Interview Questions
Sponsored Links:-

Get your SCJP kit free!!!!!
Check your Intelligence here

Read more...

Friday, August 21, 2009

Method chaining in Java Strings

Method chaining in Strings is an exceptional and tricky concept in Java Programming.Method chaining in Strings can be widely used as it can perform various and multiple string operations in single statement.Chained methods may contain all the methods of String class.For more on methods click here.

The general form or Syntax of Chained methods is given as follows:-


result = method1().method2(). ........ method n()

There are theories that you can chain as many method you want but in practice not more than three methods are chained.

So what you are supposed to do when you want to use the chained methods.There are certain rules to follow.Let us take an example :-

You wish to concat a string in the end if give string then convert it to uppercase and then replace a character in the resulting string.

First of all Accomplish first task.

suppose our string is ' s ' and we have to append " World" in the end then we would write
String s="Java";
s.concat(" World");

Then Convert to uppercase,remember we are in continuation.That is we have to apply the method on the result of previous step thus we would write

s.concat(" World").toUpperCase();

Similarly now add the replace method in the chain we will get something like this

s.concat(" World").toUpperCase().replace('V','W');

and when you assign the result you will have to write

s = s.concat(" World").toUpperCase().replace('V','W');

The output would be
"JAWA WORLD"

In Java examination the question on String methods chaining is frequently asked.What you need to know is the reverse process in deciphering the chained methods.

There are few rules too you must keep in your mind.
1.Determine what the leftmost method call will return.(Call it x)
2.Use this x as the invoking object on the method.If it is the last method then the result of this method call will be the result otherwise repeat the process as in step 1.

Take an example:-

s = s.concat(" World").toUpperCase().replace('V','W');

First consider only concat method whose output would be "Java World".
Now let it be x and invoke uppercase method on x,output would be "JAVA WORLD".
Then the last call made on new x and final output is "JAWA WORLD".

That is how it works I thinks it would be clear now and if you have any query dont hesitate to ask me.My mail id is given below in the box.

Useful links:-

How JVM handles string objects
Important String class methods

Sponsored Links :-
Check your General Knowledge
Get Your SCJP Exam Kit for Free

Read more...

Thursday, August 20, 2009

Important String class methods explained

Strings are very important part of any programming language.Same is the case with Java.There are so many String methods in String class and it will become difficult to explain all of them.I am mainly focusing on some methods which are worthful to beginners.I will also explain some basics about Strings here which makes Strings easy to understand.So, lets begin.

Basics about Strings in Java

1.You can create Strings in various ways:-
a) By Creating a String Object
String s=new String("abcdef");

b) By just creating object and then referring to string
String a=new String();
a="abcdef";

c) By simply creating a reference variable
String a="abcdef";

2.All the strings gets collected in a special memory are for Strings called " String constant pool".
3.JVM does all string related tasks to avoid the memory wastage for more info on this refer "How JVM Handles strings".
4.Every String is considered as a string literal.
5.Strings are immutable only reference changes string never changes.New string literals are referenced when there is any manipulation.The old string gets lost in the preceding.look below

String s="abcd";
s=s+"efgh";


Important String Methods
Following are most commonly used methods in the String class.

1.public String concat(String s)
This method returns a string with the value of string passed in to the method appended to the end of String which used to invoke the method.

String s="abcdefg";
System.out.println(s.concat("hijlk"));

Note:-Always use assignment operator in case of concat operator otherwise concat will be unreferenced and you will get old String.example

s.concat("hijkl");
System.out.println(s);

It will present output as " abcdefg " different than what we have expected.So always be careful in using the assignment operator in String method calls.

2.public charAt(int index)
This method returns a specific character located at the String's specific index.Remember,String indexes are zero based.Example

String s="Alfanso Mango";
System.out.println(s.charAt(0));

The output is 'A'

3.public int length()
This method returns the length of the String used to invoke the method.example:-

String s="name";
System.out.println(s.length());

The output is 4

4.public String replace(char old,char new)
This method return a String whose value is that of the String to invoke the method ,updated so that any occurrence of the char in the first argument is replaced by the char in the second argument .Example:-

String s="VaVavavav";
System.out.println(s.replace('v','V'));

The output is VaVaVaVaV

5.public boolean equalsIgnoreCase(String s)
This method returns a boolean value depending on whether the value of the string in the argument is the same as the String used to invoke the method.This method will return true even when character in the string object being compared have different cases.Example:-

String s="Vaibhav";
System.out.println(s.equalsIgnoreCase("VAIBHAV"));

The output is true

6.public String substring(int begin) / public String substring(int begin,int end)
substring method is used to return a part or substring of the String used to invoke the method.The first argument represents the starting location of the substring.Remember the indexes are zero based.example:-

String s="abcdefghi";
System.out.println(s.substring(5));
System.out.println(s.substring(5,8));

The output would be
" fghi "
" fg "

7.public String toLowerCase()
This method returns a string whose value is the String used to invoke the method,but with any uppercase converted to lowercase.:-

String s="AbcdefghiJ";
System.out.println(s.toLowerCase());

Output is " abcdefghij "

8.public String trim()
This method returns a String whose value is the String used to invoke the method ,but with any leading or trailing blank spaces removed.Example:-

String s="hey here is the blank space ";
System.out.println(s.trim())

The output is " heyhereistheblankspace"

9.public String toUpperCase()
This method returns a String whose value is String used to invoke the method ,but with any lowercase character converted to uppercase.Example:-

String s="AAAAbbbbb";
System.out.println(s.to UpperCase());

The output is " aaaabbbbb "

Above mentioned String methods are most commonly used in String class.Do remember them or otherwise I am always up for you and of course you can refer this site every time you need something.

Useful Links :-

How JVM Handles Strings
Method Chaining in Java Strings

Sponsored Links :-
Get Your SCJP preparation Kit free!!!!!!!
Get Your SCWCD preparation Kit free!!!
Are you Intelligent check here

Read more...

Wednesday, August 19, 2009

SCWCD best ebook free download

SCWCD Sun Certified web Component Developer examination is a high level sun certification.After being certified as SCWCD you are assumed to have master in web development which involves Java technology.If you are striving to become a SCWCD holder then you must refer to the Head first servlet and JSP written by Kathy Sierra,her yet another great creation.She is master in writing Sun Certification ebooks.Head first servlet and JSP doesn't give you a bunch of facts to memorize but it will drive knowledge straight into your brain.Head first servlet and JSP let you interact servlets and JSP so that you can grasp the concepts easily.This book also contains few brand new mock exams which will test your skills at the end of the book.Download Head first servlet and JSP free.To download click on the following links:-





Read more...

Tuesday, August 18, 2009

How JVM Handles Strings Objects and literals

Strings are undoubtedly the most important part of any programming language.The same is the case with Java programming Language.Handling String objects in memory is a demanding task.One of the key goals of any good programming language is to make efficient use of available memory.As the size of our application grows the size that string literals occupy also becomes larger.Sometime memory may overflow due to high number of string literals used.There may be literal redundancy in the memory.In case of Java programming Language JVM does all memory related tasks specially related with Strings.

In Java JVM sets up a special Sting memory area called " String Constant Pool ".Whenever Compiler encounters a String literal it checks to see if there is an identical String already exists.If the String exists then the reference is directed towards existing literal else new String literal object is created.

The important property of Strings is that they are immutable.Yes,you cannot change them.Once you have created a string its unchangeable.You can only assign a new value to the existing String reference,and what happened to previous string as usual it is lost.Lets see what actually happens consider following program:-

String s="abcd";

s=s+"efgh";

System.out.println(s);


In this case the output would be ' abcdefgh '.In the process of getting this value the JVM has actually 3 string literals

1.abcd
2.efgh
3.abcdefgh

In order to get the result abcdefgh we have lost the two strings.But point to be noted here is that they remain in memory because the reference is now pointing to some other string and it is considered as lost.There is no way we can refer this string in practical.

Now we can start to see why making string objects immutable is such a good idea.If several reference variables refer to the same string without even knowing it,it would be very bad if any of them could change the strings value.

You might say if somebody overrides the String class functionality then what will happen,couldn't that cause problem in the pool??? Well the language designers were well aware about it and that is why they marked String class as ' final '.Means nobody cannot ever override the String class functionality.So that you can assure yourself about String objects because they are immutable.

JVM on the other hand does garbage collection that is it periodically checks for dangling references on the string literals and on other constants.Whenever one is encountered JVM sweeps it from the memory pool.You have methods to force JVM for garbage collection but mind you it is not a human its a die hard computing machine the JVM thus it does garbage collection when it suits otherwise it keeps mum.

Useful Link :-

String class Useful Methods
Method Chaining in Java Strings

Sponsored Links :-
Get Your SCJP preparation Kit free!!!!!!!
Get Your SCWCD preparation Kit free!!!
Are you Intelligent check here

Read more...

Saturday, August 15, 2009

Java Interview questions Utilities and Threads

If You are appearing for any technical job's interview specially for software and system development you must know the language Java it is considered as the strongest language present in recent times.To make you aware of Java Util class and Thread class there are few frequently asked questions just go through.

Java Interview questions

  1. What is the List interface? - The List interface provides support for ordered collections of objects.
  2. What is the Vector class? - The Vector class provides the capability to implement a growable array of objects
  3. What is an Iterator interface? - The Iterator interface is used to step through the elements of a Collection
  4. Which java.util classes and interfaces support event handling? - The EventObject class and the EventListener interface support event processing
  5. What is the GregorianCalendar class? - The GregorianCalendar provides support for traditional Western calendars
  6. What is the Locale class? - The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region
  7. What is the SimpleTimeZone class? - The SimpleTimeZone class provides support for a Gregorian calendar
  8. What is the Map interface? - The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values
  9. What is the highest-level event class of the event-delegation model? - The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy
  10. What is the Collection interface? - The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates
  11. What is the Set interface? - The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements
  12. What is the purpose of the enableEvents() method? - The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods.
  13. What is the ResourceBundle class? - The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program’s appearance to the particular locale in which it is being run.
  14. What is the difference between yielding and sleeping? - When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.
  15. When a thread blocks on I/O, what state does it enter? - A thread enters the waiting state when it blocks on I/O.
  16. When a thread is created and started, what is its initial state? - A thread is in the ready state after it has been created and started.
  17. What invokes a thread’s run() method? - After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread’s run() method when the thread is initially executed.
  18. What method is invoked to cause an object to begin executing as a separate thread? - The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread.
  19. What is the purpose of the wait(), notify(), and notifyAll() methods? - The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object’s wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object’s notify() or notifyAll() methods.
  20. What are the high-level thread states? - The high-level thread states are ready, running, waiting, and dead
  21. What happens when a thread cannot acquire a lock on an object? - If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object’s lock, it enters the waiting state until the lock becomes available.
  22. How does multithreading take place on a computer with a single CPU? - The operating system’s task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.
  23. What happens when you invoke a thread’s interrupt method while it is sleeping or waiting? - When a task’s interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown.
  24. What state is a thread in when it is executing? - An executing thread is in the running state
  25. What are three ways in which a thread can enter the waiting state? - A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object’s lock, or by invoking an object’s wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.


Suggested Reading:-


Java Basic Questions Control statements

Simple Java Twisters

All Interview questions


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