Saturday, February 7, 2009

Linked List

Linked List Concepts

Printing Linked list without traversing the list:

void printreverse(Node *node)
{
if (node)
{
printreverse(node->next);
printf("%d -> ",node->info);
}
}


Reversing the list using stack:
Push all the nodes, pop one by one and print them… Here is the program for this..

void printreverse(Node* node)
{
Node *tmpnode;
Stack *stack = CreateStack();
while(node)
{
Push(stack, node);
node = node->next;
}
tmpnode = Pop(stack);
while(tmpnode)
{
tmpnode = Pop(stack);
printf("%d -> ", tmpnode->info);
}
DestroyStack(stack);
}
Reverse linked list using pointers
Reversing a single list can achieved using a stack very easily. however this can be done without using stack, and by simply using three additional pointers. Let us say we are using curr, next, result pointers, curr points to current node, next obviously points to the next node, result points to the new reversed linked list.
here is the pictorial representation of this operation for better understanding…

now result holds one reversed node, and curr points to the rest of the linked list..

now result holds a pointer to the reversed linked list (reversed two pointers already)…. curr holds rest of the list

we reversed successfully….

here is the routine for doing this…..
void reverse_single_linked_list(struct node** headRef)
{
struct node* result = NULL;
struct node* current = *headRef;
struct node* next;
while (current != NULL)
{
next = current->next; // tricky: note the next node
current->next = result; // move the node onto the result
result = current;
current = next;
}
*headRef = result;
Question: How could you determine if a linked list contains a cycle in it, and, at what node the cycle starts?
Answer: There are a number of approaches. The approach I shared is in time N (where N is the number of nodes in your linked list). Assume that the node definition contains a boolean flag, bVisited.
// error checking and checking for NULL at end of list omitted
p1 = p2 = head;

do {
p1 = p1->next;
p2 = p2->next->next;
} while (p1 != p2);
p2 is moving through the list twice as fast as p1. If the list is circular, (i.e. a cycle exists) it will eventually get around to that sluggard, p1.

Question: How would you reverse a doubly-linked list?
Answer: This problem isn't too hard. You just need to start at the head of the list, and iterate to the end. At each node, swap the values of pNext and pPrev. Finally, set pHead to the last node in the list.
Node * pCurrent = pHead, *pTemp;
while (pCurrent)
{
pTemp = pCurrent->pNext;
pCurrent->pNext = pCurrent->pPrev;
pCurrent->pPrev = temp;

pHead = pCurrent;

pCurrent = temp;
}
________________________________________
Question: Assume you have an array that contains a number of strings (perhaps char * a[100]). Each string is a word from the dictionary. Your task, described in high-level terms, is to devise a way to determine and display all of the anagrams within the array (two words are anagrams if they contain the same characters; for example, tales and slate are anagrams.)
Answer: Begin by sorting each element in the array in alphabetical order. So, if one element of your array was slate, it would be rearranged to form aelst (use some mechanism to know that the particular instance of aelst maps to slate). At this point, you slate and tales would be identical: aelst.
Next, sort the entire array of these modified dictionary words. Now, all of the anagrams are grouped together. Finally, step through the array and display duplicate terms, mapping the sorted letters (aelst) back to the word (slate or tales).
________________________________________
Question: Given the following prototype:
int compact(int * p, int size);
write a function that will take a sorted array, possibly with duplicates, and compact the array, returning the new length of the array. That is, if p points to an array containing: 1, 3, 7, 7, 8, 9, 9, 9, 10, when the function returns, the contents of p should be: 1, 3, 7, 8, 9, 10, with a length of 5 returned.
Answer: A single loop will accomplish this.
int compact(int * p, int size)
{
int current, insert = 1;
for (current=1; current < size; current++)
if (p[current] != p[insert-1])
{
p[insert] = p[current];
current++;
insert++;
} else
current++;
}
Happy Programming!


RE: write a c program to reverse the string without us...
________________________________________
#include
#include
main()
{
char str[50],revstr[50];
int i=0,j=0;
printf("Enter the string to be reversed : ");
scanf("%s",str);
for(i=strlen(str)-1;i>=0;i--)
{
revstr[j]=str[i];
j++;
}
revstr[j]='\0';
printf("Input String : %s",str);
printf("\nOutput String : %s",revstr);
getch();
}

write a c program to find whether a stack is
progressing in forward or reverse direction.

#include

void show_stack_dir(int * p) {
printf("%s\n", p < (int*)(&p) ? "up" : "down");
}

int main(int argc, char ** argv) {
show_stack_dir(&argc);
return 0;
}

Given a number, how can u determine using C, whether it is divisible by 3, without using *, /, % operators.

You may assume that itoa() function is available.
convert the number to the string using itoa();

add up all the digits
checkDivisibility(int num){
char *str=itoa(num)

while (1)
{
for (i =0 ; i < strlen(str);i++)
sum= sum + (str[i] - "0");

if (sum > 10)
str=itoa(sum);
else
break;
}

if(sum == 3 || sum == 6 || sum == 9)
printf("Number divisible by 3");
else
printf("Number not divisible by 3");

}


Re: Hexadecimal Conversion
« Reply #6 on: Jul 26th, 2007, 1:02am » Quote Modify

________________________________________
We can change this to...


if( ch >= '0' && ch <='9')
index=ch-'0';
else if(ch >= 'A' && ch <= 'F')
index=10+ch-'A';
else if(ch >='a' && ch <= 'f')
index=10+ch-'a';

Re: Find the Repeated Number
« Reply #5 on: Aug 1st, 2007, 3:20am » Quote Modify

________________________________________

Try and debug thru this code with an appropriate example

int findRepeated(int *arr,int length)
{
int counter=0;
int current=arr[0];
for(i=0;i{
if(counter==0)
{
counter++;
current=arr [ i ];
}
if(counter > 0)
{
if(current == arr [ i ])
{
counter++;
else
counter--;
}
}

return current;

}

Function for finding greatest of three numbers:
int maxof3(int a, int b, int c)
{
return (a + b + c * 2 + abs(a - b) + abs(a + b - c * 2 + abs(a - b))) / 4;
}
Function for finding greatest of four numbers:
int maxof4(int a, int b, int c, int d)
{
return (a + b + c + d + abs (b - a) + abs(d - c) + abs(a + b - c - d + abs( b - a) - abs(d - c)))/ 4;
}

GOOGLE CHROME - THE BEST WEB BROWSER

GOOGLE CHROME

Google Chrome is a web browser developed by Google and based on the WebKit layout engine and application framework. In December 2008, it had a share of 1.04% of the browser market.[1] It was first released as a beta version for Microsoft Windows on September 2, 2008. The name is derived from the graphical user interface frame, or "chrome", of web browsers. The public stable release was on December 11, 2008.
• Chromium is the open source project behind Google Chrome.[2] The Google-authored portion of it is released under the BSD license, with other parts being subject to a variety of different permissive open-source licenses, including the MIT License, the LGPL, the Microsoft Permissive License and a MPL/GPL/LGPL tri-license.[3] It implements the same feature set as Chrome, but has a slightly different logo.
History
Announcement
The release announcement was originally scheduled for September 3, 2008, and a comic by Scott McCloud was to be sent to journalists and bloggers explaining the features of and motivations for the new browser.[5] Copies intended for Europe were shipped early and German blogger Philipp Lenssen of Google Blogoscoped[6] made a scanned copy of the 38-page comic available on his website after receiving it on September 1, 2008.[7] Google subsequently made the comic available on Google Books and their site[8] and mentioned it on its official blog along with an explanation for the early release.[9]
Public release


The Chromium Test Shell on Linux
The browser was first publicly released for Microsoft Windows (XP and later only) on September 2, 2008 in 43 languages, officially a beta version.[10] Chrome quickly gained about 1% market share. Mac OS X and Linux versions are under development.[11][12][13][14] Recently, in the Chromium project's developer wiki[15] a message was placed that a "test shell" is available to build on Linux. Some have tried this shell, which apparently lacks many features, but appears to function quite well in rendering web sites (including JavaScript).[16][17]
On September 2, a CNET news item[18] drew attention to a passage in the terms of service for the initial beta release, which seemed to grant to Google a license to all content transferred via the Chrome browser. The passage in question was inherited from the general Google terms of service.[19] On the same day, Google responded to this criticism by stating that the language used was borrowed from other products, and removed the passage in question from the Terms of Service.[20] Google noted that this change would "apply retroactively to all users who have downloaded Google Chrome."[21] There were subsequent concern and confusion about whether and what information the program communicates back to Google. The company stated[22] that usage metrics are only sent when users opt in by checking the option "help make Google Chrome better by automatically sending usage statistics and crash reports to Google" when the browser is installed.[23]
The first release of Google Chrome passed the Acid1 and Acid2 tests. It also passed 79 out of the 100 subtests of the Acid3, higher than both Internet Explorer 7 (14) and Firefox 3 (71), but lower than Opera (83)[vague].[24] When compared with development builds of Firefox, Internet Explorer, Opera, and Safari, Chrome scored lower than Firefox 3.1 Beta 1 (85), Opera (100), and Safari 4 (Developer Preview) (100),[24] but still higher than Internet Explorer (21)[citation needed].
On January 9, 2009, CNET reports that Google plans to release versions for Mac OS X and Linux by the first half of the year.[25]
Unofficial Chromium releases
• On September 15, 2008, CodeWeavers released an unofficial bundle of a Wine derivative and Chromium Developer Build 21 for Linux and Mac OS X, which they dubbed CrossOver Chromium.[26][27]
• SRWare Iron is a release of Chromium software that explicitly disables the collection and transmission of usage information to Google which is optional within Chrome.[28]
Development
Primary design goals were improvements in security, speed, and stability compared to existing browsers. There also were extensive changes in the user interface.[8] Chrome was assembled from 26 different code libraries from Google and others from third parties such as Netscape.[29]
Security
Chrome periodically downloads updates of two blacklists (one for phishing and one for malware), and warns users when they attempt to visit a harmful site. This service is also made available for use by others via a free public API called "Google Safe Browsing API". Google notifies the owners of listed sites who may not be aware of the presence of the harmful software.[8]
Chrome will typically allocate each tab to fit into its own process to "prevent malware from installing itself" or "using what happens in one tab to affect what happens in another", however the actual process allocation model is more complex.[30] Following the principle of least privilege, each process is stripped of its rights and can compute, but can not write files or read from sensitive areas (e.g. documents, desktop)—this is similar to the "Protected Mode" that is used by Internet Explorer 7 on Windows Vista. The Sandbox Team is said to have "taken this existing process boundary and made it into a jail";[31] for example, malicious software running in one tab is unable to sniff credit card numbers, interact with the mouse, or tell "Windows to run an executable on start-up" and it will be terminated when the tab is closed. This enforces a simple computer security model whereby there are two levels of multilevel security (user and sandbox) and the sandbox can only respond to communication requests initiated by the user.[32]
Typically, plugins such as Adobe Flash Player are not standardized and as such, cannot be sandboxed as tabs can be. These often need to run at, or above, the security level of the browser itself. To reduce exposure to attack, plugins are run in separate processes that communicate with the renderer, itself operating at "very low privileges" in dedicated per-tab processes. Plugins will need to be modified to operate within this software architecture while following the principle of least privilege.[8] Chrome supports the Netscape Plugin Application Programming Interface (NPAPI),[33][34] but does not support the embedding of ActiveX controls.[34] Also, Chrome does not have an extension system such as Mozilla's XPInstall architecture.[35] Java applets support is available in Chrome as part of Java 6 update 11, which currently is the latest stable version.[36][37]
A private browsing feature called Incognito mode is provided that prevents the browser from storing any history information or cookies from the websites visited. This feature has been referred to as a porn mode similar to the private browsing feature available in Apple's Safari and the latest beta version of Internet Explorer 8.[38]
A denial-of-service vulnerability was found that allowed a malicious web page to crash the whole web browser.[39][40] However, Google Chrome developers confirmed the flaw, and it was fixed in the 0.2.149.29 release.[41]
Speed
The JavaScript virtual machine was considered a sufficiently important project to be split off (as was Adobe/Mozilla's Tamarin) and handled by a separate team in Denmark. According to Google, existing implementations were designed "for small programs, where the performance and interactivity of the system weren't that important," but web applications such as Gmail "are using the web browser to the fullest when it comes to DOM manipulations and Javascript." The resulting V8 JavaScript engine has features such as hidden class transitions, dynamic code generation, and precise garbage collection.[8] Tests by Google showed that V8 was about twice as fast as Firefox 3.0 and the Safari 4 beta.[42]
Several websites performed benchmark tests using the SunSpider JavaScript Benchmark[43] tool as well as Google's own set of computationally intense benchmarks, which includes ray tracing and constraint solving.[44] They unanimously reported that Chrome performed much faster than all competitors against which it had been tested, including Safari, Firefox 3.0, Internet Explorer 7, and Internet Explorer 8.[45][46][47][48] While Opera had not been compared to Chrome in those comparisons, in previous tests, it had been shown to be slightly slower than Firefox 3.0, which in turn, was slower than Chrome.[49][50] Another blog post by Mozilla developer Brendan Eich compared Chrome's V8 engine to his own TraceMonkey Javascript engine which was introduced in Firefox 3.1alpha, stating that some tests were faster in one engine and some were faster in the other, with Firefox 3.1a faster overall.[51] John Resig, Mozilla's JavaScript evangelist, further commented on the performance of different browsers on Google's own suite, finding Chrome "decimating" other browsers, but he questions whether Google's suite is representative of real programs. He stated that Firefox 3.0 performed poorly on recursion intensive benchmarks, such as those of Google, because the Mozilla team had not implemented recursion-tracing yet.[52]
Chrome also uses DNS prefetching to speed up website lookups.[53]
Stability
The Gears team was considering a multithreaded browser (noting that a problem with existing web browser implementations was that they are inherently single-threaded) and Chrome implemented this concept with a multi-process architecture,[54] similar to Loosely Coupled Internet Explorer (LCIE) recently implemented by Internet Explorer 8.[55] By default, a separate process is allocated to each site instance and plugin.[56] This prevents tasks from interfering with each other, which is good for security and stability; an attacker successfully gaining access to one application does not gain access to all, and failure in one application results in a Sad Tab screen of death, similar to the well-known Sad Mac, except only one single tab crashes instead of the whole application. This strategy exacts a fixed per-process cost up front, but results in less memory bloat overall as fragmentation is confined to each process and no longer results in further memory allocations.[57]
Chrome features a process management utility called the Task Manager which allows the user to "see what sites are using the most memory, downloading the most bytes and abusing [their] CPU" (as well as the plugins which run in separate processes) and terminate them.[8] Some users have reported a conflict with Internet Explorer, often resulting in the blue screen error on Windows.[58]
User interface


When Chrome is maximized, the title bar becomes hidden and instead, the tab bar is displayed at the top. Also, when the mouse is moved over a link, the URL of the link is displayed in a status bar at the bottom left. Otherwise, the status bar is invisible.


When Chrome is not maximized, the title bar is shown on top of the tab bar.
The main user interface includes back, forward, refresh, bookmark, go, and cancel options. The options are similar to Safari, while the location of the settings is similar to versions of Internet Explorer starting with version 7. The design of the window is based on Windows Vista.
When the window is not maximized, the tab bar appears directly under the title bar. When maximized, the title bar disappears, and instead, the tab bar is shown at the very top of the window. Unlike other browsers such as Internet Explorer or Firefox which also have a full-screen mode that hides the operating system's interface completely, Chrome can only be maximized like a standard Windows application. Therefore, the Windows task bar, notification area, and start menu link still take space at all times unless they have been configured to hide at all times.
Chrome includes Gears, which adds features for web developers typically relating to the building of web applications (including offline support).[8]
Chrome replaces the browser home page which is displayed when a new tab is created with a New Tab Page. This shows[59] thumbnails of the nine most visited web sites along with the sites most often searched, recent bookmarks, and recently closed tabs.[8]
The Omnibox is the URL box at the top of each tab, which combines the functionalities of both URL box and search box. It includes autocomplete functionality, but only will autocomplete URLs that were manually entered (rather than all links), search suggestions, top pages (previously visited), popular pages (unvisited), and text search over history. Search engines also can be captured by the browser when used via the native user interface by pressing Tab.[8]
Popup windows "are scoped to the tab they came from" and will not appear outside the tab unless the user explicitly drags them out.[8]
Chrome uses the WebKit rendering engine to display web pages, on advice from the Android team.[8] Like most browsers, Chrome was extensively tested internally before release with unit testing, "automated user interface testing of scripted user actions" and fuzz testing, as well as WebKit's layout tests (99% of which Chrome is claimed to have passed). New browser builds are automatically tested against tens of thousands of commonly accessed websites inside of the Google index within 20-30 minutes.[8]
Tabs are the primary component of Chrome's user interface and as such, have been moved to the top of the window rather than below the controls. This subtle change contrasts with many existing tabbed browsers which are based on windows and contain tabs. Tabs (including their state) can be transferred seamlessly between window containers by dragging. Each tab has its own set of controls, including the Omnibox.[8]
Chrome allows users to make local desktop shortcuts that open web applications in the browser. The browser, when opened in this way, contains none of the regular interface except for the title bar, so as not to "interrupt anything the user is trying to do." This allows web applications to run alongside local software (similar to Mozilla Prism and Fluid).[8]
By default, the status bar is hidden whenever it is not being used. However, it appears at the bottom left corner whenever a page is loading and when a hyperlink is hovered over.
For web developers, Chrome features an element inspector similar to the one in Firebug.[53]
Usage tracking
Usage tracking is an option presented to the user during the software's installation. Once accepted, it is possible to disable the transmission of this information by modifying Chrome's "Under the Hood" options.[60] Freeware programs such as UnChrome can remove the unique ID without having to change the browser.[61] Unofficial builds, such as SRWare Iron, seek to remove these features from the browser altogether.[62]
Extensions
As of October 2008, Google Chrome does not support 3rd party extensions.[63][64]
As of version 3499, Google Chrome has rudimentary Greasemonkey support. This feature is off by default, and may be turned on by launching the application with a specific command-line argument.
Google Chrome extensions: Not yet, but later. "We don't have that in the beta today, but we definitely plan an extension API," or application programming interface, Sundar Pichai, a Google vice president of product management, said at the Chrome launch event here Tuesday. "It is one of the things we will get to next."
—CNet News
Stable, Beta and Dev Releases
On January 08, 2009 Google introduced a new release channels system, whereby now there are three distinct release channels: Stable channel, Beta channel, and Developer preview channel. Before this change, there were only two channels: Beta channel and Developer preview channel. All previous Dev channel users were moved to Beta channel, the reason is that now the new Dev channel builds will be less stable and polished than what Dev channel users have been getting during Google Chrome's Beta period. Now the stable channel will be updated with features and fixes once they have been thoroughly tested in the Beta channel, and the Beta channel will be updated roughly monthly with stable and complete features from the Dev channel. The Dev channel is where ideas get tested (and sometimes fail), and it can be very unstable at times. [67][68] See http://googlechromereleases.blogspot.com/ for more information on specific releases.
Reception
The Daily Telegraph's Matthew Moore summarizes the verdict of early reviewers: "Google Chrome is attractive, fast and has some impressive new features, but may not—yet—be a threat to its Microsoft rival."[69]
Microsoft reportedly "played down the threat from Chrome" and "predicted that most people will embrace Internet Explorer 8." Opera Software said that "Chrome will strengthen the Web as the biggest application platform in the world."[70] Mozilla said that Chrome's introduction into the web browser market comes as "no real surprise", that "Chrome is not aimed at competing with Firefox", and furthermore that it should not affect Google's financing of Firefox.[71][72]
Chrome’s design bridges the gap between desktop and so-called “cloud computing.” At the touch of a button, Chrome lets you make a desktop, Start menu, or Quick Launch shortcut to any Web page or Web application, blurring the line between what’s online and what’s inside your PC. For example, I created a desktop shortcut for Google Maps. When you create a shortcut for a Web application, Chrome strips away all of the toolbars and tabs from the window, leaving you with something that feels much more like a desktop application than like a Web application or page.
—PC World[73]
On September 9, 2008, when Chrome still had been in beta, the German Federal Office for Information Security (BSI) issued a statement about their first examination of Chrome, expressing a concern over the prominent download links on Google's German web page, because "beta versions should not be employed for general use applications" and browser manufacturers should provide appropriate instructions regarding the use of pre-released software. They did, however, praise the browser's technical contribution to improving security on the web.[74]
Concern about Chrome's optional usage collection and tracking have been noted in several publications.[75][76]

Java Interview Questions

Java Interview Questions

Question: What is the difference between an Interface and an Abstract class?

Question: What is the purpose of garbage collection in Java, and when is it used?

Question: Describe synchronization in respect to multithreading.

Question: Explain different way of using thread?

Question: What are pass by reference and passby value?

Question: What is HashMap and Map?

Question: Difference between HashMap and HashTable?

Question: Difference between Vector and ArrayList?

Question: Difference between Swing and Awt?

Question: What is the difference between a constructor and a method?

Question: What is an Iterator?

Question: State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.

Question: What is an abstract class?

Question: What is static in java?

Question: What is final?


Q: What is the difference between an Interface and an Abstract class?
A: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
.



Q: What is the purpose of garbage collection in Java, and when is it used?
A: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.


Q: Describe synchronization in respect to multithreading.
A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.



Q: Explain different way of using thread?
A: The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.



Q: What are pass by reference and passby value?
A: Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.



Q: What is HashMap and Map?
A: Map is Interface and Hashmap is class that implements that.



Q: Difference between HashMap and HashTable?
A: The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.



Q: Difference between Vector and ArrayList?
A: Vector is synchronized whereas arraylist is not.



Q: Difference between Swing and Awt?
A: AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.



Q: What is the difference between a constructor and a method?
A: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.



Q: What is an Iterator?
A: Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.



Q: State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
A: public : Public class is visible in other packages, field is visible everywhere (class must be public too)
private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package.


Q: What is an abstract class?
A: Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.


Q: What is static in java?
A: Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.


Q: What is final?
A: A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).
Java Interview Questions



Question: What if the main method is declared as private?

Question: What if the static modifier is removed from the signature of the main method?

Question: What if I write static public void instead of public static void?

Question: What if I do not provide the String array as the argument to the method?

Question: What is the first argument of the String array in main method?

Question: If I do not provide any arguments on the command line, then the String array of Main method will be empty or null?

Question: How can one prove that the array is not null but empty using one line of code?

Question: What environment variables do I need to set on my machine in order to be able to run Java programs?

Question: Can an application have multiple classes having main method?

Question: Can I have multiple main methods in the same class?

Question: Do I need to import java.lang package any time? Why ?

Question: Can I import same package/class twice? Will the JVM load the package twice at runtime?

Question: What are Checked and UnChecked Exception?

Question: What is Overriding?

Question: What are different types of inner classes?


Q: What if the main method is declared as private?
A: The program compiles properly but at runtime it will give "Main method not public." message.
[ Received from Sandesh Sadhale]



Q: What if the static modifier is removed from the signature of the main method?
A: Program compiles. But at runtime throws an error "NoSuchMethodError".
[ Received from Sandesh Sadhale]



Q: What if I write static public void instead of public static void?
A: Program compiles and runs properly.
[ Received from Sandesh Sadhale]



Q: What if I do not provide the String array as the argument to the method?
A: Program compiles but throws a runtime error "NoSuchMethodError".
[ Received from Sandesh Sadhale]



Q: What is the first argument of the String array in main method?
A: The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.
[ Received from Sandesh Sadhale]



Q: If I do not provide any arguments on the command line, then the String array of Main method will be empty or null?
A: It is empty. But not null.
[ Received from Sandesh Sadhale]



Q: How can one prove that the array is not null but empty using one line of code?
A: Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.
[ Received from Sandesh Sadhale]



Q: What environment variables do I need to set on my machine in order to be able to run Java programs?
A: CLASSPATH and PATH are the two variables.
[ Received from Sandesh Sadhale]



Q: Can an application have multiple classes having main method?
A: Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.
[ Received from Sandesh Sadhale]



Q: Can I have multiple main methods in the same class?
A: No the program fails to compile. The compiler says that the main method is already defined in the class.
[ Received from Sandesh Sadhale]



Q: Do I need to import java.lang package any time? Why ?
A: No. It is by default loaded internally by the JVM.
[ Received from Sandesh Sadhale]



Q: Can I import same package/class twice? Will the JVM load the package twice at runtime?
A: One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.
[ Received from Sandesh Sadhale]



Q: What are Checked and UnChecked Exception?
A: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.
Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method•
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the
exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method• Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.



Q: What is Overriding?
A: When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass.
When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private.



Q: What are different types of inner classes?
A: Nested -level classes, Member classes, Local classes, Anonymous classes
Nested -level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other -level class.
Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. -level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested -level variety.

Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested -level class. The primary difference between member classes and nested -level classes is that member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a
more publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.

Java Interview Questions




Question: Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?

Question: Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?

Question: What is the difference between declaring a variable and defining a variable?

Question: What is the default value of an object reference declared as an instance variable?

Question: Can a level class be private or protected?

Question: What type of parameter passing does Java support?

Question: Primitive data types are passed by reference or pass by value?

Question: Objects are passed by value or by reference?

Question: What is serialization?

Question: How do I serialize an object to a file?

Question: Which methods of Serializable interface should I implement?

Question: How can I customize the seralization process? i.e. how can one have a control over the serialization process?

Question: What is the common usage of serialization?

Question: What is Externalizable interface?

Question: When you serialize an object, what happens to the object references included in the object?

Question: What one should take care of while serializing the object?

Question: What happens to the static fields of a class during serialization?



Q: Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?
A: Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying,can not resolve symbol
symbol : class ABCD
location: package io
import java.io.ABCD;
[ Received from Sandesh Sadhale]



Q: Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?
A: No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage.
[ Received from Sandesh Sadhale]



Q: What is the difference between declaring a variable and defining a variable?
A: In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization.
e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.
[ Received from Sandesh Sadhale]



Q: What is the default value of an object reference declared as an instance variable?
A: null unless we define it explicitly.
[ Received from Sandesh Sadhale]



Q: Can a level class be private or protected?
A: No. A level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a level class can not be private. Same is the case with protected.
[ Received from Sandesh Sadhale]



Q: What type of parameter passing does Java support?
A: In Java the arguments are always passed by value .
[ Update from Eki and Jyothish Venu]


Q: Primitive data types are passed by reference or pass by value?
A: Primitive data types are passed by value.
[ Received from Sandesh Sadhale]



Q: Objects are passed by value or by reference?
A: Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object .
[ Update from Eki and Jyothish Venu]


Q: What is serialization?
A: Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.
[ Received from Sandesh Sadhale]



Q: How do I serialize an object to a file?
A: The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.
[ Received from Sandesh Sadhale]



Q: Which methods of Serializable interface should I implement?
A: The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods.
[ Received from Sandesh Sadhale]



Q: How can I customize the seralization process? i.e. how can one have a control over the serialization process?
A: Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.
[ Received from Sandesh Sadhale]



Q: What is the common usage of serialization?
A: Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serilazed.
[ Received from Sandesh Sadhale]



Q: What is Externalizable interface?
A: Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.
[ Received from Sandesh Sadhale]



Q: When you serialize an object, what happens to the object references included in the object?
A: The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect.
[ Received from Sandesh Sadhale]



Q: What one should take care of while serializing the object?
A: One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.
[ Received from Sandesh Sadhale]



Q: What happens to the static fields of a class during serialization?
A: There are three exceptions in which serialization doesnot necessarily read and write to the stream. These are
1. Serialization ignores static fields, because they are not part of ay particular state state.
2. Base class fields are only hendled if the base class itself is serializable.
3. Transient fields.
[ Received from Sandesh Sadhale Modified after P.John David comments.]


Java Interview Questions




Question: Does Java provide any construct to find out the size of an object?

Question: Give a simplest way to find out the time a method takes for execution without using any profiling tool?

Question: What are wrapper classes?

Question: Why do we need wrapper classes?

Question: What are checked exceptions?

Question: What are runtime exceptions?

Question: What is the difference between error and an exception??

Question: How to create custom exceptions?

Question: If I want an object of my class to be thrown as an exception object, what should I do?

Question: If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?

Question: How does an exception permeate through the code?

Question: What are the different ways to handle exceptions?

Question: What is the basic difference between the 2 approaches to exception handling...1> try catch block and 2> specifying the candidate exceptions in the throws clause?
When should you use which approach?

Question: Is it necessary that each try block must be followed by a catch block?

Question: If I write return at the end of the try block, will the finally block still execute?

Question: If I write System.exit (0); at the end of the try block, will the finally block still execute?



Q: Does Java provide any construct to find out the size of an object?
A: No there is not sizeof operator in Java. So there is not direct way to determine the size of an object directly in Java.
[ Received from Sandesh Sadhale]



Q: Give a simplest way to find out the time a method takes for execution without using any profiling tool?
A: Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution.
To put it in code...
long start = System.currentTimeMillis ();
method ();
long end = System.currentTimeMillis ();
System.out.println ("Time taken for execution is " + (end - start));
Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing considerable amout of processing.
[ Received from Sandesh Sadhale]



Q: What are wrapper classes?
A: Java provides specialized classes corresponding to each of the primitive data types. These are called wrapper classes. They are e.g. Integer, Character, Double etc.
[ Received from Sandesh Sadhale]



Q: Why do we need wrapper classes?
A: It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also. Because of these resons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object.
[ Received from Sandesh Sadhale]



Q: What are checked exceptions?
A: Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions.
[ Received from Sandesh Sadhale]



Q: What are runtime exceptions?
A: Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.
[ Received from Sandesh Sadhale]



Q: What is the difference between error and an exception?
A: An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).
[ Received from Sandesh Sadhale]



Q: How to create custom exceptions?
A: Your class should extend class Exception, or some more specific type thereof.
[ Received from Sandesh Sadhale]



Q: If I want an object of my class to be thrown as an exception object, what should I do?
A: The class should extend from Exception class. Or you can extend your class from some more precise exception type also.
[ Received from Sandesh Sadhale]



Q: If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?
A: One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well.
[ Received from Sandesh Sadhale]



Q: How does an exception permeate through the code?
A: An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.
[ Received from Sandesh Sadhale]



Q: What are the different ways to handle exceptions?
A: There are two ways to handle exceptions,
1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and
2. List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions.
[ Received from Sandesh Sadhale]



Q: What is the basic difference between the 2 approaches to exception handling.
1> try catch block and
2> specifying the candidate exceptions in the throws clause?
When should you use which approach?
A: In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.
[ Received from Sandesh Sadhale]



Q: Is it necessary that each try block must be followed by a catch block?
A: It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.
[ Received from Sandesh Sadhale]



Q: If I write return at the end of the try block, will the finally block still execute?
A: Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.
[ Received from Sandesh Sadhale]



Q: If I write System.exit (0); at the end of the try block, will the finally block still execute?
A: No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.
[ Received from Sandesh Sadhale]



Java Interview Questions




Question: How are Observer and Observable used?

Question: What is synchronization and why is it important?

Question: How does Java handle integer overflows and underflows?

Question: Does garbage collection guarantee that a program will not run out of
memory?

Question: What is the difference between preemptive scheduling and time slicing?

Question: When a thread is created and started, what is its initial state?

Question: What is the purpose of finalization?

Question: What is the Locale class?

Question: What is the difference between a while statement and a do statement?

Question: What is the difference between static and non-static variables?

Question: How are this() and super() used with constructors?

Question: What are synchronized methods and synchronized statements?

Question: What is daemon thread and which method is used to create the daemon thread?

Question: Can applets communicate with each other?

Question: What are the steps in the JDBC connection?

Question: How does a try statement determine which catch clause should be used to handle an exception?




Q: How are Observer and Observable used?
A: Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.
[Received from Venkateswara Manam]



Q: What is synchronization and why is it important?
A: With respect to multithreading, synchronization is the capability to control
the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors.
[ Received from Venkateswara Manam]



Q: How does Java handle integer overflows and underflows?
A: It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
[ Received from Venkateswara Manam]



Q: Does garbage collection guarantee that a program will not run out of memory?
A: Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection
.
[ Received from Venkateswara Manam]



Q: What is the difference between preemptive scheduling and time slicing?
A: Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
[ Received from Venkateswara Manam]



Q: When a thread is created and started, what is its initial state?
A: A thread is in the ready state after it has been created and started.
[ Received from Venkateswara Manam]



Q: What is the purpose of finalization?
A: The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.
[ Received from Venkateswara Manam]



Q: What is the Locale class?
A: The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.
[ Received from Venkateswara Manam]



Q: What is the difference between a while statement and a do statement?
A: A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.
[ Received from Venkateswara Manam]



Q: What is the difference between static and non-static variables?
A: A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.
[ Received from Venkateswara Manam]



Q: How are this() and super() used with constructors?
A: This() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
[ Received from Venkateswara Manam]



Q: What are synchronized methods and synchronized statements?
A: Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
[ Received from Venkateswara Manam]



Q: What is daemon thread and which method is used to create the daemon thread?
A: Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.
[ Received from Shipra Kamra]



Q: Can applets communicate with each other?
A: At this point in time applets may communicate with other applets running in the same virtual machine. If the applets are of the same class, they can communicate via shared static variables. If the applets are of different classes, then each will need a reference to the same class with static variables. In any case the basic idea is to pass the information back and forth through a static variable.

An applet can also get references to all other applets on the same page using the getApplets() method of java.applet.AppletContext. Once you get the reference to an applet, you can communicate with it by using its public members.

It is conceivable to have applets in different virtual machines that talk to a server somewhere on the Internet and store any data that needs to be serialized there. Then, when another applet needs this data, it could connect to this same server. Implementing this is non-trivial.
[ Received from Krishna Kumar ]



Q: What are the steps in the JDBC connection?
A: While making a JDBC connection we go through the following steps :

Step 1 : Register the database driver by using :
Class.forName(\" driver classs for that specific database\" );
Step 2 : Now create a database connection using :
Connection con = DriverManager.getConnection(url,username,password);
Step 3: Now Create a query using :
Statement stmt = Connection.Statement(\"select * from TABLE NAME\");
Step 4 : Exceute the query :
stmt.exceuteUpdate();
[ Received from Shri Prakash Kunwar]



Q: How does a try statement determine which catch clause should be used to handle an exception?
A: When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exceptionis executed. The remaining catch clauses are ignored.
[ Received from P Rajesh]


Java Interview Questions




Question: Can an unreachable object become reachable again?

Question: What method must be implemented by all threads?

Question: What are synchronized methods and synchronized statements?

Question: What is Externalizable?

Question: What modifiers are allowed for methods in an Interface?

Question: What are some alternatives to inheritance?

Question: What does it mean that a method or field is "static"? ?

Question: What is the difference between preemptive scheduling and time slicing?

Question: What is the catch or declare rule for method declarations?




Q: Can an unreachable object become reachable again?
A: An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects.
[Received from P Rajesh]



Q: What method must be implemented by all threads?
A: All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface.
[ Received from P Rajesh]



Q: What are synchronized methods and synchronized statements?
A: Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
[ Received from P Rajesh]



Q: What is Externalizable?
A: Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)
[ Received from Venkateswara Manam]



Q: What modifiers are allowed for methods in an Interface?
A: Only public and abstract modifiers are allowed for methods in interfaces.
[ Received from P Rajesh]



Q: What are some alternatives to inheritance?
A: Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn't force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).
[ Received from P Rajesh]



Q: What does it mean that a method or field is "static"?
A: Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class.
Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That's how library methods like System.out.println() work out is a static field in the java.lang.System class.
[ Received from P Rajesh]



Q: What is the difference between preemptive scheduling and time slicing?
A: Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
[ Received from P Rajesh]



Q: What is the catch or declare rule for method declarations?
A: If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.
[ Received from P Rajesh]

Java Interview Questions




Question: Is Empty .java file a valid source file?

Question: Can a .java file contain more than one java classes?

Question: Is String a primitive data type in Java?

Question: Is main a keyword in Java?

Question: Is next a keyword in Java?

Question: Is delete a keyword in Java?

Question: Is exit a keyword in Java?

Question: What happens if you dont initialize an instance variable of any of the primitive types in Java?

Question: What will be the initial value of an object reference which is defined as an instance variable?

Question: What are the different scopes for Java variables?

Question: What is the default value of the local variables?

Question: How many objects are created in the following piece of code?
MyClass c1, c2, c3;
c1 = new MyClass ();
c3 = new MyClass ();

Question: Can a public class MyClass be defined in a source file named YourClass.java?

Question: Can main method be declared final?

Question: What will be the output of the following statement?
System.out.println ("1" + 3);

Question: What will be the default values of all the elements of an array defined as an instance variable?




Q: Is Empty .java file a valid source file?
A: Yes, an empty .java file is a perfectly valid source file.
[Received from Sandesh Sadhale]


Q: Can a .java file contain more than one java classes?
A: Yes, a .java file contain more than one java classes, provided at the most one of them is a public class.
[ Received from Sandesh Sadhale]



Q: Is String a primitive data type in Java?
A: No String is not a primitive data type in Java, even though it is one of the most extensively used object. Strings in Java are instances of String class defined in java.lang package.
[ Received from Sandesh Sadhale]



Q: Is main a keyword in Java?
A: No, main is not a keyword in Java.
[ Received from Sandesh Sadhale]



Q: Is next a keyword in Java?
A: No, next is not a keyword.
[ Received from Sandesh Sadhale]



Q: Is delete a keyword in Java?
A: No, delete is not a keyword in Java. Java does not make use of explicit destructors the way C++ does.
[ Received from Sandesh Sadhale]



Q: Is exit a keyword in Java?
A: No. To exit a program explicitly you use exit method in System object.
[ Received from Sandesh Sadhale]



Q: What happens if you dont initialize an instance variable of any of the primitive types in Java?
A: Java by default initializes it to the default value for that primitive type. Thus an int will be initialized to 0, a boolean will be initialized to false.
[ Received from Sandesh Sadhale]



Q: What will be the initial value of an object reference which is defined as an instance variable?
A: The object references are all initialized to null in Java. However in order to do anything useful with these references, you must set them to a valid object, else you will get NullPointerExceptions everywhere you try to use such default initialized references.
[ Received from Sandesh Sadhale]



Q: What are the different scopes for Java variables?
A: The scope of a Java variable is determined by the context in which the variable is declared. Thus a java variable can have one of the three scopes at any given point in time.
1. Instance : - These are typical object level variables, they are initialized to default values at the time of creation of object, and remain accessible as long as the object accessible.
2. Local : - These are the variables that are defined within a method. They remain accessbile only during the course of method excecution. When the method finishes execution, these variables fall out of scope.
3. Static: - These are the class level variables. They are initialized when the class is loaded in JVM for the first time and remain there as long as the class remains loaded. They are not tied to any particular object instance.
[ Received from Sandesh Sadhale]



Q: What is the default value of the local variables?
A: The local variables are not initialized to any default value, neither primitives nor object references. If you try to use these variables without initializing them explicitly, the java compiler will not compile the code. It will complain abt the local varaible not being initilized..
[ Received from Sandesh Sadhale]



Q: How many objects are created in the following piece of code?
MyClass c1, c2, c3;
c1 = new MyClass ();
c3 = new MyClass ();
A: Only 2 objects are created, c1 and c3. The reference c2 is only declared and not initialized.
[ Received from Sandesh Sadhale]



Q: Can a public class MyClass be defined in a source file named YourClass.java?
A: No the source file name, if it contains a public class, must be the same as the public class name itself with a .java extension.
[ Received from Sandesh Sadhale]



Q: Can main method be declared final?
A: Yes, the main method can be declared final, in addition to being public static.
[ Received fromSandesh Sadhale]



Q: What will be the output of the following statement?
System.out.println ("1" + 3);
A: It will print 13.
[ Received from Sandesh Sadhale]



Q: What will be the default values of all the elements of an array defined as an instance variable?
A: If the array is an array of primitive types, then all the elements of the array will be initialized to the default value corresponding to that primitive type. e.g. All the elements of an array of int will be initialized to 0, while that of boolean type will be initialized to false. Whereas if the array is an array of references (of any type), all the elements will be initialized to null.
[ Received from Sandesh Sadhale]





Java Collection Interview Questions

Question: What is the Collections API?

Question: What is the List interface?

Question: What is the Vector class?

Question: What is an Iterator interface?

Question: Which java.util classes and interfaces support event handling?

Question: What is the GregorianCalendar class?

Question: What is the Locale class?

Question: What is the SimpleTimeZone class?

Question: What is the Map interface?

Question: What is the highest-level event class of the event-delegation model?

Question: What is the Collection interface?

Question: What is the Set interface?

Question: What is the typical use of Hashtable?

Question: I am trying to store an object using a key in a Hashtable. And some other object already exists in that location, then what will happen? The existing object will be overwritten? Or the new object will be stored elsewhere?

Question: What is the difference between the size and capacity of a Vector?

Question: Can a vector contain heterogenous objects?


Q: What is the Collections API?
A: The Collections API is a set of classes and interfaces that support operations on collections of objects.
[ Received from Prasanna Inamanamelluri]



Q: What is the List interface?
A: The List interface provides support for ordered collections of objects.
[ Received from SPrasanna Inamanamelluri]



Q: What is the Vector class?
A: The Vector class provides the capability to implement a growable array of objects.
[ Received from Prasanna Inamanamelluri]



Q: What is an Iterator interface?
A: The Iterator interface is used to step through the elements of a Collection .
[ Received from Prasanna Inamanamelluri]



Q: Which java.util classes and interfaces support event handling?
A: The EventObject class and the EventListener interface support event processing.
[ Received from Prasanna Inamanamelluri]



Q: What is the GregorianCalendar class?
A: The GregorianCalendar provides support for traditional Western calendars
[ Received from Prasanna Inamanamelluri]



Q: What is the Locale class?
A: The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region .
[ Received from Prasanna Inamanamelluri]



Q: What is the SimpleTimeZone class?
A: The SimpleTimeZone class provides support for a Gregorian calendar .
[ Received from Prasanna Inamanamelluri]



Q: What is the Map interface?
A: The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.
[ Received from Prasanna Inamanamelluri]



Q: What is the highest-level event class of the event-delegation model?
A: The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy.
[ Received from Prasanna Inamanamelluri]



Q: What is the Collection interface?
A: The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates.
[ Received from Prasanna Inamanamelluri]



Q: What is the Set interface?
A: The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.
[ Received from Prasanna Inamanamelluri]



Q: What is the typical use of Hashtable?
A: Whenever a program wants to store a key value pair, one can use Hashtable.
[ Received from Sandesh Sadhale]



Q: I am trying to store an object using a key in a Hashtable. And some other object already exists in that location, then what will happen? The existing object will be overwritten? Or the new object will be stored elsewhere?
A: The existing object will be overwritten and thus it will be lost.
[ Received from Sandesh Sadhale]



Q: What is the difference between the size and capacity of a Vector?
A: The size is the number of elements actually stored in the vector, while capacity is the maximum number of elements it can store at a given instance of time.
[ Received from Sandesh Sadhale]



Q: Can a vector contain heterogenous objects?
A: Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.
[ Received from Sandesh Sadhale]



Q: Can a ArrayList contain heterogenous objects?
A: Yes a ArrayList can contain heterogenous objects. Because a ArrayList stores everything in terms of Object.
[ Received from Sandesh Sadhale]



Q: What is an enumeration?
A: An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.
[ Received from Sandesh Sadhale]



Q: Considering the basic properties of Vector and ArrayList, where will you use Vector and where will you use ArrayList?
A: The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure will give better performance than the synchronized one.
[ Received from Sandesh Sadhale]



Q: Can a vector contain heterogenous objects?
A: Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.
[ Received from Sandesh Sadhale]

C/C++ Algorithm for Interview

1. Reverse a singly linked list


//
// iterative version
//
Node* ReverseList( Node ** List )
{

Node *temp1 = *List;
Node * temp2 = NULL;
Node * temp3 = NULL;

while ( temp1 )
{
*List = temp1; //set the head to last node
temp2= temp1->pNext; // save the next ptr in temp2
temp1->pNext = temp3; // change next to privous
temp3 = temp1;
temp1 = temp2;
}

return *List;
}


2. Delete a node in double linked list


void deleteNode(node *n)
{
node *np = n->prev;
node *nn = n->next;
np->next = n->next;
nn->prev = n->prev;
delete n;
}


3. Sort a linked list

//sorting in descending order
struct node
{
int value;
node* NEXT;
}
//Assume HEAD pointer denotes the first element in the //linked list
// only change the values…don’t have to change the //pointers

Sort( Node *Head)
{
node* first,second,temp;
first= Head;
while(first!=null)
{
second=first->NEXT;
while(second!=null)
{
if(first->value < second->value)
{
temp = new node();
temp->value=first->value;
first->value=second->value;
second->value=temp->value;
delete temp;
}
second=second->NEXT;
}

first=first->NEXT;
}
}


4. Reverse a string

void ReverseString (char *String)
{
char *Begin = String;
char *End = String + strlen(String) - 1;
char TempChar = '\0';

while (Begin < End)
{
TempChar = *Begin;
*Begin = *End;
*End = TempChar;
Begin++;
End--;
}
}


5. Insert a node a sorted linked list

void sortedInsert(Node * head, Node* newNode)
{
Node *current = head;

// traverse the list until you find item bigger the // new node value
//
while (current!= NULL && current->data < newNode->data)
{
current = current->next);
}
//
// insert the new node before the big item
//
newNode->next = current->next;
current = newNode;
}



6. Covert a string to upper case

void ToUpper(char * S)
{
while (*S!=0)
{
*S=(*S >= 'a' && *S <= 'z')?(*S-'a'+'A'):*S;
S++;
}
}


7. Multiple a number by 7 without using * and + operator.

NewNum = Num << 3; // mulitplied by 2 ^ 3 = 8

NewNum = NewNum - Num; // 8 – 1 = 7


8. Write a function that takes in a string parameter and checks to see whether or not it is an integer, and if it is then return the integer value.

#include

int strtoint(char *s)
{
int index = 0, flag = 0;

while( *(s+index) != '\0')
{
if( (*(s + index) >= '0') &&
*(s + index) <= '9')
{
flag = 1;
index++;
}
else
{
flag = 0;
break;
}
}

if( flag == 1 )
return atoi(s);
else
return 0;
}

main()
{
printf("%d",strtoint("0123"));
printf("\n%d",strtoint("0123ii"));
}



9. Print a data from a binary tree – In-order(ascending)

//
// recursive version
//

Void PrintTree ( struct * node node )
{
if ( node == NULL )
return;

PrintTree(node->left );
Printf(“%d”, node->data);
PrintTree(node->right );
}

10. print integer using only putchar

//
// recursive version
//
void PrintNum ( int Num )
{
if ( Num == 0 )
return;
PrintNum ( Num / 10 );
Puthcar ( ‘0’+ Num % 10 );
}

11. Find the factorial of number

//
// recursive version
//

int Factorial( int Num )
{

If ( num > 0 )
return Num * Factorial ( Num –1 );
else
return 1;
}


//
// iterative version
//

int Factorial( int Num )
{
int I
int result = 1;

for ( I= Num; I > 0; I-- )
{
result = result * I;
}

return result;
}


12. Generate Fib numbers:

int fib( n ) // recursive version
{

if ( n < 2 )
return 1;
else
return fib ( n –1 ) + fib ( n –2 );

}

int fib( n ) //iterative version
{
int f1 =1, f2 = 1;

if ( n < 2 )
return 1;
for ( i = 1; i < N; i++)
{
f = f1 + f2;
f1= f2;
f = f1;
}

return f;
}







13. Write a function that finds the last instance of a character in a string

char *lastchar(char *String, char ch)
{
char *pStr = NULL;

// traverse the entire string

while( * String ++ != NULL )
{
if( *String == ch )
pStr = String;
}

return pStr;
}

14. Return Nth the node from the end of the linked list in one pass.

Node * GetNthNode ( Node* Head , int NthNode )
{
Node * pNthNode = NULL;
Node * pTempNode = NULL;
int nCurrentElement = 0;

for ( pTempNode = Head; pTempNode != NULL; pTempNode = pTempNode->pNext )
{
nCurrentElement++;
if ( nCurrentElement - NthNode == 0 )
{
pNthNode = Head;
}
else
if ( nCurrentElement - NthNode > 0)
{
pNthNode = pNthNode ->pNext;
}
}
if (pNthNode )
{
return pNthNode;
}
else
return NULL;
}



15. Counting set bits in a number.

First version:

int CoutSetBits(int Num)
{

for(int count=0; Num; Num >>= 1)
{
if (Num & 1)
count++;
}
return count;
}


Optimized version:

int CoutSetBits(int Num)
{

for(int count =0; Num; count++)
{
Num &= Num -1;
}
}

DBMS Interview Question and Answer

DBMS Interview Questions and Answers
QUESTION 1:
What is database?
ANSWER:
A database is a logically coherent collection of data with some inherent meaning, representing some aspect of real world and which is designed, built and populated with data for a specific purpose.
QUESTION 2:
What is DBMS?
ANSWER:
• Redundancy is controlled.
• Unauthorised access is restricted.
• Providing multiple user interfaces.
• Enforcing integrity constraints.
• Providing backup and recovery.
QUESTION 4:
What is a Database system?
ANSWER:
The database and DBMS software together is called as Database system.
QUESTION 5:
Disadvantage in File Processing System?
ANSWER:
• Data redundancy & inconsistency.
• Difficult in accessing data.
• Data isolation.
• Data integrity.
• Concurrent access is not possible.
• Security Problems. .
QUESTION 6:
Describe the three levels of data abstraction?
ANSWER:
The are three levels of abstraction:
• Physical level: The lowest level of abstraction describes how data are stored.
• Logical level: The next higher level of abstraction, describes what data are stored in database and what relationship among those data.
• View level: The highest level of abstraction describes only part of entire database.
QUESTION 7:
Define the "integrity rules"
ANSWER:
There are two Integrity rules.
• Entity Integrity: States that “Primary key cannot have NULL value”
• Referential Integrity: States that “Foreign Key can be either a NULL value or should be Primary Key value of other relation.
QUESTION 8:
What is extension and intension?
ANSWER:
Extension -It is the number of tuples present in a table at any instance. This is time dependent.
Intension - It is a constant value that gives the name, structure of table and the constraints laid on it.
QUESTION 9:
What is System R? What are its two major subsystems?
ANSWER:
System R was designed and developed over a period of 1974-79 at IBM San Jose Research Center . It is a prototype and its purpose was to demonstrate that it is possible to build a Relational System that can be used in a real life environment to solve real life problems, with performance at least comparable to that of existing system.
Its two subsystems are
• Research Storage
• System Relational Data System.
QUESTION 10:
How is the data structure of System R different from the relational structure?
ANSWER:
Unlike Relational systems in System R
• Domains are not supported
• Enforcement of candidate key uniqueness is optional
• Enforcement of entity integrity is optional
• Referential integrity is not enforced
QUESTION 11:
What is Data Independence?
ANSWER:
Data independence means that “the application is independent of the storage structure and access strategy of data”. In other words, The ability to modify the schema definition in one level should not affect the schema definition in the next higher level.
Two types of Data Independence:
• Physical Data Independence : Modification in physical level should not affect the logical level.
• Logical Data Independence : Modification in logical level should affect the view level.
NOTE: Logical Data Independence is more difficult to achieve
QUESTION 12:
What is a view? How it is related to data independence?
ANSWER:
A view may be thought of as a virtual table, that is, a table that does not really exist in its own right but is instead derived from one or more underlying base table. In other words, there is no stored file that direct represents the view instead a definition of view is stored in data dictionary.
Growth and restructuring of base tables is not reflected in views. Thus the view can insulate users from the effects of restructuring and growth in the database. Hence accounts for logical data independence. .
QUESTION 13:
What is Data Model?
ANSWER:
A collection of conceptual tools for describing data, data relationships data semantics and constraints.
QUESTION 14:
What is E-R model?
ANSWER:
This data model is based on real world that consists of basic objects called entities and of relationship among these objects. Entities are described in a database by a set of attributes.
QUESTION 15:
What is Object Oriented model?
ANSWER:
This model is based on collection of objects. An object contains values stored in instance variables with in the object. An object also contains bodies of code that operate on the object. These bodies of code are called methods. Objects that contain same types of values and the same methods are grouped together into classes.
QUESTION 16:
What is an Entity?
ANSWER:
It is a 'thing' in the real world with an independent existence.
QUESTION 17:
What is an Entity type?
ANSWER:
It is a collection (set) of entities that have same attributes.
QUESTION 18:
What is an Entity set?
ANSWER:
It is a collection of all entities of particular entity type in the database.
QUESTION 19:
What is an Extension of entity type?
ANSWER:
The collections of entities of a particular entity type are grouped together into an entity set.
QUESTION 20:
What is Weak Entity set?
ANSWER:
An entity set may not have sufficient attributes to form a primary key, and its primary key compromises of its partial key and primary key of its parent entity, then it is said to be Weak Entity set.
QUESTION 21:
What is an attribute?
ANSWER:
It is a particular property, which describes the entity.
QUESTION 22:
What is a Relation Schema and a Relation?
ANSWER:
A relation Schema denoted by R(A1, A2, …, An) is made up of the relation name R and the list of attributes Ai that it contains. A relation is defined as a set of tuples. Let r be the relation which contains set tuples (t1, t2, t3, ..., tn). Each tuple is an ordered list of n-values t=(v1,v2, ..., vn).
QUESTION 23:
What is degree of a Relation?
ANSWER:
It is the number of attribute of its relation schema.
QUESTION 24:
What is Relationship?
ANSWER:
It is an association among two or more entities.
QUESTION 25:
What is Relationship set?
ANSWER:
The collection (or set) of similar relationships.
QUESTION 26:
What is Relationship type?
ANSWER:
Relationship type defines a set of associations or a relationship set among a given set of entity types.
QUESTION 27:
What is degree of Relationship type?
ANSWER:
It is the number of entity type participating.
QUESTION 28:
What is Data Storage - Definition Language?
ANSWER:
The storage structures and access methods used by database system are specified by a set of definition in a special type of DDL called data storage-definition language.
QUESTION 29:
What is DML (Data Manipulation Language)?
ANSWER:
This language that enable user to access or manipulate data as organised by appropriate data model.
• Procedural DML or Low level: DML requires a user to specify what data are needed and how to get those data.
• Non-Procedural DML or High level: DML requires a user to specify what data are needed without specifying how to get those data.
QUESTION 30:
What is VDL (View Definition Language)?
ANSWER:
It specifies user views and their mappings to the conceptual schema.
QUESTION 31:
What is DML Compiler?
ANSWER:
It translates DML statements in a query language into low-level instruction that the query evaluation engine can understand.
QUESTION 32:
What is Query evaluation engine?
ANSWER:
It executes low-level instruction generated by compiler.
QUESTION 33:
What is DDL Interpreter?
ANSWER:
It interprets DDL statements and record them in tables containing metadata.
QUESTION 34:
What is Record-at-a-time?
ANSWER:
The Low level or Procedural DML can specify and retrieve each record from a set of records. This retrieve of a record is said to be Record-at-a-time.
QUESTION 35:
What is Set-at-a-time or Set-oriented?
ANSWER:
The High level or Non-procedural DML can specify and retrieve many records in a single DML statement. This retrieve of a record is said to be Set-at-a-time or Set-oriented.
QUESTION 36:
What is Relational Algebra?
ANSWER:
It is procedural query language. It consists of a set of operations that take one or two relations as input and produce a new relation.
QUESTION 37:
What is Relational Calculus?
ANSWER:
It is an applied predicate calculus specifically tailored for relational databases proposed by E.F. Codd. E.g. of languages based on it are DSL ALPHA, QUEL.
QUESTION 38:
How does Tuple-oriented relational calculus differ from domain-oriented relational calculus
ANSWER:
The tuple-oriented calculus uses a tuple variables i.e., variable whose only permitted values are tuples of that relation. E.g. QUEL
The domain-oriented calculus has domain variables i.e., variables that range over the underlying domains instead of over relation. E.g. ILL, DEDUCE.
QUESTION 39:
What is normalization?
ANSWER:
It is a process of analysing the given relation schemas based on their Functional Dependencies (FDs) and primary key to achieve the properties
• Minimizing redundancy
• Minimizing insertion, deletion and update anomalies.
QUESTION 40:
What is Functional Dependency?
ANSWER:
A Functional dependency is denoted by X Y between two sets of attributes X and Y that are subsets of R specifies a constraint on the possible tuple that can form a relation state r of R. The constraint is for any two tuples t1 and t2 in r if t1[X] = t2[X] then they have t1[Y] = t2[Y]. This means the value of X component of a tuple uniquely determines the value of component Y.
QUESTION 41:
When is a functional dependency F said to be minimal?
ANSWER:
• Every dependency in F has a single attribute for its right hand side.
• We cannot replace any dependency X A in F with a dependency Y A where Y is a proper subset of X and still have a set of dependency that is equivalent to F.
• We cannot remove any dependency from F and still have set of dependency that is equivalent to F.
QUESTION 42:
What is Multivalued dependency?
ANSWER:
Multivalued dependency denoted by X Y specified on relation schema R, where X and Y are both subsets of R, specifies the following constraint on any relation r of R: if two tuples t1 and t2 exist in r such that t1[X] = t2[X] then t3 and t4 should also exist in r with the following properties
• t3[x] = t4[X] = t1[X] = t2[X]
• t3[Y] = t1[Y] and t4[Y] = t2[Y]
• t3[Z] = t2[Z] and t4[Z] = t1[Z]
where [Z = (R-(X U Y)) ]
QUESTION 43:
What is Lossless join property?
ANSWER:
It guarantees that the spurious tuple generation does not occur with respect to relation schemas after decomposition.
QUESTION 44:
What is 1 NF (Normal Form)?
ANSWER:
The domain of attribute must include only atomic (simple, indivisible) values.
QUESTION 45:
What is Fully Functional dependency?
ANSWER:
It is based on concept of full functional dependency. A functional dependency X Y is full functional dependency if removal of any attribute A from X means that the dependency does not hold any more.
QUESTION 46:
What is 2NF?
ANSWER:
A relation schema R is in 2NF if it is in 1NF and every non-prime attribute A in R is fully functionally dependent on primary key.
QUESTION 47:
What is 3NF?
ANSWER:
A relation schema R is in 3NF if it is in 2NF and for every FD X A either of the following is true
• X is a Super-key of R.
• A is a prime attribute of R.
In other words, if every non prime attribute is non-transitively dependent on primary key.
QUESTION 48:
What is BCNF (Boyce-Codd Normal Form)?
ANSWER:
A relation schema R is in BCNF if it is in 3NF and satisfies an additional constraint that for every FD X A, X must be a candidate key.
QUESTION 49:
What is 4NF?
ANSWER:
A relation schema R is said to be in 4NF if for every Multivalued dependency X Y that holds over R, one of following is true
• X is subset or equal to (or) XY = R.
• X is a super key.
QUESTION 50:
What is 5NF?
ANSWER:
A Relation schema R is said to be 5NF if for every join dependency {R1, R2, ..., Rn} that holds R, one the following is true
• Ri = R for some i.
• The join dependency is implied by the set of FD, over R in which the left side is key of R.