Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Monday, April 14, 2008

JAVA QUESTIONS 125

JAVA QUESTIONS

What is the difference between an Abstract class and Interface?
What is user defined exception?
What do you know about the garbage collector?
What is the difference between java and c++?
In an HTML form I have a button which makes us to open another page in 15 seconds. How will you do that?
What is the difference between process and threads?
What is update method called?
Have you ever used HashTable and Directory?
What are statements in Java?
What is a JAR file?
What is JNI?
What is the base class for all swing components?
What is JFC?
What is the difference between AWT and Swing?
Considering notepad/IE or any other thing as process, What will happen if you start notepad or IE 3 times ? Where three processes are started or three threads are started?
How does thread synchronization occur in a monitor?
Is there any tag in HTML to upload and download files?
Why do you canvas?
How can you know about drivers and database information ?
What is serialization?
Can you load the server object dynamically? If so what are the 3 major steps involved in it?
What is the layout for toolbar?
What is the difference between Grid and Gridbaglayout?
How will you add panel to a frame?
Where are the card layouts used?
What is the corresponding layout for card in swing?
What is light weight component?
Can you run the product development on all operating systems?
What are the benefits if Swing over AWT?
How can two threads be made to communicate with each other?
What are the files generated after using IDL to java compiler?
What is the protocol used by server and client?
What is the functionability stubs and skeletons?
What is the mapping mechanism used by java to identify IDL language?
What is serializable interface?
What is the use of interface?
Why is java not fully objective oriented?
Why does java not support multiple inheritance?
What is the root class for all java classes?
What is polymorphism?
Suppose if we have a variable 'I' in run method, if I can create one or more thread each thread will occupy a separate copy or same variable will be shared?
What are virtual functions?
Write down how will you create a Binary tree?
What are the traverses in binary tree?
Write a program for recursive traverse?
What are session variable in servlets?
What is client server computing?
What is constructor and virtual function? Can we call a virtual function in a constructor?
Why do we use oops concepts? What is its advantage?
What is middleware? What is the functionality of web server?
Why is java not 100% pure oops?
When will you use an interface and abstract class?
What is the exact difference in between Unicast and Multicast object? Where will it be used?
What is the main functionality of the remote reference layer?
How do you download stubs from Remote place?
I want to store more than 10 objects in a remote server? Which methodology will follow?
What is the main functionality of Prepared Statement?
What is meant by Static query and Dynamic query?
What are Normalization Rules? Define Normalization?
What is meant by Servelet? What are the parameters of service method?
What is meant by Session? Explain something about HTTP Session Class?
In a container there are 5 components. I want to display all the component names, how will you do that?
Why there are some null interface in JAVA? What does it mean? Give some null interface in JAVA?
Tell some latest versions in JAVA related areas?
What is meant by class loader? How many types are there? When will we use them?
What is meant by flickering?
What is meant by distributed application? Why are we using that in our application?
What is the functionality of the stub?
Explain about version control?
Explain 2-tier and 3-tier architecture?
What is the role of Web Server?
How can we do validation of the fields in a project?
What is meant by cookies? Explain the main features?
Why java is considered as platform independent?
What are the advantages of java over C++?
How java can be connected to a database?
What is thread?
What is difference between Process and Thread?
Does java support multiple inheritance? if not, what is the solution?
What are abstract classes?
What is an interface?
What is the difference abstract class and interface?
What are adapter classes?
what is meant wrapper classes?
What are JVM.JRE, J2EE, JNI?
What are swing components?
What do you mean by light weight and heavy weight components?
What is meant by function overloading and function overriding?
Does java support function overloading, pointers, structures, unions or linked lists?
What do you mean by multithreading?
What are byte codes?
What are streams?
What is user defined exception?
In an HTML page form I have one button which makes us to open a new page in 15 seconds. How will you do that?

JAVA INTERVIEW QUESTIONS 120

Basic concepts
 What is it object serialization ?
Serialization is a way to convert objects (including complex data structures such as lists and trees) into a stream of bytes.
 What is it reflection (introspection) ? Why is reflection possible in the Java language?
Reflection (introspection) is querying a class about its properties, and operating on methods and fields by the name for a given object instance. Reflection is possible in the Java language because of late binding.
 How do I synchronize a block of code without declaring the entire method synchronized?
One should use something like synchronized(this){...}
 Can you synchronize a block of code within a static method?
Of course. You should write something like that:
class C
{
static char[] x = new int[5];
static void setX(int i, char value)
{
synchronized(x)
{
x[i] = value;
}
}
}
 What are the four member access level for Java?
public,private,protected,package.
User interface
 What is the purpose of the toolkit in the Abstract Window Toolkit (AWT)? How does AWT work ?
The AWT toolkit is an interface between the abstract window layer and a specific windowing implementation.
 What is layout manager ? How does it work ?
A layout manager is an object that positions and resizes the components in a Container according to some algorithm; for example, the FlowLayout layout manager lays out components from left to right until it runs out of room and then continues laying out components below that row.
 Advantages and disadvantages of layout manager?
The biggest advantage is the standard way of implementing the user interface for cross-platform application. Disadvantages are:
- Challenge to create a custom layout if the standard one does not fit in your model
- Inability to use native UI features of concrete operating system that might be quite useful especially for complex UI tasks (however, this is against the Java philosophy and quite understandable drawback)
 Compare SWING components to standard AWT.
Swing is an extension of, and not a replacement for the AWT. There is some overlap between AWT and Swing (for example a Swing JButton component might be viewed as an improved functional replacement for an AWT Button component.) One of the advantages of Swing components is that because the components are not rendered on the screen by the operating system, the look and feel of a component does not change as the application or applet is executed on different platforms running under different operating systems. Furthermore, it is possible to cause Swing components to mimic the look and feel of a specific platform no matter what platform the program is running on. This is known as pluggable look and feel. Swing components support the JDK 1.1 Delegation Event Model. From an event handling viewpoint, Swing components operate the same as AWT components (except that Swing provides a number of new event types). Many Swing components don't have an AWT counterpart. A number of new and exciting components are included in the Swing library that don't exist in the AWT (tooltips, progress bars, trees, etc.)
Java Beans
 What is Java Beans ?
According to JavaSoft, "A Java Bean is a reusable software component that can be manipulated visually in a builder tool."
Networking
 What you know about Corba implementation in Java?
Java 1.2 promises full CORBA IDL support.
 What do you know about networking support in Java?
Java supports "low-level" and "high-level" classes. "Low-level" classes provide support for socket programming: Socket, DatagramSocket, and ServerSocket classes. "High-level" classes provide "Web programming": URL, URLEncoder, and URLConnection classes. Networking programming classes ease the programming of network applications, but do not substitute your knowledge of networking. Java networking like anything else in Java is platform-independent.
Threads
 How to make application thread-safe ?
You should use the word synchronized to mark the critical section of code. You may also use other methods of thread synchronization (see wait(), notify(), notifyAll() etc.
Deployment
 Why are Java ARchive (JAR) files important?
JAR files bundle .class files and optimize applet downloads.

Core Java Test Paper1 116

Which of the following will output -4.0
1) System.out.println(Math.floor(-4.7));
2) System.out.println(Math.round(-4.7));
3) System.out.println(Math.ceil(-4.7));
4) System.out.println(Math.min(-4.7));
Question 25)
What will happen if you attempt to compile and run the
following code?
Integer ten=new Integer(10);
Long nine=new Long (9);
System.out.println(ten + nine);
int i=1;
System.out.println(i + ten);
1) 19 followed by 20
2) 19 followed by 11
3) Error: Can't convert java lang Integer
4) 10 followed by 1
Question 33)
What will happen when you attempt to compile and run the
following code?.
1) It will compile and the run method will print out the
increasing value of i.
2) It will compile and calling start will print out the
increasing value of i.
3) The code will cause an error at compile time.
4) Compilation will cause an error because while cannot take a
parameter of true.
class Background implements Runnable{
int i=0;
public int run(){
while(true){
i++;
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
System.out.println("i="+i);
} //End while
return 1;
}//End run
}//End class
Question 38)
How can you change the current working directory using an
instance of the File class called FileName?
1) FileName.chdir("DirName")
2) FileName.cd("DirName")
3) FileName.cwd("DirName")
4) The File class does not support directly changing the
current directory.
Question 46)
You need to create a class that will store a unique object
elements. You do not need to sort these elements but they must
be unique.
What interface might be most suitable to meet this need?
1)Set
2)List
3)Map
4)Vector
Question 47)
Which of the following will successfully create an instance of
the Vector class and add an element?
1) Vector v=new Vector(99);
v[1]=99;
2) Vector v=new Vector();
v.addElement(99);
3) Vector v=new Vector();
v.add(99);
4 Vector v=new Vector(100);
v.addElement("99");
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
Question 49)
What will be the result when you attempt to compile this
program?
public class Rand{
public static void main(String argv[]){
int iRand;
iRand = Math.random();
System.out.println(iRand);
}
}
1) Compile time error referring to a cast problem
2) A random number between 1 and 10
3) A random number between 0 and 1
4) A compile time error about random being an unrecognised
method
Question 50)
Given the following code
import java.io.*;
public class Th{
public static void main(String argv[]){
Th t = new Th();
t.amethod();
}
public void amethod(){
try{
ioCall();
}catch(IOException ioe){}
}
}
What code would be most likely for the body of the ioCall
method
1) public void ioCall ()throws IOException{
DataInputStream din = new DataInputStream(System.in);
din.readChar();
}
2) public void ioCall ()throw IOException{
DataInputStream din = new DataInputStream(System.in);
din.readChar();
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
}
3) public void ioCall (){
DataInputStream din = new DataInputStream(System.in);
din.readChar();
}
4) public void ioCall throws IOException(){
DataInputStream din = new DataInputStream(System.in);
din.readChar();
}
Question 53)
Which of the following can you perform using the File class?
1) Change the current directory
2) Return the name of the parent directory
3) Delete a file
4) Find if a file contains text or binary information
Question 55)
You are concerned that your program may attempt to use more
memory than is available. To avoid this situation you want to
ensure that the Java Virtual Machine will run its garbage
collection just before you start a complex routine. What can
you do to be certain that garbage collection will run when you
want .
1) You cannot be certain when garbage collection will run
2) Use the Runtime.gc() method to force garbage collection
3) Ensure that all the variables you require to be garbage
collected are set to null
4) Use the System.gc() method to force garbage collection
jd2
8) What will happen when you attempt to compile and run this
code?
private class Base{}
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
public class Vis{
transient int iVal;
public static void main(String elephant[]){
}
}
1)Compile time error: Base cannot be private
2)Compile time error indicating that an integer cannot be
transient
3)Compile time error transient not a data type
4)Compile time error malformed main method
9) What happens when you attempt to compile and run these two
files in the same directory?
//File P1.java
package MyPackage;
class P1{
void afancymethod(){
System.out.println("What a fancy method");
}
}
//File P2.java
public class P2 extends P1{
afancymethod();
}
1) Both compile and P2 outputs "What a fancy method" when run
2) Neither will compile
3) Both compile but P2 has an error at run time
4) P1 compiles cleanly but P2 has an error at compile time
Question 18)
What will happen when you attempt to compile and run the
following code?
public class Bground extends Thread{
public static void main(String argv[]){
Bground b = new Bground();
b.run();
}
public void start(){
for (int i = 0; i <10; i++){
System.out.println("Value of i = " +
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
i);
}
}
}
Question 20)
Which most closely matches a description of a Java Map?
1) A vector of arrays for a 2D geographic representation
2) A class for containing unique array elements
3) A class for containing unique vector elements
4) An interface that ensures that implementing classes cannot
contain duplicate keys
Question 21)
How does the set collection deal with duplicate elements?
1) An exception is thrown if you attempt to add an element
with a duplicate value
2) The add method returns false if you attempt to add an
element with a duplicate value
3) A set may contain elements that return duplicate values
from a call to the equals method
4) Duplicate values will cause an error at compile time
Question 22)
What can cause a thread to stop executing?
1) The program exits via a call to System.exit(0);
2) Another thread is given a higher priority
3) A call to the thread's stop method.
4) A call to the halt method of the Thread class
Question 23)
For a class defined inside a method, what rule governs access
to the variables of the enclosing method?
1) The class can access any variable
2) The class can only access static variables
3) The class can only access transient variables
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
4) The class can only access final variables
Question 24)
Under what circumstances might you use the yield method of the
Thread class
1) To call from the currently running thread to allow another
thread of the same priority to run
2) To call on a waiting thread to allow it to run
3) To allow a thread of higher priority to run
4) To call from the currently running thread with a parameter
designating which thread should be allowed to run
Question 25)
What will happen when you attempt to compile and run the
following code
public class Hope{
public static void main(String argv[]){
Hope h = new Hope();
}
protected Hope(){
for(int i =0; i <10; i ++){
System.out.println(i);
}
}
}
1) Compilation error: Constructors cannot be declared
protected
2) Run time error: Constructors cannot be declared protected
3) Compilation and running with output 0 to 10
4) Compilation and running with output 0 to 9
Question 26)
What will happen when you attempt to compile and run the
following code
public class MySwitch{
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
public static void main(String argv[]){
MySwitch ms= new MySwitch();
ms.amethod();
}
public void amethod(){
int k=10;
switch(k){
default: //Put the default at the bottom, not here
System.out.println("This is the default output");
break;
case 10:
System.out.println("ten");
case 20:
System.out.println("twenty");
break;
}
}
}
1) None of these options
2) Compile time errror target of switch must be an integral
type
3) Compile and run with output "This is the default output"
4) Compile and run with output "ten"
Question 27)
Which of the following is the correct syntax for suggesting
that the JVM performs garbage collection
1) System.free();
2) System.setGarbageCollection();
3) System.out.gc();
4) System.gc();
Question 28)
What will happen when you attempt to compile and run the
following code
public class As{
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
int i = 10;
int j;
char z= 1;
boolean b;
public static void main(String argv[]){
As a = new As();
a.amethod();
}
public void amethod(){
System.out.println(j);
System.out.println(b);
}
}
1) Compilation succeeds and at run time an output of 0 and
false
2) Compilation succeeds and at run time an output of 0 and
true
3) Compile time error b is not initialised
4) Compile time error z must be assigned a char value
Question 29)
What will happen when you attempt to compile and run the
following code with the command line "hello there"
public class Arg{
String[] MyArg;
public static void main(String argv[]){
MyArg=argv;
}
public void amethod(){
System.out.println(argv[1]);
}
}
1) Compile time error
2) Compilation and output of "hello"
3) Compilation and output of "there"
4) None of the above
Question 30)
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
What will happen when you attempt to compile and run the
following code
public class StrEq{
public static void main(String argv[]){
StrEq s = new StrEq();
}
private StrEq(){
String s = "Marcus";
String s2 = new String("Marcus");
if(s == s2){
System.out.println("we have a match");
}else{
System.out.println("Not equal");
}
}
}
1) Compile time error caused by private constructor
2) Output of "we have a match"
3) Output of "Not equal"
4) Compile time error by attempting to compare strings using
==
Question 31)
1) What will happen when you attempt to compile and run the
following code
import java.io.*;
class Base{
public static void amethod()throws FileNotFoundException{}
}
public class ExcepDemo extends Base{
public static void main(String argv[]){
ExcepDemo e = new ExcepDemo();
}
public static void amethod(){}
protected ExcepDemo(){
try{
DataInputStream din = new DataInputStream(System.in);
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
System.out.println("Pausing");
din.readChar();
System.out.println("Continuing");
this.amethod();
}catch(IOException ioe) {}
}
}
1)Compile time error caused by protected constructor
2) Compile time error caused by amethod not declaring
Exception
3) Runtime error caused by amethod not declaring Exception
4) Compile and run with output of "Pausing" and "Continuing"
after a key is hit
Question 32)
What will happen when you attempt to compile and run this
program
public class Outer{
public String name = "Outer";
public static void main(String argv[]){
Inner i = new Inner();
i.showName();
}//End of main
private class Inner{
String name =new String("Inner");
void showName(){
System.out.println(name);
}
}//End of Inner class
}
1) Compile and run with output of "Outer"
2) Compile and run with output of "Inner"
3) Compile time error because Inner is declared as private
4) Compile time error because of the line creating the
instance of Inner
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
Question 34)
Which option most fully describes will happen when you attempt
to compile and run the following code
public class MyAr{
public static void main(String argv[]) {
MyAr m = new MyAr();
m.amethod();
}
public void amethod(){
static int i;
System.out.println(i);
}
}
1) Compilation and output of the value 0
2) Compile time error because i has not been initialized
3) Compilation and output of null
4) Compile time error
Question 35)
Which of the following will compile correctly
1) short myshort = 99S;
2) String name = 'Excellent tutorial Mr Green';
3) char c = 17c;
4)int z = 015;
Question 36)
Which of the following are Java key words
1)double
2)Switch
3)then
4)instanceof
Question 37
What will be output by the following line?
System.out.println(Math.floor(-2.1));
1) -2
2) 2.0
3) -3
4) -3.0
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
Question 38)
Given the following main method in a class called Cycle and a
command line of
java Cycle one two
what will be output?
public static void main(String bicycle[]){
System.out.println(bicycle[0]);
}
1) None of these options
2) cycle
3) one
4) two
Question 39)
Which of the following statements are true?
1) At the root of the collection hierarchy is a class called
Collection
2) The collection interface contains a method called
enumerator
3) The interator method returns an instance of the Vector
class
4) The set interface is designed for unique elements
Question 41)
Given the following code
class Base{}
public class MyCast extends Base{
static boolean b1=false;
static int i = -1;
static double d = 10.1;
public static void main(String argv[]){
MyCast m = new MyCast();
Base b = new Base();
//Here
}
}
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
Which of the following, if inserted at the comment //Here will
allow the code to compile and run without error
1) b=m;
2) m=b;
3) d =i;
4) b1 =i;
Question 42)
Which of the following statements about threading are true
1) You can only obtain a mutually exclusive lock on methods in
a class that extends Thread or implements runnable
2) You can obtain a mutually exclusive lock on any object
3) A thread can obtain a mutually exclusive lock on a method
declared with the keyword synchronized
4) Thread scheduling algorithms are platform dependent
Question 43)
Your chief Software designer has shown you a sketch of the new
Computer parts system she is about to create. At the top of
the hierarchy is a Class called Computer and under this are
two child classes. One is called LinuxPC and one is called
WindowsPC. The main difference between the two is that one
runs the Linux operating System and the other runs the Windows
System (of course another difference is that one needs
constant re-booting and the other runs reliably). Under the
WindowsPC are two Sub classes one called Server and one Called
Workstation. How might you appraise your designers work?
1) Give the goahead for further design using the current
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
scheme
2) Ask for a re-design of the hierarchy with changing the
Operating System to a field rather than Class type
3) Ask for the option of WindowsPC to be removed as it will
soon be obsolete
4) Change the hierarchy to remove the need for the superfluous
Computer Class.
Question 44)
Objective 4.1)
Which of the following statements are true
1) An inner class may be defined as static
2) There are NO circumstances where an inner class may be
defined as private
3) An anonymous class may have only one constructor
4) An inner class may extend another class
Question 45)
What will happen when you attempt to compile and run the
following code
int Output=10;
boolean b1 = false;
if((b1==true) && ((Output+=10)==20)){
System.out.println("We are equal "+Output);
}else
{
System.out.println("Not equal! "+Output);
}
1) Compile error, attempting to peform binary comparison on
logical data type
2) Compilation and output of "We are equal 10"
3) Compilation and output of "Not equal! 20"
4) Compilation and output of "Not equal! 10"
Question 49)
Which of the following will compile without error?
1) File f = new File("/","autoexec.bat");
2) DataInputStream d = new DataInputStream(System.in);
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
3) OutputStreamWriter o = new OutputStreamWriter(System.out);
4) RandomAccessFile r = new RandomAccessFile("OutFile");
Question 50)
Given the folowing classes which of the following will compile
without error?
interface IFace{}
class CFace implements IFace{}
class Base{}
public class ObRef extends Base{
public static void main(String argv[]){
ObRef ob = new ObRef();
Base b = new Base();
Object o1 = new Object();
IFace o2 = new CFace();
}
}
1)o1=o2;
2)b=ob;
3)ob=b;
4)o1=b;
Question 51)
Given the following code what will be the output?
class ValHold{
public int i = 10;
}
public class ObParm{
public static void main(String argv[]){
ObParm o = new ObParm();
o.amethod();
}
public void amethod(){
int i = 99;
ValHold v = new ValHold();
v.i=30;
another(v,i);
System.out.println(v.i);
}//End of amethod
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
public void another(ValHold v, int i){
i=0;
v.i = 20;
ValHold vh = new ValHold();
v = vh;
System.out.println(v.i+ " "+i);
}//End of another
}
1) 10,0, 30
2) 20,0,30
3) 20,99,30
4) 10,0,20
Question 52)
Given the following class definition, which of the following
methods could be legally placed after the comment
//Here
public class Rid{
public void amethod(int i, String s){}
//Here
}
1)public void amethod(String s, int i){}
2)public int amethod(int i, String s){}
3)public void amethod(int i, String mystring){}
4) public void Amethod(int i, String s) {}
Question 53)
Given the following class definition which of the following
can be legally placed after the comment line
//Here ?
class Base{
public Base(int i){}
}
public class MyOver extends Base{
public static void main(String arg[]){
MyOver m = new MyOver(10);
}
MyOver(int i){
super(i);
}
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
MyOver(String s, int i){
this(i);
//Here
}
}
1)MyOver m = new MyOver();
2)super();
3)this("Hello",10);
4)Base b = new Base(10);
Question 54)
Given the following class definition, which of the following
statements would be legal after the comment //Here
class InOut{
String s= new String("Between");
public void amethod(final int iArgs){
int iam;
class Bicycle{
public void sayHello(){
//Here
}//End of bicycle class
}
}//End of amethod
public void another(){
int iOther;
}
}
1)System.out.println(s);
2) System.out.println(iOther);
3) System.out.println(iam);
4) System.out.println(iArgs);
Question 55)
Which of the following are methods of the Thread class?
1) yield()
2) sleep(long msec)
3) go()
4) stop()
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
Question 56)
Which of the following methods are members of the Vector class
and allow you to input a new element
1) addElement
2) insert
3) append
4) addItem
Question 57)
Which of the following statements are true?
1) Adding more classes via import statements will cause a
performance overhead, only import classes you actually use.
2) Under no circumstances can a class be defined with the
private modifier
3) A inner class may under some circumstances be defined with
the protected modifier
4) An interface cannot be instantiated
Question 59)
Which of the following are methods of the Collection
interface?
1) iterator
2) isEmpty
3) toArray
4) setText
Question 60)
Which of the following best describes the use of the
synhronized keyword?
1) Allows two process to run in paralell but to communicate
with each other
2) Ensures only one thread at a time may access a class or
object
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
3) Ensures that two or more processes will start and end at
the same time
4) Ensures that two or more Threads will start and end at the
same time
JD4
Q 1. What is the output of the following
StringBuffer sb1 = new StringBuffer("Amit");
StringBuffer sb2= new StringBuffer("Amit");
String ss1 = "Amit";
System.out.println(sb1==sb2);
System.out.println(sb1.equals(sb2));
System.out.println(sb1.equals(ss1));
System.out.println("Poddar".substring(3));
Ans:
a) false
false
false
dar
b) false
true
false
Poddar
c) Compiler Error
d) true
true
false
dar
Q9. What is the output of following if the return value is "the value 0 if the argument
string is equal to this string; a value less than 0 if this string is lexicographically less than
the string argument; and a value greater than 0 if this string is lexicographically greater
than the string argument" (Assuming written inside main)
String s5 = "AMIT";
String s6 = "amit";
System.out.println(s5.compareTo(s6));
System.out.println(s6.compareTo(s5));
System.out.println(s6.compareTo(s6));
Ans
a> -32
32
0
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
b> 32
32
0
c> 32
-32
0
d> 0
0
0
Q 10) What is the output (Assuming written inside main)
String s1 = new String("amit");
String s2 = s1.replace('m','i');
s1.concat("Poddar");
System.out.println(s1);
System.out.println((s1+s2).charAt(5));
a) Compile error
b) amitPoddar
o
c) amitPoddar
i
d) amit
i
Q 11) What is the output (Assuming written inside main)
String s1 = new String("amit");
System.out.println(s1.replace('m','r'));
System.out.println(s1);
String s3="arit";
String s4="arit";
String s2 = s1.replace('m','r');
System.out.println(s2==s3);
System.out.println(s3==s4);
a) arit
amit
false
true
b) arit
arit
false
true
c) amit
amit
false
true
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
d) arit
amit
true
true
Q12) Which one does not extend java.lang.Number
1)Integer
2)Boolean
3)Character
4)Long
5)Short
Q13) Which one does not have a valueOf(String) method
1)Integer
2)Boolean
3)Character
4)Long
5)Short
Q.14) What is the output of following (Assuming written inside main)
String s1 = "Amit";
String s2 = "Amit";
String s3 = new String("abcd");
String s4 = new String("abcd");
System.out.println(s1.equals(s2));
System.out.println((s1==s2));
System.out.println(s3.equals(s4));
System.out.println((s3==s4));
a) true
true
true
false
b) true
true
true
true
c) true
false
true
false
Q17) What will be the output of line 5
1 Choice c1 = new Choice();
2 c1.add("First");
3 c1.addItem("Second");
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
4 c1.add("Third");
5 System.out.println(c1.getItemCount());
a) 1
b) 2
c) 3
d) None of the above
Q18) What will be the order of four items added
Choice c1 = new Choice();
c1.add("First");
c1.addItem("Second");
c1.add("Third");
c1.insert("Lastadded",2);
System.out.println(c1.getItemCount());
a) First,Second,Third,Fourth
b) First,Second,Lastadded,Third
c) Lastadded,First,Second,Third
Q19) Answer based on following code
1 Choice c1 = new Choice();
2 c1.add("First");
3 c1.addItem("Second");
4 c1.add("Third");
5 c1.insert("Lastadded",1000);
6 System.out.println(c1.getItemCount());
a) Compile time error
b) Run time error at line 5
c) No error and line 6 will print 1000
d) No error and line 6 will print 4
Q24. Q. What will be the output of follwing
{
double d1 = -0.5d;
System.out.println("Ceil for d1 " + Math.ceil(d1));
System.out.println("Floor for d1 " +Math.floor(d1));
}
Answers:
a) Ceil for d1 0
Floor for d1 -1;
b) Ceil for d1 0
Floor for d1 -1.0;
c) Ceil for d1 0.0
Floor for d1 -1.0;
d) Ceil for d1 -0.0
Floor for d1 -1.0;
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
Q25. What is the output of following
{
float f4 = -5.5f;
float f5 = 5.5f;
float f6 = -5.49f;
float f7 = 5.49f;
System.out.println("Round f4 is " + Math.round(f4));
System.out.println("Round f5 is " + Math.round(f5));
System.out.println("Round f6 is " + Math.round(f6));
System.out.println("Round f7 is " + Math.round(f7));
}
a)Round f4 is -6
Round f5 is 6
Round f6 is -5
Round f7 is 5
b)Round f4 is -5
Round f5 is 6
Round f6 is -5
Round f7 is 5
Q26. Given Integer.MIN_VALUE = -2147483648
Integer.MAX_VALUE = 2147483647
What is the output of following
{
float f4 = Integer.MIN_VALUE;
float f5 = Integer.MAX_VALUE;
float f7 = -2147483655f;
System.out.println("Round f4 is " + Math.round(f4));
System.out.println("Round f5 is " + Math.round(f5));
System.out.println("Round f7 is " + Math.round(f7));
}
a)Round f4 is -2147483648
Round f5 is 2147483647
Round f7 is -2147483648
b)Round f4 is -2147483648
Round f5 is 2147483647
Round f7 is -2147483655
Q27)
1 Boolean b1 = new Boolean("TRUE");
2 Boolean b2 = new Boolean("true");
3 Boolean b3 = new Boolean("JUNK");
4 System.out.println("" + b1 + b2 + b3);
a) Comiler error
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
b) RunTime error
c)truetruefalse
d)truetruetrue
Q 28) In the above Question if line 4 is changed to
System.out.println(b1+b2+b3); The output is
a) Compile time error
b) Run time error
c) truetruefalse
d) truetruetrue
Q 29. What is the output
{
Float f1 = new Float("4.4e99f");
Float f2 = new Float("-4.4e99f");
Double d1 = new Double("4.4e99");
System.out.println(f1);
System.out.println(f2);
System.out.println(d1);
}
a) Runtime error
b) Infinity
-Infinity
4.4E99
c) Infinity
-Infinity
Infinity
d) 4.4E99
-4.4E99
4.4E99
Q30 Q. Which of the following wrapper classes can not
take a "String" in constructor
1) Boolean
2) Integer
3) Long
4) Character
5) Byte
6) Short
Q31. What is the output of following
Double d2 = new Double("-5.5");
Double d3 = new Double("-5.5");
System.out.println(d2==d3);
System.out.println(d2.equals(d3));
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
a) true
true
b) false
false
c) true
false
d) false
true
Q37) Consider a directory structure like this (NT or 95)
C:\JAVA\12345.msg --FILE
\dir1\IO.class -- IO.class is under dir1
Consider the following code
import java.io.*;
public class IO {
public static void main(String args[]) {
File f = new File("..\\12345.msg");
try{
System.out.println(f.getCanonicalPath());
System.out.println(f.getAbsolutePath());
}catch(IOException e){
System.out.println(e);
}
}
}
What will be the output of running "java IO" from C:\java\dir1
a) C:\java\12345.msg
C:\java\dir1\..\12345.msg
b) C:\java\dir1\12345.msg
C:\java\dir1\..\12345.msg
c) C:\java\dir1\..\12345.msg
C:\java\dir1\..\12345.msg
Q 38) Suppose we copy IO.class from C:\java\dir1 to c:\java
What will be the output of running "java IO" from C:\java.
a) C:\java\12345.msg
C:\java\..\12345.msg
b) C:\12345.msg
C:\java\..\12345.msg
c) C:\java\..\12345.msg
C:\java\\..\12345.msg
Q39) Which one of the following methods of java.io.File throws IOException and why
a) getCanonicalPath and getAbsolutePath both require filesystem queries.
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
b) Only getCannonicalPath as it require filesystem queries.
c) Only getAbsolutePath as it require filesystem queries.
Q40) What will be the output if
Consider a directory structure like this (NT or 95)
C:\JAVA\12345.msg --FILE
\dir1\IO.class -- IO.class is under dir1
import java.io.*;
public class IO {
public static void main(String args[]) {
File f = new File("12345.msg");
String arr[] = f.list();
System.out.println(arr.length);
}
}
a) Compiler error as 12345.msg is a file not a directory
b) java.lang.NullPointerException at run time
c) No error , but nothing will be printed on screen
Q41) What will be the output
Consider a directory structure like this (NT or 95)
C:\JAVA\12345.msg --FILE
import java.io.*;
public class IO {
public static void main(String args[]) {
File f1 = new File("\\12345.msg");
System.out.println(f1.getPath());
System.out.println(f1.getParent());
System.out.println(f1.isAbsolute());
System.out.println(f1.getName());
System.out.println(f1.exists());
System.out.println(f1.isFile());
}
}
a) \12345.msg
\
true
12345.msg
true
true
b) \12345.msg
\
true
\12345.msg
false
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
false
c) 12345.msg
\
true
12345.msg
false
false
d) \12345.msg
\
true
12345.msg
false
false
Q42) If in Question no 41 the line
File f1 = new File("\\12345.msg"); is replaced with File f1 = new File("12345.msg");
What will be the output
a) 12345.msg
\
true
12345.msg
true
true
b) 12345.msg
null
true
12345.msg
true
true
c) 12345.msg
null
false
12345.msg
true
true
d) \12345.msg
\
true
12345.msg
false
false
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
Question 1
What will happen if you compile/run this code?
1: public class Q1 extends Thread
2: {
3: public void run()
4: {
5: System.out.println("Before start method");
6: this.stop();
7: System.out.println("After stop method");
8: }
9:
10: public static void main(String[] args)
11: {
12: Q1 a = new Q1();
13: a.start();
14: }
15: }
A) Compilation error at line 7.
B) Runtime exception at line 7.
C) Prints "Before start method" and "After stop method".
D) Prints "Before start method" only.
Question 2
What will happen if you compile/run the following code?
1: class Test
2: {
3: static void show()
4: {
5: System.out.println("Show method in Test class");
6: }
7:}
8:
9: public class Q2 extends Test
10: {
11: static void show()
12: {
13: System.out.println("Show method in Q2 class");
14: }
15: public static void main(String[] args)
16: {
17: Test t = new Test();
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
18: t.show();
19: Q2 q = new Q2();
20: q.show();
21:
22: t = q;
23: t.show();
24:
25: q = t;
26: q.show();
27: }
28: }
A) prints "Show method in Test class"
"Show method in Q2 class"
"Show method in Q2 class"
"Show method in Q2 class"
B) prints "Show method in Test class"
"Show method in Q2 class"
"Show method in Test class"
"Show method in Test class"
C) prints "Show method in Test class"
"Show method in Q2 class"
"Show method in Test class"
"Show method in Q2 class"
D) Compilation error.

Java Interview Questions And Answers 112

What if the main method is declared as private?

The program compiles properly but at runtime it will give "Main method not public." message.

What is meant by pass by reference and pass by value in Java?

Pass by reference means, passing the address itself rather than passing the value. Pass by value means passing a copy of the value.

If you’re overriding the method equals() of an object, which other method you might also consider?

hashCode()

What is Byte Code?

Or

What gives java it’s “write once and run anywhere” nature?

All Java programs are compiled into class files that contain bytecodes. These byte codes can be run in any platform and hence java is said to be platform independent.

Expain the reason for each keyword of public static void main(String args[])?

public- main(..) is the first method called by java environment when a program is executed so it has to accessible from java environment. Hence the access specifier has to be public.

static: Java environment should be able to call this method without creating an instance of the class , so this method must be declared as static.

void: main does not return anything so the return type must be void

The argument String indicates the argument type which is given at the command line and arg is an array for string given during command line.

What are the differences between == and .equals() ?

Or

what is difference between == and equals

Or

Difference between == and equals method

Or

What would you use to compare two String variables - the operator == or the method equals()?

Or

How is it possible for two String objects with identical values not to be equal under the == operator?

The == operator compares two objects to determine if they are the same object in memory i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory.

== compares references while .equals compares contents. The method public boolean equals(Object obj) is provided by the Object class and can be overridden. The default implementation returns true only if the object is compared with itself, which is equivalent to the equality operator == being used to compare aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects, value equality means that they contain the same character sequence. For the Wrapper classes, value equality means that the primitive values are equal.

public class EqualsTest {



public static void main(String[] args) {



String s1 = "abc";

String s2 = s1;

String s5 = "abc";

String s3 = new String("abc");

String s4 = new String("abc");

System.out.println("== comparison : " + (s1 == s5));

System.out.println("== comparison : " + (s1 == s2));

System.out.println("Using equals method : " + s1.equals(s2));

System.out.println("== comparison : " + s3 == s4);

System.out.println("Using equals method : " + s3.equals(s4));

}

}


Output
== comparison : true
== comparison : true
Using equals method : true
false
Using equals method : true

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

Or

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

Program compiles. But at runtime throws an error "NoSuchMethodError".

Why oracle Type 4 driver is named as oracle thin driver?

Oracle provides a Type 4 JDBC driver, referred to as the Oracle “thin” driver. This driver includes its own implementation of a TCP/IP version of Oracle’s Net8 written entirely in Java, so it is platform independent, can be downloaded to a browser at runtime, and does not require any Oracle software on the client side. This driver requires a TCP/IP listener on the server side, and the client connection string uses the TCP/IP port address, not the TNSNAMES entry for the database name.

What is the difference between final, finally and finalize? What do you understand by the java final keyword?

Or

What is final, finalize() and finally?

Or

What is finalize() method?

Or

What is the difference between final, finally and finalize?

Or

What does it mean that a class or member is final?

o final - declare constant
o finally - handles exception
o finalize - helps in garbage collection

Variables defined in an interface are implicitly final. A final class can't be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant). finalize() method is used just before an object is destroyed and garbage collected. finally, a key word used in exception handling and will be executed whether or not an exception is thrown. For example, closing of open connections is done in the finally method.

What is the Java API?

The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.

What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars.

What is the ResourceBundle class?

The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run.

Why there are no global variables in Java?

Global variables are globally accessible. Java does not support globally accessible variables due to following reasons:

* The global variables breaks the referential transparency
* Global variables creates collisions in namespace.

How to convert String to Number in java program?

The valueOf() function of Integer class is is used to convert string to Number. Here is the code example:
String numString = "1000";
int id=Integer.valueOf(numString).intValue();

What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar.

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

A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement (post test) checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the loop body at least once.

What is the Locale class?

The Locale class is used to tailor a program output to the conventions of a particular geographic, political, or cultural region.

Describe the principles of OOPS.

There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.

Explain the Inheritance principle.

Inheritance is the process by which one object acquires the properties of another object. Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places

What is implicit casting?

Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not work for all scenarios.

Example

int i = 1000;

long j = i; //Implicit casting

Is sizeof a keyword in java?

The sizeof operator is not a keyword.

What is a native method?

A native method is a method that is implemented in a language other than Java.

In System.out.println(), what is System, out and println?

System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object.

What are Encapsulation, Inheritance and Polymorphism

Or

Explain the Polymorphism principle. Explain the different forms of Polymorphism.

Polymorphism in simple terms means one name many forms. Polymorphism enables one entity to be used as a general category for different types of actions. The specific action is determined by the exact nature of the situation.

Polymorphism exists in three distinct forms in Java:
• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface

What is explicit casting?

Explicit casting in the process in which the complier are specifically informed to about transforming the object.

Example

long i = 700.20;

int j = (int) i; //Explicit casting

What is the Java Virtual Machine (JVM)?

The Java Virtual Machine is software that can be ported onto various hardware-based platforms

What do you understand by downcasting?

The process of Downcasting refers to the casting from a general to a more specific type, i.e. casting down the hierarchy

What are Java Access Specifiers?

Or

What is the difference between public, private, protected and default Access Specifiers?

Or

What are different types of access modifiers?

Access specifiers are keywords that determine the type of access to the member of a class. These keywords are for allowing
privileges to parts of a program such as functions and variables. These are:
• Public : accessible to all classes
• Protected : accessible to the classes within the same package and any subclasses.
• Private : accessible only to the class to which they belong
• Default : accessible to the class to which they belong and to subclasses within the same package

Which class is the superclass of every class?

Object.

Name primitive Java types.

The 8 primitive types are byte, char, short, int, long, float, double, and boolean.

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

Or

What are class variables?

Or

What is static in java?

Or

What is a static method?

A static variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static variables i.e. there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static keyword in a class. These are declared outside a class and stored in static memory. Class variables are mostly used for constants. Static variables are always called by the class name. This variable is created when the program starts and gets destroyed when the programs stops. The scope of the class variable is same an instance variable. Its initial value is same as instance variable and gets a default value when its not initialized corresponding to the data type. Similarly, a static method is a method that belongs to the class rather than any object of the class and doesn't apply to an object or even require that any objects of the class have been instantiated.
Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a non-static method. In other words, you can't change a static method into an instance method in a subclass.

Non-static variables take on unique values with each object instance.

What is the difference between the boolean & operator and the && operator?

If an expression involving the boolean & operator is evaluated, both operands are evaluated, whereas the && operator is a short cut operator. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. I

How does Java handle integer overflows and underflows?

It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

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

Program compiles and runs properly.

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

In declaration we only mention the type of the variable and its name without initializing it. Defining means declaration + initialization. E.g. String s; is just a declaration while String s = new String ("bob"); Or String s = "bob"; are both definitions.

What type of parameter passing does Java support?

In Java the arguments (primitives and objects) are always passed by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object.

Explain the Encapsulation principle.

Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. Objects allow procedures to be encapsulated with their data to reduce potential interference. One way t

Java Interview Questions And Answers 108

The program compiles properly but at runtime it will give "Main method not public." message.

What is meant by pass by reference and pass by value in Java?

Pass by reference means, passing the address itself rather than passing the value. Pass by value means passing a copy of the value.

If you’re overriding the method equals() of an object, which other method you might also consider?

hashCode()

What is Byte Code?

Or

What gives java it’s “write once and run anywhere” nature?

All Java programs are compiled into class files that contain bytecodes. These byte codes can be run in any platform and hence java is said to be platform independent.

Expain the reason for each keyword of public static void main(String args[])?

public- main(..) is the first method called by java environment when a program is executed so it has to accessible from java environment. Hence the access specifier has to be public.

static: Java environment should be able to call this method without creating an instance of the class , so this method must be declared as static.

void: main does not return anything so the return type must be void

The argument String indicates the argument type which is given at the command line and arg is an array for string given during command line.

What are the differences between == and .equals() ?

Or

what is difference between == and equals

Or

Difference between == and equals method

Or

What would you use to compare two String variables - the operator == or the method equals()?

Or

How is it possible for two String objects with identical values not to be equal under the == operator?

The == operator compares two objects to determine if they are the same object in memory i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory.

== compares references while .equals compares contents. The method public boolean equals(Object obj) is provided by the Object class and can be overridden. The default implementation returns true only if the object is compared with itself, which is equivalent to the equality operator == being used to compare aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects, value equality means that they contain the same character sequence. For the Wrapper classes, value equality means that the primitive values are equal.

public class EqualsTest {



public static void main(String[] args) {



String s1 = "abc";

String s2 = s1;

String s5 = "abc";

String s3 = new String("abc");

String s4 = new String("abc");

System.out.println("== comparison : " + (s1 == s5));

System.out.println("== comparison : " + (s1 == s2));

System.out.println("Using equals method : " + s1.equals(s2));

System.out.println("== comparison : " + s3 == s4);

System.out.println("Using equals method : " + s3.equals(s4));

}

}


Output
== comparison : true
== comparison : true
Using equals method : true
false
Using equals method : true

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

Or

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

Program compiles. But at runtime throws an error "NoSuchMethodError".

Why oracle Type 4 driver is named as oracle thin driver?

Oracle provides a Type 4 JDBC driver, referred to as the Oracle “thin” driver. This driver includes its own implementation of a TCP/IP version of Oracle’s Net8 written entirely in Java, so it is platform independent, can be downloaded to a browser at runtime, and does not require any Oracle software on the client side. This driver requires a TCP/IP listener on the server side, and the client connection string uses the TCP/IP port address, not the TNSNAMES entry for the database name.

What is the difference between final, finally and finalize? What do you understand by the java final keyword?

Or

What is final, finalize() and finally?

Or

What is finalize() method?

Or

What is the difference between final, finally and finalize?

Or

What does it mean that a class or member is final?

o final - declare constant
o finally - handles exception
o finalize - helps in garbage collection

Variables defined in an interface are implicitly final. A final class can't be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant). finalize() method is used just before an object is destroyed and garbage collected. finally, a key word used in exception handling and will be executed whether or not an exception is thrown. For example, closing of open connections is done in the finally method.

What is the Java API?

The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.

What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars.

What is the ResourceBundle class?

The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run.

Why there are no global variables in Java?

Global variables are globally accessible. Java does not support globally accessible variables due to following reasons:

* The global variables breaks the referential transparency
* Global variables creates collisions in namespace.

How to convert String to Number in java program?

The valueOf() function of Integer class is is used to convert string to Number. Here is the code example:
String numString = "1000";
int id=Integer.valueOf(numString).intValue();

What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar.

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

A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement (post test) checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the loop body at least once.

What is the Locale class?

The Locale class is used to tailor a program output to the conventions of a particular geographic, political, or cultural region.

Describe the principles of OOPS.

There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.

Explain the Inheritance principle.

Inheritance is the process by which one object acquires the properties of another object. Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places

What is implicit casting?

Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not work for all scenarios.

Example

int i = 1000;

long j = i; //Implicit casting

Is sizeof a keyword in java?

The sizeof operator is not a keyword.

What is a native method?

A native method is a method that is implemented in a language other than Java.

In System.out.println(), what is System, out and println?

System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object.

What are Encapsulation, Inheritance and Polymorphism

Or

Explain the Polymorphism principle. Explain the different forms of Polymorphism.

Polymorphism in simple terms means one name many forms. Polymorphism enables one entity to be used as a general category for different types of actions. The specific action is determined by the exact nature of the situation.

Polymorphism exists in three distinct forms in Java:
• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface

What is explicit casting?

Explicit casting in the process in which the complier are specifically informed to about transforming the object.

Example

long i = 700.20;

int j = (int) i; //Explicit casting

What is the Java Virtual Machine (JVM)?

The Java Virtual Machine is software that can be ported onto various hardware-based platforms

What do you understand by downcasting?

The process of Downcasting refers to the casting from a general to a more specific type, i.e. casting down the hierarchy

What are Java Access Specifiers?

Or

What is the difference between public, private, protected and default Access Specifiers?

Or

What are different types of access modifiers?

Access specifiers are keywords that determine the type of access to the member of a class. These keywords are for allowing
privileges to parts of a program such as functions and variables. These are:
• Public : accessible to all classes
• Protected : accessible to the classes within the same package and any subclasses.
• Private : accessible only to the class to which they belong
• Default : accessible to the class to which they belong and to subclasses within the same package

Which class is the superclass of every class?

Object.

Name primitive Java types.

The 8 primitive types are byte, char, short, int, long, float, double, and boolean.

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

Or

What are class variables?

Or

What is static in java?

Or

What is a static method?

A static variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static variables i.e. there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static keyword in a class. These are declared outside a class and stored in static memory. Class variables are mostly used for constants. Static variables are always called by the class name. This variable is created when the program starts and gets destroyed when the programs stops. The scope of the class variable is same an instance variable. Its initial value is same as instance variable and gets a default value when its not initialized corresponding to the data type. Similarly, a static method is a method that belongs to the class rather than any object of the class and doesn't apply to an object or even require that any objects of the class have been instantiated.
Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a non-static method. In other words, you can't change a static method into an instance method in a subclass.

Non-static variables take on unique values with each object instance.

What is the difference between the boolean & operator and the && operator?

If an expression involving the boolean & operator is evaluated, both operands are evaluated, whereas the && operator is a short cut operator. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. I

How does Java handle integer overflows and underflows?

It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

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

Program compiles and runs properly.

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

In declaration we only mention the type of the variable and its name without initializing it. Defining means declaration + initialization. E.g. String s; is just a declaration while String s = new String ("bob"); Or String s = "bob"; are both definitions.

What type of parameter passing does Java support?

In Java the arguments (primitives and objects) are always passed by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object.

Explain the Encapsulation principle.

Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. Objects allow procedures to be encapsulated with their data to reduce potential interference. One way t

Advanced enterprise Java interview questions 106

1) What is the purpose of garbage collection in Java, and when is it used?

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

2) Describe synchronization in respect to multithreading.

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

>

3) How is JavaBeans differ from Enterprise JavaBeans?

The JavaBeans architecture is meant to provide a format for general-purpose components. On the other hand, the Enterprise JavaBeans architecture provides a format for highly specialized business logic components.

4) In what ways do design patterns help build better software?

Design patterns helps software developers to reuse successful designs and architectures. It helps them to choose design alternatives that make a system reusuable and avoid alternatives that compromise reusability through proven techniques as design patterns.

5) Describe 3-Tier Architecture in enterprise application development.

In 3-tier architecture, an application is broken up into 3 separate logical layers, each with a well-defined set of interfaces. The presentation layer typically consists of a graphical user interfaces. The business layer consists of the application or business logic, and the data layer contains the data that is needed for the application.

Advanced JAVA questions 104

What is RMI?
Explain about RMI Architecture?
What are Servelets?
What is the use of servlets?
Explain RMI Architecture?
How will you pass values from htm page to the servlet?
How do you load an image in a Servelet?
What is purpose of applet programming?
How will you communicate between two applets?
What IS the difference between Servelets and Applets?
How do you communicate in between Applets and Servlets?
What is the difference between applet and application?
What is the difference between CGI and Servlet?
In the servlets, we are having a web page that is invoking servlets ,username and password? which is checks in database? Suppose the second page also if we want to verify the same information whether it will connect to the database or it will be used previous information?
What are the difference between RMI and Servelets?
How will you call an Applet using Java Script Function?
How can you push data from an Applet to a Servlet?
What are 4 drivers available in JDBC? At what situation are four of the drivers used?
If you are truncated using JDBC , how can you that how much data is truncated?
How will you perform truncation using JDBC?
What is the latest version of JDBC? What are the new features added in that?
What is the difference between RMI registry and OS Agent?
To a server method, the client wants to send a value 20, with this value exceeds to 20 a message should be sent to the client . What will you do for achieving this?
How do you invoke a Servelet? What is the difference between doPost method and doGet method?
What is difference between the HTTP Servelet and Generic Servelet? Explain about their methods and parameters?
Can we use threads in Servelets?
Write a program on RMI and JDBC using Stored Procedure?
How do you swing an applet?
How will you pass parameters in RMI? Why do you serialize?
In RMI ,server object is first loaded into memory and then the stub reference is sent to the client. true or false?
Suppose server object not loaded into the memory and the client request for it. What will happen?
What is the web server used for running the servelets?
What is Servlet API used for connecting database?
What is bean? Where can it be used?
What is the difference between java class and bean?
Can we sent objects using Sockets?
What is the RMI and Socket?
What is CORBA?
Can you modify an object in corba?
What is RMI and what are the services in RMI?
What are the difference between RMI and CORBA?
How will you initialize an Applet?
What is the order of method invocation in an Applet?
What is ODBC and JDBC? How do you connect the Database?
What do you mean by Socket Programming?
What is difference between Generic Servlet and HTTP Servelet?
What you mean by COM and DCOM?
what is e-commerce?

(FAQ) Advanced Java Interview Questions 100

1. What is RMI?
2. Explain about RMI Architecture?
3. What are Servelets?
4. What is the use of servlets?
5. Explain RMI Architecture?
6. How will you pass values from htm page to the servlet?
7. How do you load an image in a Servelet?
8. What is purpose of applet programming?
9. How will you communicate between two applets?
10. What IS the difference between Servelets and Applets?
11. How do you communicate in between Applets and Servlets?
12. What is the difference between applet and application?
13. What is the difference between CGI and Servlet?
14. In the servlets, we are having a web page that is invoking servlets ,username and password? which is checks in database? Suppose the second page also if we want to verify the same information whether it will connect to the database or it will be used previous information?
15. What are the difference between RMI and Servelets?
16. How will you call an Applet using Java Script Function?
17. How can you push data from an Applet to a Servlet?
18. What are 4 drivers available in JDBC? At what situation are four of the drivers used?
19. If you are truncated using JDBC , how can you that how much data is truncated?
20. How will you perform truncation using JDBC?
21. What is the latest version of JDBC? What are the new features added in that?
22. What is the difference between RMI registry and OS Agent?
23. To a server method, the client wants to send a value 20, with this value exceeds to 20 a message should be sent to the client . What will you do for achieving this?
24. How do you invoke a Servelet? What is the difference between doPost method and doGet method?
25. What is difference between the HTTP Servelet and Generic Servelet? Explain about their methods and parameters?
26. Can we use threads in Servelets?
27. Write a program on RMI and JDBC using Stored Procedure?
28. How do you swing an applet?
29. How will you pass parameters in RMI? Why do you serialize?
30. In RMI ,server object is first loaded into memory and then the stub reference is sent to the client. true or false?
31. Suppose server object not loaded into the memory and the client request for it. What will happen?
32. What is the web server used for running the servelets?
33. What is Servlet API used for connecting database?
34. What is bean? Where can it be used?
35. What is the difference between java class and bean?
36. Can we sent objects using Sockets?
37. What is the RMI and Socket?
38. What is CORBA?
39. Can you modify an object in corba?
40. What is RMI and what are the services in RMI?
41. What are the difference between RMI and CORBA?
42. How will you initialize an Applet?
43. What is the order of method invocation in an Applet?
44. What is ODBC and JDBC? How do you connect the Database?
45. What do you mean by Socket Programming?
46. What is difference between Generic Servlet and HTTP Servelet?
47. What you mean by COM and DCOM?
48. what is e-commerce?

TrainJava Blog interviews 98

This is a interview test for a Java programmer at an advanced level. There are 10 questions but more than a single answer to most of the questions. The correct answers are given at the end of the article together with the points awarded for each correct option and the difficulty of the question on a 1-10 scale. The best score you can get is 100 by answering correctly to all questions.

1. Question : Language Features - OO rules

What is going to happen when the following program executes?

class A {
public void a() {
b();
}
private void b() {
System.out.println(“Executing A’s b()”);
}
}
class B extends A {
public void b() {
System.out.println(“Executing B’s b()”);
}
}

public static void main(String[] argv) {
B b = new B();
b.b();
b.a();
}
1. B’s b() will run and then A’s b() will run
2. A’s b() is going to be called twice
3. B’s b() is going to be called twice
4. A’s b() will run and the B’s b() will run
5. The compiler will not allow the above code to compile

2. Question : APIs - Swing

Swing Components can change their look and feel (l&F) at runtime.
Which of the l&f come standard with swing?

1. macintosh l&f
2. metal l&f
3. motif l&f
4. windows l&f
5. vax l&f

3. Question : VM Architecture : Parts and Design

Which of the following statements concerning the Virtual Machine are true and which are false?

1. Object are stored in the heap, local variables are stored in the stack.
2. The Virtual Machine has 8 registers, each one has the length of one word.
3. The Virtual Machine does not differentiate between an instance method and a constructor method.
4. A StackFrame gets created into the VM’s stack area for every thread executed.
5. The VM keeps a program counter for every thread.

4. Question : VM Architecture : Performance

Which of the following statements concerning performance are true and which are false?

1. Methods called through an interface reference are slower than those called through abstract methods because they can never be pointed directly by fields in the class pool of the caller
2. The invocation of an interface method is slower than Instantiation
3. The statement x = 3 executes faster than the statement x = 15.
4. Hotspot compilers convert all the bytecode into native code at runtime
5. Polymorphic calls are almost as fast as static method calls.

5. Question : Language Features - Classloaders

When two objects loaded through different Classloaders can they communicate?

1. When the invoker object access the other object through an interface that has been loaded using the invoker object’s classloader.
2. When they belong to the same package
3. When the invoker’s classloader has resolved the class of the other object
4. When the Security Manager allows it
5. Never, objects loaded using different Classloaders can’t communicate.

6. Question : Language Features - Reflection

Which of the following are valid ways of making an instance from class X

1. X myX = new X();
2. X myX = (X)((X.class).newInstance())
3. X myX = (X)Class.instantiate(X);
4. X myX = (X)(X.class).getClass().forName(”X”).newInstance();
5. X myX = (X)(Class.forName(”X”)).newInstance())

7. Question : Language Tools - Debuggers - Dissassemblers - Profilers

Which of the following statements are true and which are false?

1. JPDA stands for Java Personal Digital Assistant
2. SerVer is a jdk tool that allows serial verification of test profiles
3. The 4 first bytes on the header of any valid class file says JAVABABE
4. The bytecode form of a program can’t store the identifier names
5. Changing a String value of a bytecode class file will damage the file and render it unloadable.

8. Question : Object Orientation Principles - Patterns Basic

What is the pattern that best expresses the relationship between AWT’s classes Component and Container?

1. Factory
2. Strategy
3. Composite
4. Decorator
5. Proxy

9. Question : Object Orientation Principles - Patterns Advanced

Which of the following statements concerning the use of design patterns into the various java API’s are true and which are false?

1. An AWT’s Toolkit plays the role of an “Abstract Factory”
2. The LayoutManager in AWT plays the role of a “Decorator”
3. The Enumeration Interface reveals actually a “Mediator”
4. A Point in AWT is a “Wrapper”
5. A File is implemented in java using the “Composite” pattern

10. Question : Java API Design

The implementation of which design pattern would significantly improve the layout mechanism in terms of simplicity and readability?

1. State
2. Singleton
3. Null Object
4. Decorator
5. Facade

1. Answer to Question 1:

Answer : 1 = true
Grading : 10 points for the correct answer
Difficulty : 9/10 A.

2. Answer to Question 2:

Answer : 2 = true, 3 = true, 4=true
Grading : 10 points for all the correct answers
Difficulty : 1/10 A.

3. Answer to Question 3:

Answer : 1 = true, 2 = false, 3 = false, 4 = false, 5 = true
Grading : 2 points per correct answer
Difficulty : 4/10 A.

4. Answer to Question 4:

Answer : 1 = true, 2 = false, 3 = true, 4 = false, 5 = false
Grading : 2 points per correct answer
Difficulty : 8/10 A.

5. Answer to Question 5:

Answer : 1 = true
Grading : 10 points for the correct answer
Rational : This question assesses the delegate’s understanding of
Difficulty : 8/10 A.

6. Answer to Question 6:

Answer : 1 = true, 2 = true, 3 = false, 4 = true, 5 = true
Grading : 10 points for giving all four correct answers
Difficulty : 5/10 A.

7. Answer to Question 7:

Answer : 1 = false, 2 = false, 3 = false, 4 = false, 5 = false
Grading : 2 points for every correct answer
Difficulty : 1/10 A.

8. Answer to Question 8:

Answer :3 = true
Grading :10 points for correct answer
Difficulty : 4/10 A.

9. Answer to Question 9:

Answer : 1 = true, 2 = false, 3 = false, 4 = false, 5 = false
Grading : 2 points for every correct answer
Difficulty : 10/10 A.

10. Answer to Question 10:

Answer : 3 = true
Grading : Grading: 10 points for correct answer
Difficulty : 10/10 A.

Java Exceptions Questions 94

Explain the user defined Exceptions?

User defined Exceptions are custom Exception classes defined by the user for specific purpose. A user defined exception can be created by simply sub-classing an Exception class or a subclass of an Exception class. This allows custom exceptions to be generated (using throw clause) and caught in the same way as normal exceptions.
Example:

class CustomException extends Exception {

}

What classes of exceptions may be caught by a catch clause?

A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. Errors are generally irrecoverable conditions

What is the difference between exception and error?

Error's are irrecoverable exceptions. Usually a program terminates when an error is encountered.

What is the difference between throw and throws keywords?

The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as an argument. The exception will be caught by an enclosing try-catch block or propagated further up the calling hierarchy. The throws keyword is a modifier of a method that denotes that an exception may be thrown by the method. An exception can be rethrown.

What class of exceptions are generated by the Java run-time system?

The Java runtime system generates Runtime Exceptions and Errors.

What is the base class for Error and Exception?

Throwable

What are Checked and Unchecked Exceptions?

A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Making an exception checked forces client programmers to deal with the exception may be thrown. Checked exceptions must be caught at compile time. Example: IOException.
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. Example: ArrayIndexOutOfBoundsException. Errors are often irrecoverable conditions.

Does the code in finally block get executed if there is an exception and a return statement in a catch block?

Or

What is the purpose of the finally clause of a try-catch-finally statement?

The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. If an exception occurs and there is a return statement in catch block, the finally block is still executed. The finally block will not be executed when the System.exit(0) statement is executed earlier or on system shut down earlier or the memory is used up earlier before the thread goes to finally block.

try{
//some statements
}
catch{
//statements when exception is caught
}
finally{
//statements executed whether exception occurs or not
}

Does the order of placing catch statements matter in the catch block?

Yes, it does. The FileNoFoundException is inherited from the IOException. So FileNoFoundException is caught before IOException. Exception’s subclasses have to be caught first before the General Exception

Java technical interview guide - part 1 90

I did a technical evaluation for a candidate my employer was looking at awhile ago, so I had an opportunity to try and figure out a good set of technical questions for a prospective intermediate level Java web developer. I’ll just present a whole bunch of questions I came up with - no answers though. I might start up an answers post at a later date, but I don’t want to make this too easy for those trying to fool interviewers. =) Obviously, if you ask every question I have listed here your interview could take hours, so pick and choose what you like. I’d be interested in feedback for ideas on important topics I’ve overlooked or questions that are unfair or unnecessary. I’ve tried to avoid things that can be easily answered with a quick google search, such as basic syntax and API method questions.

Anyways, on to the questions.

General Intro Questions

Just laying the ground work to help lead the way for areas to focus on…

  • Give me a high level description of your experience with the Java platform. What APIs do you have experience with? Servlets? J2EE? Swing?
  • What development methodologies have you used? Which one have you liked the most? The least?
  • What open source frameworks do you have experience with?
  • What other languages have you used?

Object Oriented Principles

  • Define object oriented programming (quite a loaded question…). What are the key OO principles?
  • Describe polymorphism.
  • Describe inheritance (”is-a”) and composition (”has-a”). Can you give an example of a use case for each?
  • What is coupling? Why do we want loose coupling in our systems?

Java Basics

Some very fundamental questions I think any “non-beginner” level dev should know. If there are a lot of problems with these it may not be worth continuing.

  • What is the difference between abstract classes and interfaces?
  • Explain the access modifiers in Java.
  • Talk about method overriding and method overloading and their differences.
  • Why does Java have exceptions? What is the difference between checked and unchecked exceptions?
  • What are constructors? Are they inherited?
  • What is the static modifier used for in regards to classes and methods?
  • What are the equals() and hashcode() ? Describe their contracts.
  • When do you use String and when do you use StringBuffer/StringBuilder

Java Intermediate/Advanced

  • Explain the following statement: Java is always pass-by-value.
  • How do you create an immutable type? What are the advantages of immutability?
  • What is a static inner class? Can you provide an example from the Java API?
  • What are the implications of implementing serializable in an object?
  • Why would you declare a private constructor?
  • When do you want to use unchecked exceptions and when do you want to use checked?
  • Can you explain how Strings are “interned” in Java?
  • What are enumerated types? Why would you use them?

Java Collections

  • What are the core interfaces of the Collection framework?
  • How do Vector and HashTable relate to Collections?
  • Desribe typical use cases or examples of common uses for Map, Set, and Lists.
  • What method(s) should override for objects you plan to add to sets or maps?
  • How do you get an immutable collection?

Threading

If a developer works only in the heavily abstracted world of Spring/Hibernate/whatever, they may not have had to touch an actual Runnable since college. Still, its good to know about threading at least on a basic level.

  • What does the synchronized key word do? Where is it valid to use it (ie inside a method call, static block, etc)?
  • Explain the two ways to instantiate threads in Java.
  • What is “double-checked locking“? What design pattern is it typically associated with? What is wrong with it?
  • What is a daemon thread? How do you create one?
  • What method do you use to start a thread?

Servlets and JSPs

  • What are the steps to create a basic servlet?
  • Describe the lifecycle of a basic servlet - for instance, when are they created? What method is called from a typical HTTP request? What about requests and threads?
  • What does it mean to say that HTTP is stateless? How do servlets provide a possible solution to maintain state for web applications?
  • Are JSP’s thread safe?
  • What are Listeners? What is a typical use for a StartupListener?
  • What are filters and why would you use them?
  • Describe the four different scopes available with servlets?

Design Patterns

  • What are the three types of design patterns?
  • Can you talk about the history of design patterns?
  • Why use design patterns?
  • What is the role of composition (aggregation) in design patterns?
  • What design patterns do you use often and have the most experience with? Can you talk about a typical use case?
  • Can you provide a description of any of the following patterns? Strategy, State, or Template method?
  • What is Model View Controller, and why would you want to use it? What are some of the disadvantages of it?
  • What is inversion of control, and what does it give you?

Open Ended Questions

These questions are more to just stir discussion and debate and to get a feel for the candidate, rather then to get the “right” answer.

  • How would you build a software version of Monopoly?
  • Can you compare (insert dynamic language of choice here - Ruby/Python/Lisp/etc) to Java? When would you prefer one over the other?
  • What do you think is the most common cause of project failure in the software development business?
  • What do you think of the rise of open source over the last ten years? Where do you see open source in the future?
  • What does agile development mean to you?
  • What is your ideal development environment like? Both in terms of hardware and software, and location and surroundings?
  • What was the last technical book you read? Give me the Cliff Notes version of it.
  • What are some of your favorite resources beyond Google? This could include websites, magazines, technical authors, experts, favorite blogs, etc.
  • Do you have experience with Test Driven Development? If so, what do you think of it?
  • What will be the next language or development topic you want to learn about?

Archives