How is an argument passed in Java methods?
In Java no matter if the variable is primitive datatype or an object when passed as an argument to a method, they are always passed by value.
This is a most common error that most of newcomers to language and even veterans do in understanding this concept.
Please go through to following link on java.sun.com website for a detailed discussion and understanding of this concept.
What is the difference between class variable, member variable and automatic(local) variable?
The class variable is a static variable and it does not belong to any instance of class but shared across all the instances.
The member variable belongs to a particular instance of class and can be called from any method of the class.
The automatic or local variable is created on a method entry and valid within method scope and they have to be initialized explicitly.
When are static and non static variables of a class initialized?
The static variables are initialized at class load time during compilation and non static variables are initialized just before the constructor is called.
Can shift operators be applied to float types?
No, shift operators are applicable only on integer or long types.
What are different Java declarations and their associated rules?
All variables in Java are introduced/declared with some basic datatypes with some basic values, e.g. every decimal value by default is a double.The names of variables must avoid reserved Java keywords.The local variables are explicitly initialized.
What are Java Modifiers?
Java classes, interfaces, and their members can be declared with one or more modifiers.They can be categorised as:
Class Modifiers :
ClassModifier: one of
public private(for inner classes) protected(for inner classes)
abstract static final strictfp
Any top level class can either be public or package private(no explicit modifier)
Field Modifiers
FieldModifier: one of
public protected private
static final transient volatile
Method Modifiers
MethodModifier: one of
public protected private abstract static
final synchronized native strictfp
Constructor Modifiers
ConstructorModifier: one of
public protected private
The following matrix of the all modifiers in Java shows which modifier maps to which element:-
Explain final modifier.
'final' modifier can be applied to classes, methods and variables and the features cannot be changed. final class cannot be subclassed, methods cannot be overridden
Can you change the reference of the final object?
No the reference cannot be changed, but the data in that object can be changed.
Can abstract class be instantiated?
No,an abstract class cannot be instantiated i.e you cannot create a new object of this class. When does the compiler insist that the class must be abstract?
In following conditions,compiler insists 'abstract' keyword with a class :
• If one or more methods of the class are abstract.
• If class inherits one or more abstract methods from the parent abstract class and no implementation is provided for that method
• If class implements an interface and provides no implementation for those methods
Where can static modifiers be used?
They can be applied to variables, methods and even a block of code, static methods and variables are not associated with any instance of class.They are loaded at the class compile time.
What is static initializer code?
A class can have a block of initializer code that is simply surrounded by curly braces and labeled as static e.g.
public class Demo{
static int =10;
static{
System.out.println("Hello world');
}
}
And this code is executed exactly once at the time of class load.
Can an anonymous class implement an interface and extend a class at the same time?
No,an anonymous class can either implement an interface or extend a class at a particular time but not both at the same time.
What are volatile variables?
A volatile variable is modified asynchronously by concurrently running threads in a Java application.It is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Of course, it is likely that volatile variables have a higher access and update overhead than "plain" variables, since the reason threads can have their own copy of data is for better efficiency.
Can protected or friendly features be accessed from different packages?
No,when features are friendly or protected they can be accessed from all the classes in that package but not from classes in another package.
How many ways can one write an infinite loop ?
Personally I would recommend following ways to implement infinite loop in Java but their can be other ways like calling a method recursively , though I never tested that.
- while (true)
- for (;;) { }
When do you use 'continue' and 'break' statements?
When one wants to complete the iteration of a loop prematurely then 'continue' statement is used.
While the 'break' statement is used to exit the entire loop whenever encountered.
What is the difference between 'while' and 'do while' loop?
In case of 'do-while' loop, body is always executed at least once,since test is performed at the end of the body.It should usually be ignored while coding.
What is an Assertion and why using assertion in your program is a good idea ?
In a Java program,several times, one would like to make certain assumptions for executing a program.For example,while taking a square root of a numeric value it has to be assumed that this value should not be negative.An assertion is a statement in the Java programming language that enables to test assumptions about one's program.Assertions are supported from J2SE1.4 and later.A simple exmaple of assertion can be checking of an employee object from being null:
Employee employee = null;
Explain Assertions with a code example
The main reason of introducing assertions in Java from R1.4 onwards is to reduce the chances of bugs which otherwise would have gone unnoticed, in one's code.In fact, finding and removing bugs is one tedious and not so exciting task.Assertions should be used for scenarios which ideally should never happen in the lifecycle of a program,check assumptions about data structures (such as ensuring that an array is of the correct length), or enforcing constraints on arguments of private methods.Assertions help in a way to block these bugs at the beginning of writing actual logic inside your code that saves lot of efforts,time and most significantly, costs.A simple assertion facility provides a limited form of design-by-contract programming.In design-by-contract programming identification of preconditions and post conditions to a program are must before even starting the coding itself.
Here is simple Java code which uses assertions, here the task is to determine the gender of a person.We have used a switch-case statement to define the over all flow of the logic :
How many forms of assertions we have?
There are two forms of assertions:
The first, simpler form is:
assert Expression1 ;
where Expression1 is a boolean expression.
When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no detail message.
While the second form of the assertion statement is:
assert Expression1 : Expression2 ;
where:
Expression1 is a boolean expression.
Expression2 is an expression that has a value. (It cannot be an invocation of a method that is declared void.)
This form is used when the assert statement has to provide a detail message for the AssertionError.The system passes the value of Expression2 to the appropriate AssertionError constructor, and this constructor uses the string representation of the value as the error's detail message. This detail message helps in analysing and diagnosing the assertion failure which ultimately helps in resolving the error.
When assertions should be avoided?
In following situations the assertions should be avoided:
-When assertion becomes a performance issue.It means an assertion should not include too complex logic equalling implementation of a method.
-Do not use assertions in argument checking of public methods.As argument checking is part of a method implementation and if these arguments are erroneous then it will throw runtime exception and assertion failure will not result in any error.
What situations are best suitable for implementing assertions?
Assertions can best be implemented :
- As Internal Invariants
- As Control flow Invariants
- As Preconditions and Postconditions
- As Class Invariants
What is Exception ?
An exception is an abnormal behavior existing during a normal execution of a program. For example: When writing to a file if there does not exist required file then an appropriate exception will be thrown by java code.
What is a user-defined exception?
For every project you implement you need to have a project dependent exception class so that objects of this type can be thrown so in order to cater this kind of requirement the need for user defined exception class is realized.
for example:
class MyException extends Exception{
public MyException(){};
public MyException(String msg){
super(msg);
}
What do you know about the garbage collector?
In Java, memory management is done automatically by JVM.A programmer is free of this responsibility of handling memory. A garbage collector is a part of JVM responsible for removing objects from heap, which is no longer in use. The garbage collector typically runs in a background thread, periodically scanning the heap, identifying garbage objects, and releasing the memory they occupy so that the memory is available for future objects.
Why Java does not support pointers?
As per the design decision Java does not support pointers explicitly.This greatly reduces the burden of dynamic memory management while coding from programmers.Though programmers dynamically allocate memory while coding but they need not worry about deallocating this memory.The automatic garbage collection feature of Java collects dangling references of objects though it has a trade off on performance as programmer managed memory management will be efficient as compared to JVM driven automatic garbage collection.
Does garbage collection guarantee that a program will not run out of memory?
Garbage collection does not guarantee that a program will not run out of memory. As garbage collection is JVM dependent then It is possible for programs to use memory resources faster than they are garbage collected.Moreover garbage collection cannot be enforced,it is just suggested.Java guarantees that the finalize method will be run before an object is Garbage collected,it is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
The garbage collection is uncontrolled, it means you cannot predict when it will happen, you thus cannot predict exactly when the finalize method will run. Once a variable is no longer referenced by anything it is available for garbage collection.You can suggest garbage collection with System.gc(), but this does not guarantee when it will happen.
What is finally in Exception handling?
'finally' is a part of try-catch-throw and finally blocks for exception handling mechanism in Java.'finally' block contains snippet which is always executed irrespective of exception occurrence. The runtime system always executes the statements within the finally block regardless of what happens within the try block. The cleanup code is generally written in this part of snippet e.g. dangling references are collected here.
What can prevent the execution of the code in finally block?
Use of System.exit()
-The death of thread
-Turning off the power to CPU
-An exception arising in the finally block itself
Explain 'try','catch' and 'finally' blocks?
In Java exceptions are handled in try, catch, throw and finally blocks. It says try a block of Java code for a set of exception/s catch an exception if it appears in a catch block of code separate from normal execution of code. It clearly segregates errors from a block of code in an effective and efficient manner. The exceptions, which are caught, thrown using throw keyword. A finally block is called in order to execute clean up activities for any mess caused during abnormal execution of program.
Define Checked and Unchecked exception.
A checked exception is one, which a block of code is likely to throw, and represented by throws clause.It represents invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files).
In Java it is expected that a method 'throws' an exception which is a checked exception.They are subclasses of Exception.
While unchecked exceptions represent defects in the program (often invalid arguments passed to a non-private method).
According to definition in The Java Programming Language, by Gosling, Arnold, and Holmes,"Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time." They are subclasses of RuntimeException, and are usually implemented using IllegalArgumentException, NullPointerException, or IllegalStateException
It is somewhat confusing, but note as well that RuntimeException (unchecked) is itself a subclass of Exception (checked).
What is the difference between an abstract class and an interface?
An abstract class allows its subclasses to override the methods defined in it. It is never instantiated and a class can inherit from a single class, as Java doesn't support for Multiple Inheritance. It may contain both abstract and non-abstract methods.
An interface has public, abstract methods and may have public, static and final variables (read only). It introduces multiple inheritance by a class implementing several interfaces.
What is the use of interface?
An interface is a collection of public abstract methods and read only i.e. public, static and final variables.
The concept of interfaces in Java makes Multiple Inheritance a reality. Two or more non-related classes can implement the same interface. A class can implement multiple interfaces.Whenever there has to be an ancestry associated with classes along with some concrete behaviors then it is good idea to come up with abstract classes in such scenario but when implementation is more generic in nature and not dependent upon class relations or type hierarchy then such behaviors should be packaged inside an interface.The methods defined inside an interface can be implemented by non related classes.
What is serializable interface?
In java.io package there is an interface called java.io.Serializable, which is a syntactic way of serializing objects. This interface does not define any method. The purpose of serialization is persistence, communication over sockets or RMI. In Object serialization an object can be converted into byte stream and vice versa.
Does a class inherit constructors from its superclass?
The answer is No.Constructors cannot be inherited.Constructors are used to initialize a valid sate of an object.Whenever a subclass instance is created then it calls no argument default constructor of super class.
The following code will explain implicit call to default constructor of base class:-
class Base {
Base() {
System.out.println("I am constructing Base");
}
}
class Child extends Base {
Child() {
System.out.println("I am constructing Child");
}
}
public class A {
public static void main(String[] args) {
Child child = new Child();
}
}
Once executed this code will print:
I am constructing Base
I am constructing Child
It means when a child class object is created it inherently calls no arg default constructor of base class.
What's the difference between constructors and other 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.
If the method to be overridden has access type 'protected', can subclass have the access type as 'private'?
No, it must have access type as protected or public, since an overriding method must restrict access of the method it overrides.
If you use super() or this() in a constructor where should it appear in the constructor?
It should always be the first statement in the constructor.
What modifiers may be used with an inner class that is a member of an outer class?
A (non-local) inner class may be declared as public, protected,
private, static, final, or abstract.
Can an inner class be defined inside a method?
Yes it can be defined inside a method and it can access data of the
enclosing methods or a formal parameter if it is final.
What is an anonymous class?
It is a type of inner class with no name.Once defined an object can be
created of that type as a parameter all in one line. it cannot have
explicitly declared constructor.The compiler automatically provides an
anonymous constructor for such class.
An anonymous class is never abstract. An anonymous class is always an
inner class; it is never static. An anonymous class is always
implicitly final.
What is a thread?
A thread is most fundamental unit of a computer program which is under execution independent of other parts.A thread and a task are similar and often confused.An operating system executes a program by allocating it certain resources like memory,CPU cycles and when there are many a programs doing several things corresponding to several users requests.In such a scenario each program is viewed as a 'task' by OS for which it identifies an allocate resources. An OS treats each application e.g. Word Processor,spreadsheet,email client etc as a separate task , if a certain program initiates some parallel activity e.g. doing some IO operations,printing then a 'thread' will be created fro doing this job.
What is the difference between process and threads?
A thread is part of a process; a process may contain several different threads. Two threads of the same process share a good deal of state and are not protected against one another, whereas two different processes share no state and are protected against one another. Two threads of the same process have different values of the program counter; different stacks (local variables); and different registers.The program counter, stack pointer, and registers are therefore saved in the thread table. Two threads share open files and memory allocation; therefore, file information and memory information (e.g. base/limit register or page table) is stored in the process table.
What are two types of multitasking?
Co-operative
In case of co-operative multitasking applications consume resources i.e. memory and CPU cycle and once it is completed with its execution of set of instructions, it returns control back to the OS. The scheme depends on the application co-operating and so is known as co-operative multitasking. In cases where the application entered an endless loop and never reached the code which handed control back to the operating system, the whole machine became locked up. An example is Windows 3.1
Pre -emptive
In this technique the operating system allocates resources to an application. This will enable it to execute. Rather than wait for the application to give the resources up, the operating system is
activated at certain time intervals and may take the resources back from the executing application and allocate them to another application that is waiting.Example: Unix, Windows NT, and 32 bit programs running under Windows '95
Labels
.NET Job Questions
About Java
Absract class
Abstract class
Abstract Class and Interface
Aggregation
ajax
aop
apache ofbiz
Apache ofbiz tutrial
Association
authentication
autocad
basics
batch
Binary Tree
bootstrap loader in java
build
Builder design pattern
C++ Job Questions
caching
CallableStatement in java
certifications
Chain of responsibility Design pattern
charts
check parentheses in a string
Classes
classloader in java
classloading concept
code quality
collage level java program
Composition
concurrency
Concurrency Tutorial
Converting InputStream to String
Core Java
core java concept
core java interview questions
Core Java Interview Questions
Core Java Questions
core java tutorial
CyclicBarrier in Java
data structures
database
Database Job Questions
datetime in c#
DB
Db2 SQL Replication
deserialization in java
Design Patterns
designpatterns
Downloads
dtd
Eclipse
ejb
example/sample code
exception handling in core java
file handling injava
File I/O vs Memory-Mapped
Filter
first program in spring
flex
Garbage Collection
Generics concept in java
grails
groovy and grails
Guice
Heap
hibernate
Hibernate Interview Questions
how-to
IBM DB2
IBM DB2 Tutorial
ide
immutable
Interceptor
Interface
interview
Interview Questions for Advanced JAVA
investment bank
j2ee
java
JAVA Code Examples
Java 7
java changes
java class loading
JAVA Classes and Objects
Java Classloader concept
Java classloading concept
java cloning concept
java collection
Java collection interview questions
Java Collections
java concurrency
Java CountDownLatch
java definiton
Java design pattern
Java EE 5
Java EE 6
Java Exceptions
Java file
Java Garbage Collection
Java generics
Java Glossary
java hot concept
java immutable concept
Java Interface
Java interview Question
java interview question 2012
java interview question answer
Java Interview Questions
Java Interview Questions and Answers
java interview topic
java investment bank
Java Job Questions
java multithreading
java multithreading concept
java new features
Java Packages
java proxy object
java questions
Java Serialization
Java serialization concept
java serialization interview question
java session concept
java string
Java Swings Questions
java synchronization
java threading
Java Threads Questions
java tutorial
java util; java collections; java questions
java volatile
java volatile interview question
Java Wrapper Classes
java.java1.5
java.lang.ClassCastException
JavaNotes
javascript
JAX-WS
jdbc
JDBC
JDBC Database connection
jdk 1.5 features
JDK 1.5 new features Concurrent HashMap
JMS interview question
JMS tutorial
job
JSESSIONID concept
JSESSIONID interview Question
JSF
jsp
JSP Interview Question
JSP taglib
JSTL with JSP
Junit
Junit Concept
Junit interview question.Best Practices to write JUnit test cases in Java
JVM
Linux - Unix tutorial
Marker Interfaces
MD5 encryption and decryption
messaging
MNC software java interview question
musix
NCR java interview question
Networking Job Questions
news
Object Serialization
Objects
ojdbc14.jar
OOP
Oracle
Oracle SQL Query for two timestamp difference
orm
own JavaScript function call in Apache ofbiz
Packages
Palm Apps
patterns
pdf
persistence
Portal
Portlet Spring Integration
Prime number test in java
programs
Rails
Reboot remote computers
REST
Ruby
Sample application
schema
SCJP
security
Senior java developer interviews
servlet3
servlets
session tracking
singleton design pattern
Spring
Spring 2.5 Framework
spring ebook
Spring framework concept
spring MVC
spring pdf
Spring Security
Spring Security interview questions
SQL
SQL performance
SQL Query to create xml file
Sql Query tuning
ssis and ssrs
StAX and XML
string concept
string immutable
string in java
strings
struts
Struts2
Struts2 integration
synchronization works in java
Technical Interview
testing
tips
Tomcat
top
Tutorial
Volatile in deep
Volatile working concept
web
Web Developer Job Questions
web services
weblogic
Weblogic Application Server
websphere
what is JSESSIONID
xml
XML parsing in java
XML with Java
xslt
No comments:
Post a Comment