Some interview questions
What is the default value of byte datatype in Java
0
How can a dead thread be started?
A dead thread cannot be restarted
what is an applet
A java program that runs in a Web browser, can be fully functional Java app because it has the entire Java API at its disposal
Difference between Swing and AWT components
AWT is heavy weight, Swing is light weight. Heavy weight depends on the local windowing toolkit (ex. java.awt.Button) when running on Java platform it maps to a real Motif button
what is polymorphism
Ability of object to take on many forms. most common use is when parent class reference is used to refer to child class object
difference between an interface and an abstract class
Abstract class can have instance methods that implement a default behavior Interface can only declare constans and instance methods BUT cannot implement default behavior, and all methods are implicitly abstract. Interface has all public members and no implementation
When a thread is created and started what is its initial state
After created and started a thread is in the ready state
What inokes a thread's run() method
After the thread it started via its start() method of Thread class the JVM invokes the threads run() method when the thread is inititally executed
What needs to be kept in mind while creating your own expections in java
All exceptions must be a child of throwable if you want to write a checked exception that is automaticaally enforced by Handle or Declare rule you need to extend the Exception class if you write a runtime exception you need to extend the runtimeException class
What is a Runtime Exception
Are ignored at the time of compilation, will compile
Difference between a break statement and continue statment
Break results in termination of statement to which it applies(switch, for, do, or while) a continue statement is used to end the current loop iteration and return control to the loop statement
What are advantages of arrayList over arrays
Can grow dynamically and provides more powerful insertion and search mechanisms than arrays
What is meant by checked exception
Cannot be ignored at the time of compilation, won't compile
What kind of variables can be in a class?
Class can consists of local, instance or class variables
What is a static variable
Class variable, declared with stataic keyword but outside a method, constructor or a block
What are Wrapper classes
Classes that allow primitive types to be accessed as objects EX: Integer, Character, Double, Boolean, etc.
Why is Java Architectural Neutral
Compiler generates achitecture-neutral object file format, makes compiled code executable on many processors as long as Java runtime is present
which class is immediate superclass of Container class
Component class is immediate super class
difference between ocnstructors and other methods
Constructors must have same name as class and can not return a value, only called once Regular methods could be called many times
Singleton class
Control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes
Three steps for creating an Object for a class
Declared Instantiated Initialized
What is the difference between error and an exception
Error is irrecoverable condition at runtime(ex. OutOfMemory) Exceptions are conditinos that occur because of bad input (ex. FileNotFound)
What is final class
Final classes are creataed so the methods implemented by that class cannot be overridden can't be inherited
Difference between Window and a Frame
Frame class extends Window to define a main app window that can have a menu bar
Define packages in Java
Group of related types(classes, interfaces, enumeraations and annotations) providing access protection and name space management
Define composition
Holding the reference of the other classes within some other class is known as composition
What are two subclasses under exception class?
IOException class and RuntimeException class
When is throws keyword used
If a method doesn't handle a checked exception, the method must declare it using the throws keyword, appears at end of methods signature.
What are two ways in which thread can be created
Implementing Runnable interface, extending the thread class
Which arithmetic operations can result in the throwing of an ArithemticException
Integer / and %
List IDE's for Java
Intelisence, Netbeans, Eclipse
Features of interface
Interface -cannot be instantiated -does not contain any constructors -all the methods are abstract
What do mean by Constructor
Invoked when a new object is created. Every claass has one, if you don't make one then the compiler creates a default one for you
Is it necessary that each try block must be followed by a catch block
It is not necessary that each try block be followed by a catch block, it should be followed by a catch block or a finally block
Define Jave Runtime Element
JRE: an implementation of the JVM which executes Java programs. provides min requirements for executing a Java app
What is JAR file
Java Archive File, it aggregates many files into one. Holds Java classes in a library, JAR files are build on ZIP file formate and have .jar file extension
What do you know about Java?
Java is a high-level programing language. Runs on variety of platforms
What makes Java High Performance
Java uses Just-In-Time compiler, turns Java bytecode which is a program that must be interpreted into instructions that are sent directly to processor
purpose of default constructor
Javaa compiler creates a default constructor only if there is no constructor in the class
What is a method
Methods operate on an objects internal state and serve as the primary mechanism for object-to-object communication
Can a top level class be private or protected?
No, a top level class is either public or has no modifier
Can constructor be inherited
No, constructor cannot be inherited
Does garbage collection guarantee that a program will not run out of memory
No, it is possible for programs to use up memory faster than garbage is collected, also possible to create objects not subject to garbage collection
Caan a constructor be made final
No, that is not possible
What whill happen if a static modifier is removed from signature of main method?
NoSuchMethodError is thrown at runtime
default value of ano object reference delcared as an instance variable
Null, unless it is defined explicitly
List any five features of Java
Object Oriented Platform Independent Robust Multi-threaded Interpreted
What is difference between object oriented programming language and object based programming language
Object based programming langauges follow all features of OOPs except inheritance. JavaScript is an example of object based programming language
What does Object mean
Object is an instance of a class, its state is stored in fields and its behavior is shown in methods.
Define Immutable
Once created it cannot be changed
What is String considered immutable
Once it is created the object cannot be changed. It can safely be shared between many threads which is important for multi-threading programming
If a variable is private, where may the variable be accessed?
Only within the class in which it is declared
Immediate superclass of Applet class?
Panel is the immediate superclass. provides space in which an app can attach any other component including other panels
java.util.regex consists of which classes?
Pattern class Matcher class PatternSyntaxException class
According to Java Operator precedence, which operator is considered to have the highest precedence?
Postfix operators () [] have the highest precedence
Define Inheritance
Process where one object acquires the properties of another. With use of inheritance information is managed in a hierarchical order
Why is Vector class used?
Provides capability to implement a growable array of objects. Vector is useful if don't know the size of array in advance, or if you need one that can change sizes
Difference between Reader/Writer class heirarchy and InputSteam/OutputStream class heirarchy
Reader/Writer class is character oriented, Input/Output class is byte oriented
What is runtime polymorphism or dynamic method dispatch
Runtimme polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process an overrident method is called through the reference variable of a superclass
Serialization and deserialization
Serialization is process of writing the state of an object to a byte stream, deserialization is process of restoring these objects
Why is StringBuffer called mutable
String class is immutable, so once created it cannot be chaanged, You would use StringBuffer to make modifications to the String of characters. So since it can modify/change the Buffer is considered mutable
Use of subclass in a Java program
Sub class inherits all the public and protected methods and implementation. also inherits the default modifier methods and their implementation
What are synchronized methods and synchronized statements
Synchronized methods are used to control access to an object Syncrhonized statements can only be executed after a thread has acquired the lock for the object class or reference in the sychronized statement
Which Java operator is right associative
The = operator is right associative
What does access modifier mean/refer to
They set access levels for claasses, variables, methods and constructors members have package or default accessibility if one isn't declared
difference between throw and throws
Throw: used to trigger an exception where as Throws: is used in declaration of exception w/out throws checked exception cannot be handled, where as a checked excpetion caan be propagaated with throws
Whata is nullPointerException
Thrown when calling the instance method of a null object, accessing, or modifying the filed of a null object
When can pasreInt() method be used?
To get the primitive data type of a specific String
when should you use the byte datatype
To save space in a large array, mainly in place of integers
How many bits are in Unicode ASCII UTF-16 UTF-8
Unicode requires 16 ASCII requires 7, represented as 8 UTF-8 represents usins 8, 16 and 18 bit patters UTF-16 uses 16 bit and larger
Explain garbage collection in Java
Used to free memory, cleans objects that are no longer reference by any of the program
Class variables
Variables declared within a class, outside any method with the static keyword
What is a local variable
Variables defined inside methods, constructors or blocks. variable is declared and initialized within the method and it will be destroyed once the method is completed
Instance variable
Variables witin a class but outside any method. They are instantiated when the class is loaded
Why do we need wrapper classes?
We can pass them around as method parameters where a method expects and object. it also provides utility methods
What is a WAR file
Web Archive file, used to store XML, java classes, and JavaServer pages. used to distribute a collection of JavaServer Pages, Java Servlets, Java classes, XML files, static web pages etc.
What is function overloading
When a class has multiple functions of the same name but with different parameters. Same name, different signature
What is Java Virtual Machine
When compiled Java is not platform specific, it is platform independent, the JVM interprets the code on whichever platform Java is running on
When is ArrayStoreException thrown
When copying elements between diff arrays if the source or destination argument types are not compatible
What is difference between yielding and sleeping
When invoking yield() method it returns to ready state When invoking sleep() method it returns to waiting state
What platforms are supported by Java?
Windows, Mac OS, Unix/Linus
Limitations of using inheritance?
Yes, since inheritance inherits everything from superclass and its interface it may make subclass too clusterd and error-prone when dynamic overloading or overriding
Can try statements be nested?
Yes, try statements can be nested
Can you call one constructor from another if a class has multiple constructors?
Yes, use this() syntax
Does it matter what order catch statements for FileNotFoundException and IOException are written
Yes. FileNotFoundException is inherited from the IOException. Exception's subclasses have to be caught first
Can you write a Java class that could be used both as an applet as well as an application?
Yes. just add a main() method to the applet
Define class
a blue print from what objects are created. Can contain fields and methods to describe the behavior of an object
What are ClassLoaders
a class loader is an object that is responsible for loading classes, ClassLoader is an Abstract class
What is an Exception
a problem that arises during the execution of a program. caught by hanglers positioned along the threads method invocation stack
Variable that boolean is automatically initialized as
booleans are automatically false
What datatypes can be used in in switch statments?
byte, short, int or char
what is Abstract class
cannot be instantiated and are either partially implemented or not at all implemented. Class contains one or more abstract methods which are simply method declarations without a body
synchronization
capability to control the access of mulitple threads to sharaed resources, provids locking which ensures mutuaal exclusive access of shared resources and prevent data race
what is an interface
collection of abstract methods. A class implements an interface thereby inheriting the abstract methods of interface
Explain Set interface
collection of element which cannot contain duplicaate elements. contains only methods inherited from Collection aand adds the restriction that duplicate elements are prohibited
What does multithreaded program mean?
contains two or more parts that can run concurrently. Each part of such a program is called a thread, each thread defines a seperate path of execution
Why is java considered dynamic
designed to adapt to an evolving environment can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time
what is default value of floaat or double datatype
float = 0.0f double = 0.0d
what conditions is an objects finale() invoked by garbage collector
garbage collector invokes an objects finalize() method when it detects that the object is unreachable
what class exceptions are generated by Java run-time system
generates RuntimeException and Error exceptions
When is super keyword used?
if child method overrides one of its superclass's methods. overridden methods can be invoked through use of super. can also refer to a hidden field
When is an Abstract method used
if you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes
List keywords unique to Java
import, super, finally
JIT compiler?
improves the runtime performance of computer programs based on bytecode
List primitive java types
int, boolean, char, double, float, short, long, byte
Extends which class
java.applect.Applet
Which class should you use to obtain design information about an object
java.lang.Class class instance represents classes, interfaces in a running Java app
Which package is used for pattern matchine with regular expressions
java.util.regex
Which package has light weight components
javax.Swing.package, most components of Swing are light weight
how does multi-threading take place on a computer with a single CPU
operating systems task schedulr aallocates execution time to multiple tasks. By quickly switching between executing tasks it creates the impression that the task execute sequentially
Overloading vs. overriding
overloading increases readability of the prograam. overriding provides specific implementation of the method that is already provided by its super class
what does protected accesss modifier mean
package level, used in inheritence when a class is extended from the superclass
paint() vs repaint()
paint() supports painting via a Graphics object. repaint() used to cause paint() to be invoked by the AWT painting thread
What are use cases?
part of the analysis of a program and describes a situation that a program might encounter and what behavior the program should exhibit in that circumstance
snychronized Non Access Modifier
provide functionalities other than Access Modifiers, syncrhonized is used to indicate that a method can be accessed by only one thread at a time
Explain public static void main (String args[])
public: access specifier static: allows main() to be called without instantiating a particular instance of a class void: tells compiler that no value is returned by main main(): called at beginning of Java program String args[]: args parameter is an instance arry of class String
what is abstraction
reduces complexity and improves maintainabiltiy of the system.
What is Dynamic binding(late binding)
referes to linking of a procedure call to the code to be executed in response to the call. Dynamic binding means that the code associated with a given procedure call is not known unitl time of the call at run-time
Explain treeset
set implemented when we wanat elements in a sorted order
What is Collections API
set of classes and interfaces that support operations on collections of objects
Diff between sleep() and wai()
sleep() puts thread aside for exactly 2 sec, wait() causes a wait up to 2 seconds
Difference between static and non-static variables
static variable is associated with the class as a whole, rather than a specific instance of the class. Non-static variables take on unique values with each object instance
what is encapsulation
technique of making fields in a class private and providing access to the fields via a public method. if field is declared private it cannot be accessed by anyone outside the class, also called data hiding
benefit of encapsulation
the main benefit of encapsulation is ability to modify our implemented code w/out breaking the code of oethers who use our code. gives maintaiablity, flexibilty and extensibility of our code
What are the ways in which a thread can enter the waiting state
thread can enter the waiting state by invoking its sleep() method by blocking on IO, by unsuccessfully attempting to acquire an objects lock or by invoking an objects wait() method. it can also enter the waiting state by invoking its (deprecated) suspend() method
why are packages used?
to prevent naming conflicts, control access, and organization
Purpose of the System class
to provide access to system resources
Difference between StringBuffer and StringBuilder
use StringBuilder whenever possible because its faster, but if thread safety is necessary then use StringBuffer objects
How is finally used under exception handling?
used to create a block of code that follows a try block, always executes whether or not an exception has occured
Purpose of File class?
used to create objects that provide access to the files and directorires of local file system
what is finalize() method
used to ensure that object terminates cleanly, defined just before aan objects final destruction by the garbage collector
Whata is static block
used to initialize the static data member, executed before main method at the time of classloading
comparable interface
used to sort collections and arraays of objects using the collections.sort() and java.utils the objects of that class implementing Comparable interface can be ordered
What is the Locale class
used to tailor program output to the conventions of a particular geographic, polirical or cultural region
explain use of () with regard to constructors
used with variables or methods, used to call constructor of same class
What is a transient variable
variable that may not be serialized during Serialization and which is initilized by its default value during de-serialization
What is function overriding
when a subclass provides a specific implementation of a method that is already provided by its paarent class
relationship between clipping and repaining under AWT
when a window is repainted by AWT it sets clipping regions to the area of the window that requires repainting
When is ArithmeticException thrown
when integer is divided by zero or taking remainder of a number by zero, never thrown in floating-point operations