Showing posts with label Interview Question Of Java. Show all posts
Showing posts with label Interview Question Of Java. Show all posts

Friday 15 July 2016

Advance Java Basic Interview Question Part 1



1. What is a transient variable?

A transient variable is a variable that may not be serialized.

2. Which containers use a border Layout as their default layout?

The Window, Frame and Dialog classes use a border layout as their default layout.

3. Why do threads block on I/O?

Threads block on I/O (that is enters the waiting state) so that other threads may execute while the I/O Operation is performed.

' 4. How are Observer and Observable used?

Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

5. What is synchronization and why is it important?

With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors.

6. Can a lock be acquired on a class?

Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object

7. What's new with the stop(), suspend() and resume() methods in JDK 1.2?

The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

8. Is null a keyword?

The null is not a keyword.

9. What is the preferred size of a component?

The preferred size of a component is the minimum component size that will allow the component to display normally.

10. What method is used to specify a container's layout?

The setLayout() method is used to specify a container's layout.

11. Which containers use a FlowLayout as their default layout?

The Panel and Applet classes use the FlowLayout as their default layout.

12. What state does a thread enter when it terminates its processing?

When a thread terminates its processing, it enters the dead state

13. What is the Collections API?

The Collections API is a set of classes and interfaces that support operations on collections of objects.

14. Which characters may be used as the second character of an identifier, but not as the first character of an identifier?

The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.

15. What is the List interface?

The List interface provides support for ordered collections of objects.

16. 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.

17. What is the Vector class?

The Vector class provides the capability to implement a growable array of objects

18. What modifiers may be used with an inner class that is a member of an outer class?

A (non-local) inner class may be declared as public, protected, private, static, final, or abstract

19. What is an Iterator interface?

The Iterator interface is used to step through the elements of a Collection.

20. What is the difference between the >> and >>> operators?

The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.

21. Which method of the Component class is used to set the position and size of a component?

setBounds() method is used to set the position and size of a component.

22. What is the difference between yielding and sleeping?

When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.

23. Which java.util classes and interfaces support event handling?

The EventObject class and the EventListener interface support event processing.

24. Is sizeof a keyword?

The sizeof operator is not a keyword.

25. What are wrapped classes?

Wrapped classes are classes that allow primitive types to be accessed as objects.

26. Does garbage collection guarantee that a program will not run out of memory?

Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.

27. What restrictions are placed on the location of a package statement within a source code file?

A package statement must appear as the first line in a source code file (excluding blank lines and comments).

28. Can an object's finalize() method be invoked while it is reachable?

An object's finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize() method may be invoked by other objects.

29. What is the immediate superclass of the Applet class?

Panel

30. What is the difference between pre-emptive scheduling and time slicing?

Under pre-emptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then re-enters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors

31. Name three Component subclasses that support painting.

The Canvas, Frame, Panel, and Applet classes support painting.

32. What value does readLine() return when it has reached the end of a file?

The readLine() method returns null when it has reached the end of a file.

33. What is the immediate superclass of the Dialog class?

Window

34. What is clipping?

Clipping is the process of confining paint operations to a limited area or shape.

35. What is a native method?

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

36. Can a for statement loop indefinitely?

Yes, a for statement can loop indefinitely. For example, consider the following:

for(;;) ;

37. What are order of precedence and associativity, and how are they used?

Order of precedence determines the order in which operators are evaluated in expressions. Associativity determines whether an expression is evaluated left-to- right or right-to- left.

38. When a thread blocks on I/O, what state does it enter?

A thread enters the waiting state when it blocks on I/O.

39. To what value is a variable of the String type automatically initialized?

The default value of an String type is null.

40. What is the catch or declare rule for method declarations?

If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.

41. What is the difference between a MenuItem and a CheckboxMenuItem?

The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked.

42. What is a task's priority and how is it used in scheduling?

A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks

43. What class is the top of the AWT event hierarchy?

The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy.

44. When a thread is created and started, what is its initial state?

A thread is in the ready state after it has been created and started.

45. Can an anonymous class be declared as implementing an interface and extending a class?

An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

46. What is the immediate superclass of Menu?

MenuItem

47. What is the purpose of finalization?

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

48. Which class is the immediate superclass of the MenuComponent class?

Object.

49. What invokes a thread's run() method?

After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.

50. What is the difference between the Boolean & operator and the && operator?

If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. 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. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.

Friday 8 July 2016

Basics Interview Questions Of Java For Beginners Part-4

1. What is the difference between a constructor and a method?

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

2. 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.

3. 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.

4. What is an abstract class?

Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie. you may not call its constructor), abstract class may contain static data.

Any class with an abstract method is automatically abstract itself, and must be declared as such. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.

5. What is the difference between an Interface and an Abstract class?

An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract.

An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.

6. Explain different way of using thread?

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


7. What is an Iterator?

Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn.

Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.

8. State the significance of public, private, protected, default modifiers both singly and in

combination and state the effect of package relationships on declared items qualified by these

modifiers.


public: Public class is visible in other packages, field is visible everywhere (class must be public too)

private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.

protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature. This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.

What you get by default ie, without any access modifier (ie, public private or protected). It means that it is visible to all within a particular package.

9. What is static in java?

Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object.

A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

10. What is final class?

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

11. What if the main() method is declared as private?

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

12. What if the static modifier is removed from the signature of the main() method?

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

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

Program compiles and runs properly.

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

Program compiles but throws a runtime error "NoSuchMethodError".

15. What is the first argument of the String array in main() method?

The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.

16. If I do not provide any arguments on the command line, then the String array of main() method will be empty or null?

It is empty. But not null.

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

Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.

18. What environment variables do I need to set on my machine in order to be able to run Java

programs?

CLASSPATH and PATH are the two variables.

19. Can an application have multiple classes having main() method?

Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main() method.

20. Can I have multiple main() methods in the same class?

No the program fails to compile. The compiler says that the main() method is already defined in the class.

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

No. It is by default loaded internally by the JVM.

22. Can I import same package/class twice? Will the JVM load the package twice at runtime?

One can import the same package or same class multiple times. Neither compiler nor JVM complains about it. And the JVM will internally load the class only once no matter how many times you import the same class.

23. What are Checked and UnChecked Exception?

A checked exception is some subclass of Exception (or Exception itself), excluding class  RuntimeException and its subclasses. Making an exception checked forces client programmers to
deal with the possibility that the exception will be thrown.

Example: IOException thrown by java.io.FileInputStream's read() method·


Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers  may not even know that the exception could be thrown.

Example: StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

24. What is Overriding?

When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass.

When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, ot more private

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

Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying, can not resolve symbol

symbol : class ABCD

location: package io

import java.io.ABCD;

' 26. Does importing a package imports the subpackages as well? Example: Does importing 
com.MyTest.* also import com.MyTest.UnitTests.*?

No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage.

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

In declaration we just mention the type of the variable and it's name. We do not initialize it. But
defining means declaration + initialization.

Example: String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.

28. What is the default value of an object reference declared as an instance variable?

The default value will be null unless we define it explicitly.

29. Can a top level class be private or protected?

No. A top level class cannot be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.

If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with  protected.

30. What type of parameter passing does Java support?

In Java the arguments are always passed by value

Thursday 7 July 2016

Basics Interview Questions Of Java For Beginners Part-3

Question 51:- Describe the different stages in the life cycle of an applet.

Answer:- The stages in the life cycle of an applet are-

1. Born or initialization state

2. Running state

3. Idle state

4. Dead or destroyed state

Born or initialization state: - Applet enters the initialization state when it is first loaded. This is achieved by calling the init () method of Applet class. The applet is born. At this stage, we may do the following if required

a) Create objects needed by the applet

b) Set up initial values

c) Load images or fonts

d) Set up colors

The initialization occurs only once in the applet’s life cycle. To provide any of the behaviours ,we must override the init() method.

Running state: - Applet enters the running state when the system calls the start( ) method of Applet Class. This occurs automatically after the applet is initialized. Starting can also occur if the Applet is already in ‘stopped” ( idle) state. For example, we may leave the web page containing the applet temporarily to another page and return back to the page. This again starts the applet running. Note that, unlike init( ) method, the start( ) method may be called more than once. We may override the start( ) method to create a thread to control the applet.

Idle or stopped state: - An applet becomes idle when it is stopped from running. Stopping occurs automatically when we leave the page containing the currently running applet. We can also do so by calling the stop( ) method explicitly. If we use a thread to run the applet, then we must use stop( ) method to terminate the thread. We can achieve this by overriding the stop( ) method;

Dead state: - An applet is said to be dead when it is removed from memory. This occurs automatically by invoking the destroy( ) method when we quit the browser. Like initialization, destroying stage occurs only once in the applet’s life cycle. If the applet has created any resources, like threads, we may override the destroy( ) method to clean up these resources.

Question 52 :- What is event handling?

Answer :- Event handling is a mechanism that is used to handle events generated by applets. An event could be the occurrence of any activity such as a mouse click or a key press. In java, events are regarded as method calls with a certain task performed against the occurrence of each event.

Question 53:- Name some of the key events?

Answer:- Some of the key events are:

1.ActionEvent is triggered whenever a user interface element is activated, such as selection of a menu item.

2. ItemEvent is triggered at the selection or deselection of an itemized or list element, such as checkbox.

3. TextEvent is triggered when a text field is modified.

4. WindowEvent is triggered whenever a window – related operation is performed, such as closing or activating a window.

Question 54:- Define Event Listeners.

Answer:- The event listener object contains methods for receiving and processing event notifications sent by the source object. These methods are implemented from the corresponding listener interface contained in the java.awt.event package.

Question 55 :-Define Event Classes.

Answer:- All the events in java have corresponding event classes associated with item. Each of these classes is derived from one single super class, i.e., EventObject. It is contained in the java.util package. The EventObject class contains the following two important methods for handling events:

1. getSource(): Returns the event source.

2. toString (): Returns a string containing information about the event source.

Question 56: How is java’s coordinate system organized?

Answer:- Java’s coordinate system has the origin (0, 0) in the upper–left corner. Positive x values are to the right, and positive y values are to the bottom. The values of coordinates x and y are in pixels.

Question 57:- Describe the arguments used in the method drawRoundRect( ).

Answer:- The drawRoundRect() method takes 6 arguments:-The first two represent the x and y coordinates of the top left corner of the rectangle,and the next two represent the width and the height of the rectangle and the remaining two represent the width and height of the angle of corners.

Question 58 :- What is AWT?

Answer:-The Abstract Windowing Toolkit ( AWT) IS AN APL that is responsible for building the Graphical User Interface ( GUI). It is a part of java Foundation Classes (JFC). AWT includes a rich set of user interface components, a powerful event handling model, graphics and image tools, layout managers and support for data transfer using cut and paste through clipboards. AWT also supports JavaBeans architecture. Every AWT component is a simple bean. The java.awt package contains all classes for creating user interfaces and for painting graphics and image.


Question 59 :- What is Component?

Answer:- Component class is the super class to all the class to all the other classes from which various GUI elements are realized. It is primary responsible for effecting the display of a graphic object on the screen. It also handles the various keyboard and mouse events of the GUI application.

Question 60:- What is Container?

Answer:- The Container object contains the other awt components. It manages the layout and placement of the various awt components within the container. A container object can contain other containers objects as well; thus allowing nesting of containers.

Question 61:- What is Window?

Answer:- The Window object realizes a top-level window but without any border or menu bar. It just specifies the layout of the window. A typical window that you would want to create in your application is not normally derived from the Window class but from its subclass, i.e., Frame.

Question 62:- What is Panel?

Answer:- The super class of applet, Panel represents a window space on which the application’s output is displayed. It is just like a normal window having no border, title bar, menu bar, etc. A panel can contain within itself other panels as.

Question 63 :-What is Frame?

Answer:- The Frame object realizes a top-level window complete with border and menu bar. It supports common window- related events such as close, open, activate, deactivate, etc. Almost all the programs that we created while discussing applets and graphics programming used one or more classes of the awt packaged.

Question 64:- Describe the arguments used in the method drawRoundRect ().

Answer:- The arguments used are the first two represent the x and y coordinates of the top left corner of the rectangle and the next two represent the width and height of the rectangle and the remaining two represent the width and height of the angle of the corners.

Question 65:- What is an Error?

Answer:- An error may produce an incorrect output or may terminate the execution of the program abruptly or even may cause in the program will not terminate or crash during execution.

Question 66 :- What are the types of Errors?

Answer:- Errors may broadly be classified into two categories:

1. Compile-time errors:- All syntax errors will be detected and displayed by the java compiler and therefore these errors are known as compile-time errors. Whenever the Compiler displays an error, it will not create the class file. It is therefore necessary that we fix all the errors before we can successfully compile and run the program.

2. Run-time errors:- Sometimes, a program may compile successfully creating the .class file but may not run properly. Such programs may produce wrong results due to wrong logic or may terminate due to errors such as stack overflow. This is called Run-time errors.

Question 67 :- Define exception.

Answer :- An exception is a condition that is caused by a run-time error in the program. When the java interpreter encounters an error such as dividing an integer by zero, it creates an exception object and throws it (i.e. informs us that an error has occurred. The purpose of exception handling mechanism is to provide a means to detect and report an “exceptional circumstance” so that appropriate action can be taken.

Question 68 :- How is Exceptions in java categorized?

Answer :- Exceptions in java can be categorised into two types:

1.Checked exceptions: These exceptions are exceptions are explicitly handled in the code itself with the help of try- catch blocks. Checked exceptions are extended from the java.lang.Eception class.

2. Unchecked exceptions: These exceptions are not essentially handed in the program code; instead the JVM handles such exceptions. Unchecked exceptions are extended from the java.lang.RuntimeException class.

Question 69 :- What is Persistent data?

Answer :- Data stored in files is often called Persistent data.

' Question 70 :- What is Object serialization?

Answer :- The process of reading and writing objects is called object serialization.

Question 71 :- What is a file?

Answer :- A file is a collection of related records placed in a particular area on disk.

Question 72 :- What is a record?

Answer :- A record is composed of several fields and a field is a group of characters.

Question 73 :- What is file processing?

Answer :- Storing and managing data using files is known as file processing which includes tasks such as creating files, updating files and manipulation of data.

Question 74:-What is a stream?

Answer:- A stream in java is a path along which data flows (like a river or a pipe along which water flows). It has a source (of data) and a destination (for that data).

Question 75 :- How is the concept of steams used in java?

Answer:- The concept of sending data from one stream to another (like one pipe feeding into another pipe) has made streams in java a powerful tool for file processing.

Question 76 :- What are input and output streams?

Answer:- Java streams are classified into two basic types, namely, input stream and output stream. An input stream extracts (i.e. reads) data from the source (file) and sends it to the program. Similarly, an output stream takes data from the program and sends (i.e. writes) it to the destination (file).

Question 77:- What is stream class? How are the stream class classified?

Answer:- The java.io package contains a large number of stream classes that provide capabilities for processing all types of data. These classes may be categorized into two groups based on the data type on which they operate.

1.Byte stream classes that provide support for handling I/O operations on bytes.

2. Character stream classes that provide support for managing I/O operations on characters.

Question 78:- Describe the major tasks of input and output stream classes.

Answer :- The super class InputStream is an abstract class, and, therefore, we cannot create instances of this class. Rather, we must use the subclasses that inherit from this class.

The InputStream class defines methods for performing input functions such as

1 Reading bytes

2 Closing streams

3 Marking Positions in streams

4 Skipping ahead in a stream

5 Finding the number of bytes in a stream

Outputstream is an abstract class and therefore we cannot instantiate it. The several subclasses of the OutputStream can be used for performing the output operations.

The Ouptputstream includes methods that are designed to perform the following tasks:

1 Writing bytes

2 Closing streams

3 Flushing streams

Question 79:- What is reader stream class?

Answer:- Reader stream classes are designed to read character from the files. The Reader class contains methods that are identical to those available in the Inputstream class, except reader is designed to handle characters.

Question 80 :- What is writer stream classes?

Answer:- The writer class is an abstract class which acts as a base class for all the other writer stream classes.

Question 81:- What is RandomAccessFile?

Answer:- The RandomAccessFile enables us to read and write bytes, text and java data types to any location in a file (when used with appropriate access permissions). This class extends object class and implements DataInput and Dataoutput interfaces. This forces the RandomAccessFile to implement the methpods described in both these interfaces.


Question 82:- What is Stream Tokenizer?

Answer:- The class Stream Tokenizer, a subclass of object can be used for breaking up a stream of text from an input text file into meaningful pieces called tokens. The behaviour of the Stream Tokenizer class is similar to that of the String Tokenizer class (of java.util Package) that breaks a string into its component tokens.

Question 83:-What is file class?

Answer:- The java.io package includes a class known as the File class that provides support for creating files and directories.

The class includes several constructors for maintaining the file objects. This class also contains several methods for  supporting the operations such as

1 Creating a file

2 Opening a file

3 Closing a file

4 Deleting a file

5 Getting a name of a file

6 Getting the size of a file

7 Checking the existence of a file

8 Renaming of a file

9 Checking whether the file is writable

1o Checking whether the file is readable

Wednesday 6 July 2016

Basics Interview Questions Of Java For Beginners Part-2

Question 26 :- What is the use of hash table?

Answer:-  A hash table stores information using a special calculation on the object to be stored. A hash code is produced as a result of the calculation. The hash code is used to choose the location in which to store the object.

Question 27:- How to define an Interface in Java?

Answer :- In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.

Example of Interface:

public interface sampleInterface {

public void functionOne();

public long CONSTANT_ONE = 1000;

}



Question 28:- What is the difference between class and interface in java?

Answer:- The difference between interface and java are-


CLASS INTERFACE
1. The members of a class can be constant or variables 1. The members of an interface are always declared as constant, i.e. their values are final
2.The class definition can contain the code for each of its methods 2. The methods in interface are abstract in nature i.e. there is no code associated with them.
3. It can be instantiated by declaring objects 3. It cannot be used to declare objects
4. It can use various specifiers like public,private,protected

4. It can only use the public access specifier
Question 29:-What are the similarities between interfaces and classes?

Answer:-

 The similarities between interfaces and classes are-

 An interface is basically a kind of class.

 Like classes, an interface contains methods and variables.

 Both can be inherited.


Question 30:- What is a package?

Answer:- Packages are java’s ways of grouping a variety of classes and /or interfaces together. They are containers for classes that are used to compartmentalize the class name space. Packages are stored in a hierarchical manner and are explicitly imported into new class definitions.

Question 31:- What is static import? How is it useful?

Answer:- It is another language feature introduced with the J2SE 5.0 release. This feature eliminates the need of qualifying a static member with the class name. The static import declaration is similar to that of import. Also static import statement used to import static members from classes and use them without qualifying the class name.

Question 32:- What is a thread?

Answer:- A thread is similar to a program that has a single flow of control. It has a beginning a body, and an end, and executes commands sequentially.

Question 33:- Define multithreaded program.

Answer:- A program that contains multiple flows of control is known as multithreaded program.

Question 34 :- Define concurrency.

Answer:- The ability of a language to support multithreads is referred to as concurrency.

Question 35:- Define lightweight threads.

Answer:- Threads in java are subprograms of a main application program and share the same memory space are known as lightweight threads.

Question 36:- What is the difference between multithreading and multitasking?

Answer :- The difference between multithreading and multitasking are-

Multithreading Multitasking
1.It is a programming concept in which a program or a process is divided into two or more subprograms or threads that are executed at the same time in parallel. 1. It is an operating system concept in which multiple tasks are performed simultaneously.
2.It supports execution of multiple parts of a single program simultaneously. 2. It supports execution of multiple programs simultaneously.
3. The processor has to switch between different parts or threads of a program. 3. The processor has to switch between different programs or processes.
4. It is highly efficient. 4. It is less efficient in comparison to multithreading.
5. A thread is smallest unit in multithreading. 5 .A program or process is the smallest unit in a multitasking environment.
6. It helps in developing efficient programs. 6. It helps in developing efficient operating systems.
7. It is cost- effective in case of context switching. 7. It is expensive in case of context switching



Question 37:- What are the ways to create threads?

Answer:- A new thread can be created in two ways:-

1. By creating a thread class: Define a class thread that extends Thread class and override its run () method with the code required by the thread.

2. By converting a class to a thread: Define a class that implements Runnable interface. The Runnable interface has only one method, run (), that is to be defined in the method with the code to be executed by the thread.

Question 38 :-How do we start a thread?

Answer:- To Start a thread we must write the following code:-

ClassnameaThread = new classname ();

aThread.start ( );

Question 39:- What are the methods by which we may block threads?

Answer:-A thread can be temporarily suspended or blocked from entering into the runnable and subsequently running state

by using either of the following thread methods:-

1. sleep () // blocked for a specified

2. suspend () // blocked until further orders

3. wait () // blocked until certain condition occurs

Question 40 :-What is the difference between suspending and stopping a thread?

Answer:-Suspending a thread means that thread can be revived by using the resume () method. This approach is useful when we want to suspend a thread for some time due to certain reason, but do not want to kill it. Stopping a thread causes the thread to move to the dead state. The stop () method may be used when the premature death of a thread is desired.

Question 41:- How do we set priorities for thread?

Answer:- Java permits us to set the priority of a thread using the setPriority () method as follows:

Thread Name.SetPriority (int Number);

The intNumber is an integer value to which the thread’s priority is set. The Thread class defines several priority constants:

MIN_PRIORITY =1

NORM_PRIORITY =5

MAX_PRIORITY =10

The int number may assume one of these constants or any value between 1 and 10. The default setting is

NORM_PRIORITY.

Question 42:-Describe the complete life cycle of a thread.

Answer:- During the life time of a thread, there are many states it can enter. They include:

1. Newborn state: When we create a thread object, the thread is born and is said to be in newborn state.

2. Runnable state: It means that the thread is ready for execution and is waiting for the availability of the processor.

3. Running state: It means that the processor has given its time to the thread for its execution.

4. Blocked state: It is when thread is prevented from entering into the runnable state and subsequently the running state.

5. Dead state: It is the last stage of the thread. In this stage the thread is killed or it has completed executing its run () method.

Question 43:-Define time-slicing.

Answer :- The process of assigning time to threads is known as time-slicing.

Question 44 :- What is synchronization? When do we use it?

Answer :-Synchronization is a process of controlling the access of shared resources by the multiple threads such a manner that only one thread can access one resource at a time. In non-synchronized multi threaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption. We use this when a situation such as one thread may try to read a record from a file while another is still writing to the same file arises.

= Question 45:- What is an applet?

Answer :- Applets are small java programs that are primarily used in internet computing. They can be transported over the internet from one computer to another and run using the Applet viewer or any web browser that supports java. It can perform arithmetic operations, display graphics, play sounds, accept user input, create animation, and play interactive games.

Question 46:- What is a local applet?

Answer:- An applet developed locally and stored in a local system is known as alocal applet. When a web page is trying to find as a local applet, it does not need to use internet connection and therefore the local system does not use the internet connection. It simply searches the directories in the local system and locates and loads the specified applet.

Question 47 :- What is a remote applet?

Answer:- A remote applet is that which is developed by someone else and stored on a remote computer connected to the internet. If our system is connected to the internet, we can download the remote applet onto our system via at the internet and run it.

Question 48 :- How do applets differ from application programs?

Answer:- Applets differ from application programs in the following ways-

 Applets do not use the main () method for initiating the execution of the code. Applets, when loaded, automatically call certain methods of Applet class to start and execute the applet code

 Unlike stand-alone applications, applets cannot be run independently. They are run from inside a web page using a special feature known as HTML tag

 Applets cannot read from or write to the files in the local computer

 Applets cannot communicate with other servers on the network

 Applets cannot run any program from the local computer

 Applets are restricted from using libraries from other languages such as C or C++

Question 49:- What are the various sections of Web Page?

Answer:- A web page is basically made up of text and HTML tags that can be interpreted by a web browser or an applet viewer. A web page is marked by an opening HTML tag <HTML> and a closing HTML tag<\HTML> and is divided into the following three major sections-

1. Comment section ( optional )

2. Head section ( optional )

3. Body section


Header section: - The head section is defined with a starting <HEAD> tag and a closing <\HEAD> tag. This section usually contains a title for the web page.

Body section:-This section contains the entire information about the web page and its behaviour. We can set u many options to indicate how our page must appear on the screen (like color, location, sound etc.) It contains applet tag also.

Question 50:- How many arguments can be passed to an applet using <PARAM> tags?

Answer:- We can supply user-defined parameters to an applet using <PARAM> tags. Each <PARAM> tag has a name attribute such as color, and a value attribute such as red. Inside the applet code, the applet can refer to that parameter by name to find its value.

Tuesday 5 July 2016

Basics Interview Questions Of Java For Beginners

Question 1 :- When and who invented java?

Answer:- Java is developed by Sun Microsystems of USA in 1991.

Question 2:- Why is java known as platform-neutral language?

Answer:- It is so because java is not tied to any particular hardware or operating system. Programs developed in java can be executed anywhere on any system.

Question 3:- How is java more secured than other languages?

Answer:- It is so because java systems not only verify all memory access but also ensure that no viruses are communicated with an applet. The absence of pointers in java ensures that programs cannot gain access to memory locations without proper authorization.

Question 4:- What is the difference between java and C?

Answer:-

                               Java                                                                     C

1.It doesn’t have C unique statement keywords       1.It contains the unique keywords sizeof, and
sizeof,andtypedef.                                                        tyedef.

2.It doesn’t have data types struct and union.           2.It contains data types struct and union.

3.It doesn’t support an explicit pointer type.            3.It support an explicit pointer type.

4.It adds labelled break and continue statements    .4.It doesn’t have break and continuestatements.

5.It doesn’t have a preprocessor.                              5.It have preprocessor.


Question 5:- What is the difference between Java and C++?

Answer:-

                      Java                                                                              C++

1. It doesn’t support operator overloading.                1. It supports operator overloading.

2. It doesn’t have template classes.                            2. It has template classes.

3. It doesn’t have multiple inheritance.                      3. It has multiple inheritance.

4. It doesn’t support global variables.                        4. It supports global variables.

5. It doesn’t use pointers.                                           5. It uses pointers.

6. It uses finalize () function.                                     6. It uses destructor () function.

7. There are no header files in java.                           7. It has header files.

Question 6:- Why do we need import statement in java?

Answer:- It is because using import statements we can have access to classes that are part of other named package.

Question 7:- What is the task of main () method in a java program?

Answer:- The main method creates objects of various classes and establishes communication between them. On reaching the end of main, the program terminates and the control passes back to the operating system.

Question 8:- What are separators? What are the various separators used in java?

Answer:- Separators are symbols used to indicate where groups of code are divided and arranged. They basically define the shape and function of our code.

Java includes six types of separators:-

1. Parentheses ()

2, Braces {}

3. Brackets []

4. Semicolon ;

5. Comma ,

6. Period

Question 9:- What are command line arguments? How are they useful?

Answer:- They are the parameters that are supplied to the application program at the time of invoking it for execution. They are useful as we make like our program to act in a particular way depending on the input provided at the time of execution which is achieved by command line arguments.

Question 10 :- Java is a freeform language. Comment.

Answer:- It is a freeform language as we need not have to indent any lines to make the program work properly. Also java system does not care where on the line we begin typing.

Question 11:- List the features of java?

Answer:-Java has the following features:-

 Simple and powerful

 Secure

 Portable

 Object-oriented

 Robust

 Multithreaded

 Architecture-neutral

 Interpreted and High performance

 Distributed

 Dynamic

Question 12:- What are the newly added features in java 2?

Answer:- The following are the newly added features in java 2:-

 Swing

 Collections framework

 Various tools such as javac, java and javadoc have been enhanced.

 Just-In- Time (JIT) compiler

 Policy files

 Digital certificates

 Advanced features for working with shapes, images and text.

 Various security tools

 The user can now play audio files such as MIDI, AU, WAV and RMF files using java programs.

Sub domain:-Fundamentals of java

Question 13 :- What is type casting? Why is it required in programming?

Answer :-The process of converting one data type to another is called casting. It is required because we often encounter situations where there is a need to store a value of one type into a variable of other type. Casting is often necessary when a method returns a type different than the one we require.

Syntax:-

Type variable1 = (type) variable2;

Question 14:- What are wrapper classes? What is their use?

Answer:- Wrapper classes are provided for the primitive data types in order to use these types as objects. The wrapper classes for the primitive data types have the same name as the primitive type, but with the first letter capitalized. The advantage of using wrappers is that when an object is passed to a method, the method is able to work on the object itself. Also the user can derive his/her own classes from java’s built-in wrapper classes.

Question 15:- What is a literal? What are the difference types of literals?

Answer:- A literal represents a value of a certain type where the type describes the behavior of the value. The different types of literals are:-

 Number literals

 Character literals

 Boolean literals

 String literals

Question 16 :- What is a variable? What are the different types of variables?

Answer :- Variables are locations in the memory that can hold values. Java has three kinds of variables namely,

 Instance variable

 Local variable

 Class Variable

Local variables are used inside blocks as counters or in methods as temporary variables. Once the block or the method is executed, the variable ceases to exist. Instance variables are used to define attributes or the state of a particular object. These are used to store information needed by multiple methods in the objects.

Domain: -Classes,Objects, Methods

Question 17:- What is Collection API?

Answer:- The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hash tables if effectively replaces.

Example of classes: Hash Set, Hash Map, Array List, Linked List, Tree Set and Tree Map.

Example of interfaces: Collection, Set, List and Map.

Question 18:- Is Iterator a Class or Interface? What is its use?

Answer:- Iterator is an interface which is used to step through the elements of a Collection.

Question 19 :- What is similarities/difference between an Abstract class and Interface?

Answer:- Differences are as follows:

Interfaces provide a form of multiple inheritances. A class can extend only one other class. Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.

A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.

Interfaces are slow as it requires extra indirection to find corresponding method in in the actual class. Abstract classes are fast.

Similarities:

Neither Abstract classes or Interface can be instantiated.

Question 20:- How to define an Abstract class?

Answer:- A class containing abstract method is called Abstract class. An Abstract class can't be instantiated.

Example of Abstract class:

abstract class testAbstractClass {

protected String myString;

public String getMyString() {

return myString;

}

public abstract string anyAbstractFunction();

}

Question 21 :-When do we create member of a class static?

Answer:- Static variables are used when we want to have a variable common to all instances of a class. Java creates only one copy for static variable which can be used even if the class is never actually instantiated.

Question 22:- Describe the syntax of single inheritance in java?

Answer:-

Syntax:-

Class subclassname extends superclassname

{

Variables declaration;

Methods declaration;

}

Question 23 :- Describe method overloading and method overriding?

Answer :- The process in which methods have same name, but different parameter lists and different definitions is called method overloading. It is used when objects are required to perform similar tasks but using different input parameters. These are the forms of Static polymorphism. Domain:-Arrays and Strings

Question 24 :-What is string Buffer?

Answer :-It is a peer class of string that provides much of the common functionality of strings. Strings represent fixed-length character sequences. String Buffer represents varied length character sequences. String buffer may have characters and substrings inserted in the middle, or appended at the end. The complier automatically creates a String Buffer to evaluate certain expressions, in particular when the overloaded operators + and += are used with string objects.

Question 25:- What are arrays?

Answer:- An array is an object that stores a list of items. Each slot in an array holds individual elements. An array should be of a single type, comprising of integers, strings and so on.