What are loops?
How would you explain Count Down_to_Zero Loop?
Can you explain what Count_Up_Loops mean?
What is the difference between Count Down_to_Zero Loop and Count_Up_Loops? Which one is better to use?
Explain Interrupt Latency. How can we reduce it?
Is it possible to pass structures to the functions by value?
Can arrays be passed to functions by value?
Can you name the different qualifiers in C?
How would you describe inline functions?
What are ARM compilers? What are its functions?
What are static variables? What is the scope of static variable?
What are BSD and SVR4? What are the different communication mechanisms in BSD and SVR4?
What is pSOS? What are the different features in pSOS?
There are three ways to write infinite loops? Explain them. Which one of the three is the most efficient method?
How do you find out the number of instance of a class?
How would you explain forward reference with respect to pointers in C?
What are the advantages of using a macro function?
Is it possible to have constant volatile variable? Explain.
What are object oriented languages and object based languages? Is there a difference between the two?
How would a global variable result in unoptimized code?
Can you name the different storage classes in C?
Is it possible to have inline virtual functions in a class?
Do inline functions help to improve performance? Explain in what way?
What are the advantages and disadvantages of using inline functions?
Explain the difference between hard real-time and soft real-time Operating systems.
Friday, June 17, 2011
Embedded C interview Questions for Embedded Systems Engineers
Q: Which is the best way to write Loops?
Q: Is Count Down_to_Zero Loop better than Count_Up_Loops?
A: Always, count Down to Zero loops are better.
This is because,at loop termination, comparison to Zero can be optimized by complier. (Eg using SUBS)
Else, At the end of the loop there is ADD and CMP.
Q: What is loop unrolling?
A: Small loops can be unrolled for higher performance, with the disadvantage of increased
codesize. When a loop is unrolled, a loop counter needs to be updated less often and
fewer branches are executed. If the loop iterates only a few times, it can be fully unrolled,
so that the loop overhead completely disappears.
eg:
int countbit1(uint n)
{ int bits = 0;
while (n != 0)
{
if (n & 1) bits++;
n >>= 1;
}
return bits;
}
int countbit2(uint n)
{ int bits = 0;
while (n != 0)
{
if (n & 1) bits++;
if (n & 2) bits++;
if (n & 4) bits++;
if (n & 8) bits++;
n >>= 4;
}
return bits;
}
Q: How does, taking the address of local variable result in unoptimized code?
A: The most powerful optimization for compliler is register allocation. That is it operates the variable from register, than memory. Generally local variables are allocated in registers. However if we take the address of a local variable, compiler will not allocate the variable to register.
Q: How does global variable result in unoptimized code?
A: For the same reason as above, compiler will never put the global variable into register. So its bad.
Q: So how to overcome this problem?
A: When it is necessary to take the address of variables, (for example if they are passed as a
reference parameter to a function). Make a copy of the variable, and pass the address of that copy.
Q: Which is better a char, short or int type for optimization?
A: Where possible, it is best to avoid using char and short as local variables. For the types
char and short the compiler needs to reduce the size of the local variable to 8 or 16 bits
after each assignment. This is called sign-extending for signed variables and zeroextending
for unsigned variables. It is implemented by shifting the register left by 24 or 16
bits, followed by a signed or unsigned shift right by the same amount, taking two
instructions (zero-extension of an unsigned char takes one instruction).
These shifts can be avoided by using int and unsigned int for local variables. This
is particularly important for calculations which first load data into local variables and then
process the data inside the local variables. Even if data is input and output as 8- or 16-bit
quantities, it is worth considering processing them as 32-bit quantities.
Q: How to reduce function call overhead in ARM based systems?
A:
. Try to ensure that small functions take four or fewer arguments. These will not use
the stack for argument passing. It will copied into registers.
· If a function needs more than four arguments, try to ensure that it does a
significant amount of work, so that the cost of passing the stacked arguments is
outweighed.
· Pass pointers to structures instead of passing the structure itself.
· Put related arguments in a structure, and pass a pointer to the structure to
functions. This will reduce the number of parameters and increase readability.
· Minimize the number of long long parameters, as these take two argument words.
This also applies to doubles if software floating-point is enabled.
· Avoid functions with a parameter that is passed partially in a register and partially
on the stack (split-argument). This is not handled efficiently by the current
compilers: all register arguments are pushed on the stack.
· Avoid functions with a variable number of parameters. Varargs functions
Q: What is a pure function in ARM terminology?
A: Pure functions are those which return a result which depends only on their arguments.
They can be thought of as mathematical functions: they always return the same result if
the arguments are the same. To tell the compiler that a function is pure, use the special
declaration keyword __pure.
__pure int square(int x)
{ return x * x;
}
Compiler does optimization for pure functions. For example, the values which are allocated to
memory can be safely cached in registers, instead of being written to memory before a call
and reloaded afterwards.
Q: What are inline functions?
A: The ARM compilers support inline functions with the keyword __inline. This results in
each call to an inline function being substituted by its body, instead of a normal call. This
results in faster code, but it adversely affects code size, particularly if the inline function is
large and used often.
Q: Is Count Down_to_Zero Loop better than Count_Up_Loops?
A: Always, count Down to Zero loops are better.
This is because,at loop termination, comparison to Zero can be optimized by complier. (Eg using SUBS)
Else, At the end of the loop there is ADD and CMP.
Q: What is loop unrolling?
A: Small loops can be unrolled for higher performance, with the disadvantage of increased
codesize. When a loop is unrolled, a loop counter needs to be updated less often and
fewer branches are executed. If the loop iterates only a few times, it can be fully unrolled,
so that the loop overhead completely disappears.
eg:
int countbit1(uint n)
{ int bits = 0;
while (n != 0)
{
if (n & 1) bits++;
n >>= 1;
}
return bits;
}
int countbit2(uint n)
{ int bits = 0;
while (n != 0)
{
if (n & 1) bits++;
if (n & 2) bits++;
if (n & 4) bits++;
if (n & 8) bits++;
n >>= 4;
}
return bits;
}
Q: How does, taking the address of local variable result in unoptimized code?
A: The most powerful optimization for compliler is register allocation. That is it operates the variable from register, than memory. Generally local variables are allocated in registers. However if we take the address of a local variable, compiler will not allocate the variable to register.
Q: How does global variable result in unoptimized code?
A: For the same reason as above, compiler will never put the global variable into register. So its bad.
Q: So how to overcome this problem?
A: When it is necessary to take the address of variables, (for example if they are passed as a
reference parameter to a function). Make a copy of the variable, and pass the address of that copy.
Q: Which is better a char, short or int type for optimization?
A: Where possible, it is best to avoid using char and short as local variables. For the types
char and short the compiler needs to reduce the size of the local variable to 8 or 16 bits
after each assignment. This is called sign-extending for signed variables and zeroextending
for unsigned variables. It is implemented by shifting the register left by 24 or 16
bits, followed by a signed or unsigned shift right by the same amount, taking two
instructions (zero-extension of an unsigned char takes one instruction).
These shifts can be avoided by using int and unsigned int for local variables. This
is particularly important for calculations which first load data into local variables and then
process the data inside the local variables. Even if data is input and output as 8- or 16-bit
quantities, it is worth considering processing them as 32-bit quantities.
Q: How to reduce function call overhead in ARM based systems?
A:
. Try to ensure that small functions take four or fewer arguments. These will not use
the stack for argument passing. It will copied into registers.
· If a function needs more than four arguments, try to ensure that it does a
significant amount of work, so that the cost of passing the stacked arguments is
outweighed.
· Pass pointers to structures instead of passing the structure itself.
· Put related arguments in a structure, and pass a pointer to the structure to
functions. This will reduce the number of parameters and increase readability.
· Minimize the number of long long parameters, as these take two argument words.
This also applies to doubles if software floating-point is enabled.
· Avoid functions with a parameter that is passed partially in a register and partially
on the stack (split-argument). This is not handled efficiently by the current
compilers: all register arguments are pushed on the stack.
· Avoid functions with a variable number of parameters. Varargs functions
Q: What is a pure function in ARM terminology?
A: Pure functions are those which return a result which depends only on their arguments.
They can be thought of as mathematical functions: they always return the same result if
the arguments are the same. To tell the compiler that a function is pure, use the special
declaration keyword __pure.
__pure int square(int x)
{ return x * x;
}
Compiler does optimization for pure functions. For example, the values which are allocated to
memory can be safely cached in registers, instead of being written to memory before a call
and reloaded afterwards.
Q: What are inline functions?
A: The ARM compilers support inline functions with the keyword __inline. This results in
each call to an inline function being substituted by its body, instead of a normal call. This
results in faster code, but it adversely affects code size, particularly if the inline function is
large and used often.
.net interview questions with answers 2010 for freshers
1. Differences between DLL and EXE?
.exe
1.These are outbound file.
2.Only one .exe file exists per application.
3. .Exe cannot be shared with other applications.
.dll
1.These are inbund file .
2.Many .dll files may exists in one application.
3. .dll can be shared with other applications.
2. Can an assembly have EXE?
Assembly is nothing but single deployment and self describing. Yes Assembly can have dll/exe.
3. Can a DLL be changed to an EXE?
In short, the answer is no. Unlike an EXE file which contains a single entry point (typically WinMain() or simply main() depending on the type of exe file), a DLL file is a library of functions intended to be linked into a running application. A DLL file can have a nearly infinite (it’s based on file size and such) possible entry points.
4. Compare & contrast rich client (smart clients or Windows-based) & browser-based Web application
When implementing a client/server architecture you need to determine if it will be the client or the server that handles the bulk of the workload. By client, we mean the application that runs on a PC or workstation and relies on a server to perform some operations.
In last week’s Did You Know article we discussed the differences between thick clients (also called fat clients) and thin clients in terms of hardware. The terms thick client and thin client, however, have double meanings, as thick and thin also are used to describe the applications or software. In this article we take a look at the terms thick and thin as related to client application software.
5. Compare Client server application with n-Tier application
All web applications are N-Tier architectures. An N-Tier architecture is really a Client-Server architecture combined with the Layered architecture. The reason why I combine Client-Server and N-Tier here is because they are very much related.
A Client-Server system is one in which the server performs some kind of service that is used by many clients. The clients take the lead in the communication. The basic Client-Server architecture has 2 tiers (Client and Server).
6. Can a try block have more than one catch block?
Yes, It can have as many as you want. It allows you to catch very specific exceptions.
7. Can a try block have nested try blocks?
Yes perfectly legal, but not always it is useful.
8. How do you load an assembly at runtime?
Here is the sample code, hope it will help
Loader.AssemblyLoader assLoader = null;
object[] parms = { AssemblyName }; // string AssebmlyName
assLoader = (Loader.AssemblyLoader)domain.CreateInstanceFromAndUnwrap(
“yourAssemply.dll”, “Loader.AssemblyLoader”, true, bindings, null, parms,
null, null, null);
9. If I am writing in a language like VB or C++, what are the procedures to be followed to support .NET?
If you want your VB6 or C++ code to be used with .NET code your code should be CLS compliant….
What is CLS-Compliant?
One of the greatest advantages of .net is that you can write code in a variety of different languages and it all translates to MSIL at the end and is run by the CLR. That’s a wonderful feature, however languages themselves differ in the kind of features that they support. For example C# supports operator overloading while some languages do not.
To resolve this Microsoft introduced the Common Language Specification. Basically, if your code is CLS Compliant it means that all your code is guaranteed to be callable by any .Net module. You can accomplish this by using the CLSCompliant assembly attribute:
1: [assembly: CLSCompliant(true)]
CLS is a subset of the Common Type System / Common Language Runtime. For more information on making your assemblies CLS Compliant check out this article on MSDN http://msdn2.Microsoft.com/en-us/library/bhc3fa7f(VS.71).aspx
10. How do you view the methods and members of a DLL?
Go to visual studio 2003/2005 command prompt and type “ildasm”. It will open a window. In that window load ur dll, it will show all the methods and members.
11. What is shadowing?
Shadowing is either through scope or through inheritance. Shadowing through inheritance is hiding a method of a base class and providing a new implementation for the same. This is the default when a derived class writes an implementation of a method of base class which is not declared as overridden in the base class. This also serves the purpose of protecting an implementation of a new method against subsequent addition of a method with the same name in the base class.’shadows’ keyword is recommended although not necessary since it is the default.
12. What are the collections you’ve used?
.Net collections that you have used.
.exe
1.These are outbound file.
2.Only one .exe file exists per application.
3. .Exe cannot be shared with other applications.
.dll
1.These are inbund file .
2.Many .dll files may exists in one application.
3. .dll can be shared with other applications.
2. Can an assembly have EXE?
Assembly is nothing but single deployment and self describing. Yes Assembly can have dll/exe.
3. Can a DLL be changed to an EXE?
In short, the answer is no. Unlike an EXE file which contains a single entry point (typically WinMain() or simply main() depending on the type of exe file), a DLL file is a library of functions intended to be linked into a running application. A DLL file can have a nearly infinite (it’s based on file size and such) possible entry points.
4. Compare & contrast rich client (smart clients or Windows-based) & browser-based Web application
When implementing a client/server architecture you need to determine if it will be the client or the server that handles the bulk of the workload. By client, we mean the application that runs on a PC or workstation and relies on a server to perform some operations.
In last week’s Did You Know article we discussed the differences between thick clients (also called fat clients) and thin clients in terms of hardware. The terms thick client and thin client, however, have double meanings, as thick and thin also are used to describe the applications or software. In this article we take a look at the terms thick and thin as related to client application software.
5. Compare Client server application with n-Tier application
All web applications are N-Tier architectures. An N-Tier architecture is really a Client-Server architecture combined with the Layered architecture. The reason why I combine Client-Server and N-Tier here is because they are very much related.
A Client-Server system is one in which the server performs some kind of service that is used by many clients. The clients take the lead in the communication. The basic Client-Server architecture has 2 tiers (Client and Server).
6. Can a try block have more than one catch block?
Yes, It can have as many as you want. It allows you to catch very specific exceptions.
7. Can a try block have nested try blocks?
Yes perfectly legal, but not always it is useful.
8. How do you load an assembly at runtime?
Here is the sample code, hope it will help
Loader.AssemblyLoader assLoader = null;
object[] parms = { AssemblyName }; // string AssebmlyName
assLoader = (Loader.AssemblyLoader)domain.CreateInstanceFromAndUnwrap(
“yourAssemply.dll”, “Loader.AssemblyLoader”, true, bindings, null, parms,
null, null, null);
9. If I am writing in a language like VB or C++, what are the procedures to be followed to support .NET?
If you want your VB6 or C++ code to be used with .NET code your code should be CLS compliant….
What is CLS-Compliant?
One of the greatest advantages of .net is that you can write code in a variety of different languages and it all translates to MSIL at the end and is run by the CLR. That’s a wonderful feature, however languages themselves differ in the kind of features that they support. For example C# supports operator overloading while some languages do not.
To resolve this Microsoft introduced the Common Language Specification. Basically, if your code is CLS Compliant it means that all your code is guaranteed to be callable by any .Net module. You can accomplish this by using the CLSCompliant assembly attribute:
1: [assembly: CLSCompliant(true)]
CLS is a subset of the Common Type System / Common Language Runtime. For more information on making your assemblies CLS Compliant check out this article on MSDN http://msdn2.Microsoft.com/en-us/library/bhc3fa7f(VS.71).aspx
10. How do you view the methods and members of a DLL?
Go to visual studio 2003/2005 command prompt and type “ildasm”. It will open a window. In that window load ur dll, it will show all the methods and members.
11. What is shadowing?
Shadowing is either through scope or through inheritance. Shadowing through inheritance is hiding a method of a base class and providing a new implementation for the same. This is the default when a derived class writes an implementation of a method of base class which is not declared as overridden in the base class. This also serves the purpose of protecting an implementation of a new method against subsequent addition of a method with the same name in the base class.’shadows’ keyword is recommended although not necessary since it is the default.
12. What are the collections you’ve used?
.Net collections that you have used.
Java server pages |jsp interview questions |answers for freshers
Q: What is a output comment?
A comment that is sent to the client in the viewable page source.The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.
JSP Syntax
] –>
Example 1
<%= (new java.util.Date()).toLocaleString() %>
–>
Q.Displays in the page source:
Q. What are stored procedures? How is it useful?
A stored procedure is a set of statements/commands which reside in the database. The stored procedure is pre-compiled and saves the database the effort of parsing and compiling sql statements everytime a query is run. Each database has its own stored procedure language, usually a variant of C with a SQL preproceesor. Newer versions of db’s support writing stored procedures in Java and Perl too. Before the advent of 3-tier/n-tier architecture it was pretty common for stored procs to implement the business logic( A lot of systems still do it). The biggest advantage is of course speed. Also certain kind of data manipulations are not achieved in SQL. Stored procs provide a mechanism to do these manipulations. Stored procs are also useful when you want to do Batch updates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC Connection may be significant in these cases.
Q.What is a Hidden Comment?
A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or “comment out” part of your JSP page.
You can use any characters in the body of the comment except the closing –%> combination. If you need to use –%> in your comment, you can escape it by typing –%\>.
JSP Syntax
<%– comment –%>
Examples
<%@ page %>
A Hidden Comment
<%– This comment will not be visible to the colent in the page source –%>
Q.How do I include static files within a JSP page?
Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.
Q.What are the two kinds of comments in JSP and what’s the difference between them.
<%– JSP Comment –%>
Q.What is JSP technology?
Java Server Page is a standard Java extension that is defined on top of the servlet Extensions. The goal of JSP is the simplified creation and management of dynamic Web pages. JSPs are secure, platform-independent, and best of all, make use of Java as a server-side scripting language.
Q. What is JSP page?
A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format such as HTML, SVG, WML, and XML, and JSP elements, which construct dynamic content.
Q. What is a Expression?
An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file. Like
<%= someexpression %>
<%= (new java.util.Date()).toLocaleString() %>
You cannot use a semicolon to end an expression
Q.What is a Declaration?
A declaration declares one or more variables or methods for use later in the JSP source file.
A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file.
<%! somedeclarations %>
<%! int i = 0; %>
<%! int a, b, c; %>
Q.What is a Scriptlet?
A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.Within scriptlet tags, you can
1.Declare variables or methods to use later in the file (see also Declaration).
2.Write expressions valid in the page scripting language (see also Expression).
3.Use any of the JSP implicit objects or any object declared with a tag.
You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.
Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it.
Q.What are the implicit objects?
Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are:
–request
–response
–pageContext
–session
–application
–out
–config
–page
–exception
Q. How many JSP scripting elements and what are they?
There are three scripting language elements:
–declarations
–scriptlets
–expressions
Q. Why are JSP pages the preferred API for creating a web-based client program?
Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.
Q.Is JSP technology extensible?
YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.
Q. Can we use the constructor, instead of init(), to initialize servlet?
Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.
Q. How can a servlet refresh automatically if some new data has entered the database?
You can use a client-side Refresh or Server Push.
A comment that is sent to the client in the viewable page source.The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.
JSP Syntax
] –>
Example 1
<%= (new java.util.Date()).toLocaleString() %>
–>
Q.Displays in the page source:
Q. What are stored procedures? How is it useful?
A stored procedure is a set of statements/commands which reside in the database. The stored procedure is pre-compiled and saves the database the effort of parsing and compiling sql statements everytime a query is run. Each database has its own stored procedure language, usually a variant of C with a SQL preproceesor. Newer versions of db’s support writing stored procedures in Java and Perl too. Before the advent of 3-tier/n-tier architecture it was pretty common for stored procs to implement the business logic( A lot of systems still do it). The biggest advantage is of course speed. Also certain kind of data manipulations are not achieved in SQL. Stored procs provide a mechanism to do these manipulations. Stored procs are also useful when you want to do Batch updates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC Connection may be significant in these cases.
Q.What is a Hidden Comment?
A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or “comment out” part of your JSP page.
You can use any characters in the body of the comment except the closing –%> combination. If you need to use –%> in your comment, you can escape it by typing –%\>.
JSP Syntax
<%– comment –%>
Examples
<%@ page %>
<%– This comment will not be visible to the colent in the page source –%>
Q.How do I include static files within a JSP page?
Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.
Q.What are the two kinds of comments in JSP and what’s the difference between them.
<%– JSP Comment –%>
Q.What is JSP technology?
Java Server Page is a standard Java extension that is defined on top of the servlet Extensions. The goal of JSP is the simplified creation and management of dynamic Web pages. JSPs are secure, platform-independent, and best of all, make use of Java as a server-side scripting language.
Q. What is JSP page?
A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format such as HTML, SVG, WML, and XML, and JSP elements, which construct dynamic content.
Q. What is a Expression?
An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file. Like
<%= someexpression %>
<%= (new java.util.Date()).toLocaleString() %>
You cannot use a semicolon to end an expression
Q.What is a Declaration?
A declaration declares one or more variables or methods for use later in the JSP source file.
A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file.
<%! somedeclarations %>
<%! int i = 0; %>
<%! int a, b, c; %>
Q.What is a Scriptlet?
A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.Within scriptlet tags, you can
1.Declare variables or methods to use later in the file (see also Declaration).
2.Write expressions valid in the page scripting language (see also Expression).
3.Use any of the JSP implicit objects or any object declared with a
You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.
Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it.
Q.What are the implicit objects?
Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are:
–request
–response
–pageContext
–session
–application
–out
–config
–page
–exception
Q. How many JSP scripting elements and what are they?
There are three scripting language elements:
–declarations
–scriptlets
–expressions
Q. Why are JSP pages the preferred API for creating a web-based client program?
Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.
Q.Is JSP technology extensible?
YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.
Q. Can we use the constructor, instead of init(), to initialize servlet?
Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.
Q. How can a servlet refresh automatically if some new data has entered the database?
You can use a client-side Refresh or Server Push.
Q: Difference between forward and sendRedirect?
When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.
Q: What are the different scope valiues for the ?
The different scope values for are
1. page
2. request
3.session
4.application
Q: Explain the life-cycle mehtods in JSP?
A: THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two mehtods – jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests. This interface declares one method _jspService().
The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance.
The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects.
The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.
Q: How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
A: You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.
<%
response.setHeader(“Cache-Control”,”no-store”); //HTTP 1.1
response.setHeader(“Pragma\”,”no-cache”); //HTTP 1.0
response.setDateHeader (“Expires”, 0); //prevents caching at the proxy server
%>
Q: What is the difference b/w variable declared inside a declaration part and variable declared in scriplet part?
A: Variable declared inside declaration part is treated as a global variable.that means after convertion jsp file into servlet that variable will be in outside of service method or it will be declared as instance variable.And the scope is available to complete jsp and to complete in the converted servlet class.where as if u declare a variable inside a scriplet that variable will be declared inside a service method and the scope is with in the service method.
Q: Is there a way to execute a JSP from the comandline or from my own application?
A: There is a little tool called JSPExecutor that allows you to do just that. The developers (Hendrik Schreiber & Peter Rossbach ) aim was not to write a full blown servlet engine, but to provide means to use JSP for generating source code or reports. Therefore most HTTP-specific features (headers, sessions, etc) are not implemented, i.e. no reponseline or header is generated. Nevertheless you can use it to precompile JSP for your website.
Q: How does JSP handle run-time exceptions?
A: You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example:
<%@ page errorPage=\”error.jsp\” %> redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: <%@ page isErrorPage=\”true\” %> Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.
Q: How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?
A: You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe=”false” %> within your JSP page. With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine. More importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use <%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe .
Q: How do I use a scriptlet to initialize a newly instantiated bean?
A: A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.
The following example shows the “today” property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.
value=”<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>” / >
<%– scriptlets calling bean setter methods go here –%>
Q: How can I prevent the word “null” from appearing in my HTML input text fields when I populate them with a resultset that has null values?
A: You could make a simple wrapper function, like
<%!
String blanknull(String s) {
return (s == null) ? \”\” : s;
}
%>
then use it inside your JSP form, like
” >
Q: What’s a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
A: Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading.
Also, note that SingleThreadModel is pretty resource intensive from the server\’s perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free – which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.
Q: How can I enable session tracking for JSP pages if the browser has disabled cookies?
A: We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie.
Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page. Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting.
hello1.jsp
<%@ page session=\”true\” %>
<%
Integer num = new Integer(100);
session.putValue(“num”,num);
String url =response.encodeURL(“hello2.jsp”);
%>
hello2.jsp
<%@ page session=”true” %>
<%
Integer i= (Integer )session.getValue(“num”);
out.println(“Num value in session is ” + i.intValue());
%>
. The code in a finally clause will never fail to execute, right? Using System.exit(1); in try block will not allow finally code to execute.
Q: | ||
A: | Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below
|
Java swing interview questions and answers
1) What is a swing?
Swing is a GUI toolkit for Java. It is one part of the Java Foundation Classes (JFC). Swing includes graphical user interface (GUI) widgets such as text boxes, buttons, split-panes, and tables.
Swing widgets provide more sophisticated GUI components than the earlier Abstract Window Toolkit. Since they are written in pure Java, they run the same on all platforms, unlike the AWT which is tied to the underlying platform’s windowing system. Swing supports pluggable look and feel – not by using the native platform’s facilities, but by roughly emulating them. This means you can get any supported look and feel on any platform. The disadvantage of lightweight components is slower execution. The advantage is uniform behavior on all platforms.
2) Why does JComponent have add() and remove() methods but Component does not?
Answer: because JComponent is a subclass of Container, and can contain other components and jcomponents.
3) How would you create a button with rounded edges?
Answer: there’s 2 ways. The first thing is to know that a JButton’s edges are drawn by a Border. so you can override the Button’s paintComponent(Graphics) method and draw a circle or rounded rectangle (whatever), and turn off the border. Or you can create a custom border that draws a circle or rounded rectangle around any component and set the button’s border to it.
4) If I wanted to use a SolarisUI for just a JTabbedPane, and the Metal UI for everything else, how would I do that?
Answer: in the UIDefaults table, override the entry for tabbed pane and put in the SolarisUI delegate. (I don’t know it offhand, but I think it’s “com.sun.ui.motiflookandfeel.MotifTabbedPaneUI” – anything simiar is a good answer.)
5) What is the difference between the ‘Font’ and ‘FontMetrics’ class?
Answer: The Font Class is used to render ‘glyphs’ – the characters you see on the screen. FontMetrics encapsulates information about a specific font on a specific Graphics object. (width of the characters, ascent, descent)
6) What class is at the top of the AWT event hierarchy?
Answer: java.awt.AWTEvent. if they say java.awt.Event, they haven’t dealt with swing or AWT in a while.
7) Explain how to render an HTML page using only Swing.
Answer: Use a JEditorPane or JTextPane and set it with an HTMLEditorKit, then load the text into the pane.
How would you detect a keypress in a JComboBox?
Answer: This is a trick. most people would say ‘add a KeyListener to the JComboBox’ – but the right answer is ‘add a KeyListener to the JComboBox’s editor component.’
9) Why should the implementation of any Swing callback (like a listener) execute quickly?
A: Because callbacks are invoked by the event dispatch thread which will be blocked processing other events for as long as your method takes to execute.
10) In what context should the value of Swing components be updated directly?
A: Swing components should be updated directly only in the context of callback methods invoked from the event dispatch thread. Any other context is not thread safe?
11) Why would you use SwingUtilities.invokeAndWait or SwingUtilities.invokeLater?
A: I want to update a Swing component but I’m not in a callback. If I want the update to happen immediately (perhaps for a progress bar component) then I’d use invokeAndWait. If I don’t care when the update occurs, I’d use invokeLater.
12) If your UI seems to freeze periodically, what might be a likely reason?
A: A callback implementation like ActionListener.actionPerformed or MouseListener.mouseClicked is taking a long time to execute thereby blocking the event dispatch thread from processing other UI events.
13) Which Swing methods are thread-safe?
A: The only thread-safe methods are repaint(), revalidate(), and invalidate()
14) Why won’t the JVM terminate when I close all the application windows?
A: The AWT event dispatcher thread is not a daemon thread. You must explicitly call System.exit to terminate the JVM.
15) Can a class be its own event handler? Explain how to implement this.
Answer: Sure. an example could be a class that extends Jbutton and implements ActionListener. In the actionPerformed method, put the code to perform when the button is pressed.
16)What is AWT?
AWT is heavy-weight components, but Swing is light-weight components. AWT is OS dependent because it uses native components, But Swing components are OS independent. We can change the look and feel in Swing which is not possible in AWT. Swing takes less memory compared to AWT. For drawing AWT uses screen rendering where Swing uses double buffering.
17) What are heavy weight components?
A heavyweight component is one that is associated with its own native screen resource (commonly known as a peer).
18) What is JFC?
JFC stands for Java Foundation Classes. The Java Foundation Classes (JFC) are a set of Java class libraries provided as part of Java 2 Platform, Standard Edition (J2SE) to support building graphics user interface (GUI) and graphics functionality for client applications that will run on popular platforms such as Microsoft Windows, Linux, and Mac OSX.
Swing is a GUI toolkit for Java. It is one part of the Java Foundation Classes (JFC). Swing includes graphical user interface (GUI) widgets such as text boxes, buttons, split-panes, and tables.
Swing widgets provide more sophisticated GUI components than the earlier Abstract Window Toolkit. Since they are written in pure Java, they run the same on all platforms, unlike the AWT which is tied to the underlying platform’s windowing system. Swing supports pluggable look and feel – not by using the native platform’s facilities, but by roughly emulating them. This means you can get any supported look and feel on any platform. The disadvantage of lightweight components is slower execution. The advantage is uniform behavior on all platforms.
2) Why does JComponent have add() and remove() methods but Component does not?
Answer: because JComponent is a subclass of Container, and can contain other components and jcomponents.
3) How would you create a button with rounded edges?
Answer: there’s 2 ways. The first thing is to know that a JButton’s edges are drawn by a Border. so you can override the Button’s paintComponent(Graphics) method and draw a circle or rounded rectangle (whatever), and turn off the border. Or you can create a custom border that draws a circle or rounded rectangle around any component and set the button’s border to it.
4) If I wanted to use a SolarisUI for just a JTabbedPane, and the Metal UI for everything else, how would I do that?
Answer: in the UIDefaults table, override the entry for tabbed pane and put in the SolarisUI delegate. (I don’t know it offhand, but I think it’s “com.sun.ui.motiflookandfeel.MotifTabbedPaneUI” – anything simiar is a good answer.)
5) What is the difference between the ‘Font’ and ‘FontMetrics’ class?
Answer: The Font Class is used to render ‘glyphs’ – the characters you see on the screen. FontMetrics encapsulates information about a specific font on a specific Graphics object. (width of the characters, ascent, descent)
6) What class is at the top of the AWT event hierarchy?
Answer: java.awt.AWTEvent. if they say java.awt.Event, they haven’t dealt with swing or AWT in a while.
7) Explain how to render an HTML page using only Swing.
Answer: Use a JEditorPane or JTextPane and set it with an HTMLEditorKit, then load the text into the pane.
How would you detect a keypress in a JComboBox?
Answer: This is a trick. most people would say ‘add a KeyListener to the JComboBox’ – but the right answer is ‘add a KeyListener to the JComboBox’s editor component.’
9) Why should the implementation of any Swing callback (like a listener) execute quickly?
A: Because callbacks are invoked by the event dispatch thread which will be blocked processing other events for as long as your method takes to execute.
10) In what context should the value of Swing components be updated directly?
A: Swing components should be updated directly only in the context of callback methods invoked from the event dispatch thread. Any other context is not thread safe?
11) Why would you use SwingUtilities.invokeAndWait or SwingUtilities.invokeLater?
A: I want to update a Swing component but I’m not in a callback. If I want the update to happen immediately (perhaps for a progress bar component) then I’d use invokeAndWait. If I don’t care when the update occurs, I’d use invokeLater.
12) If your UI seems to freeze periodically, what might be a likely reason?
A: A callback implementation like ActionListener.actionPerformed or MouseListener.mouseClicked is taking a long time to execute thereby blocking the event dispatch thread from processing other UI events.
13) Which Swing methods are thread-safe?
A: The only thread-safe methods are repaint(), revalidate(), and invalidate()
14) Why won’t the JVM terminate when I close all the application windows?
A: The AWT event dispatcher thread is not a daemon thread. You must explicitly call System.exit to terminate the JVM.
15) Can a class be its own event handler? Explain how to implement this.
Answer: Sure. an example could be a class that extends Jbutton and implements ActionListener. In the actionPerformed method, put the code to perform when the button is pressed.
16)What is AWT?
AWT is heavy-weight components, but Swing is light-weight components. AWT is OS dependent because it uses native components, But Swing components are OS independent. We can change the look and feel in Swing which is not possible in AWT. Swing takes less memory compared to AWT. For drawing AWT uses screen rendering where Swing uses double buffering.
17) What are heavy weight components?
A heavyweight component is one that is associated with its own native screen resource (commonly known as a peer).
18) What is JFC?
JFC stands for Java Foundation Classes. The Java Foundation Classes (JFC) are a set of Java class libraries provided as part of Java 2 Platform, Standard Edition (J2SE) to support building graphics user interface (GUI) and graphics functionality for client applications that will run on popular platforms such as Microsoft Windows, Linux, and Mac OSX.
Java technichal interview questions and answers for interview
- What is garbage collection? What is the process that is responsible for doing that in java? – Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process
- What kind of thread is the Garbage collector thread? – It is a daemon thread.
- What is a daemon thread? – These are the threads which can run without user intervention. The JVM can exit when there are daemon thread by killing them abruptly.
- How will you invoke any external process in Java? – Runtime.getRuntime().exec(….)
- What is the finalize method do? – Before the invalid objects get garbage collected, the JVM give the user a chance to clean up some resources before it got garbage collected.
- What is mutable object and immutable object? – If a object value is changeable then we can call it as Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the value of an object, it is immutable object. (Ex., String, Integer, Float, …)
- What is the basic difference between string and stringbuffer object? – String is an immutable object. StringBuffer is a mutable object.
- What is the purpose of Void class? – The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void.
- What is reflection? – Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions.
- What is the base class for Error and Exception? – Throwable
- What is the byte range? -128 to 127
- What is the implementation of destroy method in java.. is it native or java code? – This method is not implemented.
- What is a package? – To group set of classes into a single unit is known as packaging. Packages provides wide namespace ability.
- What are the approaches that you will follow for making a program very efficient? – By avoiding too much of static methods avoiding the excessive and unnecessary use of synchronized methods Selection of related classes based on the application (meaning synchronized classes for multiuser and non-synchronized classes for single user) Usage of appropriate design patterns Using cache methodologies for remote invocations Avoiding creation of variables within a loop and lot more.
- What is a DatabaseMetaData? – Comprehensive information about the database as a whole.
- What is Locale? – A Locale object represents a specific geographical, political, or cultural region
- How will you load a specific locale? – Using ResourceBundle.getBundle(…);
- What is JIT and its use? – Really, just a very fast compiler… In this incarnation, pretty much a one-pass compiler — no offline computations. So you can’t look at the whole method, rank the expressions according to which ones are re-used the most, and then generate code. In theory terms, it’s an on-line problem.
- Is JVM a compiler or an interpreter? – Interpreter
- When you think about optimization, what is the best way to findout the time/memory consuming process? – Using profiler
- What is the purpose of assert keyword used in JDK1.4.x? – In order to validate certain expressions. It effectively replaces the if block and automatically throws the AssertionError on failure. This keyword should be used for the critical arguments. Meaning, without that the method does nothing.
- How will you get the platform dependent values like line separator, path separator, etc., ? – Using Sytem.getProperty(…) (line.separator, path.separator, …)
- What is skeleton and stub? what is the purpose of those? – Stub is a client side representation of the server, which takes care of communicating with the remote server. Skeleton is the server side representation. But that is no more in use… it is deprecated long before in JDK.
- What is the final keyword denotes? – final keyword denotes that it is the final implementation for that method or variable or class. You can’t override that method/variable/class any more.
- What is the significance of ListIterator? – You can iterate back and forth.
- What is the major difference between LinkedList and ArrayList? – LinkedList are meant for sequential accessing. ArrayList are meant for random accessing.
- What is nested class? – If all the methods of a inner class is static then it is a nested class.
- What is inner class? – If the methods of the inner class can only be accessed via the instance of the inner class, then it is called inner class.
- What is composition? – Holding the reference of the other class within some other class is known as composition.
- What is aggregation? – It is a special type of composition. If you expose all the methods of a composite class and route the method call to the composite method through its reference, then it is called aggregation.
- What are the methods in Object? – clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString
- Can you instantiate the Math class? – You can’t instantiate the math class. All the methods in this class are static. And the constructor is not public.
- What is singleton? – It is one of the design pattern. This falls in the creational pattern of the design pattern. There will be only one instance for that entire JVM. You can achieve this by having the private constructor in the class. For eg., public class Singleton { private static final Singleton s = new Singleton(); private Singleton() { } public static Singleton getInstance() { return s; } // all non static methods … }
- What is DriverManager? – The basic service to manage set of JDBC drivers.
- What is Class.forName() does and how it is useful? – It loads the class into the ClassLoader. It returns the Class. Using that you can get the instance ( “class-instance”.newInstance() ).
- Inq adds a question: Expain the reason for each keyword ofpublic static void main(String args[])
core java interview questions and answers
1.How could Java classes direct program messages to the system console, but error messages, say to a file?
The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream(“output.txt”)); System.setErr(st); System.setOut(st);
2.How would you create a button with rounded edges?
There’s 2 ways. The first thing is to know that a JButton’s edges are drawn by a Border. so you can override the Button’s paintComponent(Graphics) method and draw a circle or rounded rectangle (whatever), and turn off the border. Or you can create a custom border that draws a circle or rounded rectangle around any component and set the button’s border to it.
3.Why should the implementation of any Swing callback (like a listener) execute quickly?
A: Because callbacks are invoked by the event dispatch thread which will be blocked processing other events for as long as your method takes to execute.
4. Question: How you can force the garbage collection?
Garbage collection automatic process and can’t be forced. You could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.
Garbage collection is one of the most important feature of Java, Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program can’t directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.
5. What’s the difference between constructors and normal methods?
Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times and it can return a value or can be void.
6. When should the method invokeLater()be used?
This method is used to ensure that Swing components are updated through the event-dispatching thread.
7.Explain the usage of Java packages.
This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.
8.What are some advantages and disadvantages of Java Sockets?
Some advantages of Java Sockets:
Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications. Sockets cause low network traffic. Unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request, Java applets can send only necessary updated information.
Some disadvantages of Java Sockets:
Security restrictions are sometimes overbearing because a Java applet running in a Web browser is only able to establish connections to the machine where it came from, and to nowhere else on the network Despite all of the useful and helpful Java features, Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.
9.What is Collection API?
The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
10.Explain the usage of the keyword transient?
Transient keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).
11.What’s the difference between the methods sleep() and wait()
The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.
12.Why would you use a synchronized block vs. synchronized method?
Synchronized blocks place locks for shorter periods than synchronized methods.
13.Can an inner class declared inside of a method access local variables of this method?
It’s possible if these variables are final.
14.Explain the user defined Exceptions?
User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions.
Example:
class myCustomException extends Exception {
/ The class simply has to exist to be an exception
}
15.Describe the wrapper classes in Java.
Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.
Following table lists the primitive types and the corresponding wrapper classes:
Primitive Wrapper
boolean – java.lang.Boolean
byte – java.lang.Byte
char – java.lang.Character
double – java.lang.Double
float – java.lang.Float
int – java.lang.Integer
long – java.lang.Long
short – java.lang.Short
void – java.lang.Void
16.Which of the following are valid definitions of an application’s main( ) method?
a) public static void main();
b) public static void main( String args );
c) public static void main( String args[] );
d) public static void main( Graphics g );
e) public static boolean main( String args[] );
The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream(“output.txt”)); System.setErr(st); System.setOut(st);
2.How would you create a button with rounded edges?
There’s 2 ways. The first thing is to know that a JButton’s edges are drawn by a Border. so you can override the Button’s paintComponent(Graphics) method and draw a circle or rounded rectangle (whatever), and turn off the border. Or you can create a custom border that draws a circle or rounded rectangle around any component and set the button’s border to it.
3.Why should the implementation of any Swing callback (like a listener) execute quickly?
A: Because callbacks are invoked by the event dispatch thread which will be blocked processing other events for as long as your method takes to execute.
4. Question: How you can force the garbage collection?
Garbage collection automatic process and can’t be forced. You could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.
Garbage collection is one of the most important feature of Java, Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program can’t directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.
5. What’s the difference between constructors and normal methods?
Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times and it can return a value or can be void.
6. When should the method invokeLater()be used?
This method is used to ensure that Swing components are updated through the event-dispatching thread.
7.Explain the usage of Java packages.
This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.
8.What are some advantages and disadvantages of Java Sockets?
Some advantages of Java Sockets:
Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications. Sockets cause low network traffic. Unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request, Java applets can send only necessary updated information.
Some disadvantages of Java Sockets:
Security restrictions are sometimes overbearing because a Java applet running in a Web browser is only able to establish connections to the machine where it came from, and to nowhere else on the network Despite all of the useful and helpful Java features, Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.
9.What is Collection API?
The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
10.Explain the usage of the keyword transient?
Transient keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).
11.What’s the difference between the methods sleep() and wait()
The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.
12.Why would you use a synchronized block vs. synchronized method?
Synchronized blocks place locks for shorter periods than synchronized methods.
13.Can an inner class declared inside of a method access local variables of this method?
It’s possible if these variables are final.
14.Explain the user defined Exceptions?
User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions.
Example:
class myCustomException extends Exception {
/ The class simply has to exist to be an exception
}
15.Describe the wrapper classes in Java.
Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.
Following table lists the primitive types and the corresponding wrapper classes:
Primitive Wrapper
boolean – java.lang.Boolean
byte – java.lang.Byte
char – java.lang.Character
double – java.lang.Double
float – java.lang.Float
int – java.lang.Integer
long – java.lang.Long
short – java.lang.Short
void – java.lang.Void
16.Which of the following are valid definitions of an application’s main( ) method?
a) public static void main();
b) public static void main( String args );
c) public static void main( String args[] );
d) public static void main( Graphics g );
e) public static boolean main( String args[] );
antartcia|news|sun|photo|collapses
Antarct
Antarctica news, all the latest and breaking Antarctic news ...
The Antarctic Sun: News about Antarctica - Home Page
ica News, Antarctic News, Alerts, Latest News, Breaking ...BBC News - Vast Antarctic iceberg 'threatens marine life'
Time Zone Changes in Antarctica
PHOTO IN THE NEWS: Giant Antarctic Ice Shelf Collapses
australis|news|topix|latest|online
News.com.au | News Online from Australia & the World | NewsComAu
Breaking news | Stories from Australia and the World | News.com.au
Australia News - Topix
Australia Weather | news.com.au
The Age - Business, World & Breaking News | Melbourne, Australia
The Australian | The Australian Homepage | TheAustralian
Australia News - Topix
Australia Weather | news.com.au
The Age - Business, World & Breaking News | Melbourne, Australia
The Australian | The Australian Homepage | TheAustralian
Gulf News
Khaleej Times Home - Dubai News, UAE News, Gulf, News, Abu Dhabi ...
Home
News for news of dubai
UAE News and information - United Arab Emirates
| 7DAYS
Dubai News » BuzzTracker News Headlines
BITS Dubai | News
BBC NEWS | Special Reports | Fiery spectacle opens Dubai hotel
The Dubai Life - The Latest Dubai News, Dubai Property News, Dubai ...
Daily News on GoDubai, Dubai, UAE Middle east News, Online News
BBC News - Dubai death Briton Lee Brown 'choked on vomit'
Subscribe to:
Posts (Atom)