You are on page 1of 16

TCS:

1.whats inline thread?

ANS: You can start a thread "inline" without implementing Runnable or extending Thread class

( new Thread() { public void run()


{
// do something
} } ).start();

Read more: http://wiki.answers.com/Q/What_is_inline_thread_in_java#ixzz1C9m9Y9Tb

2.Iterate through the values of Java


HashMap example
1. /*
2.   Iterate through the values of Java HashMap example
3.   This Java Example shows how to iterate through the values contained in
the
4.   HashMap object.
5. */
6.  
7. import java.util.Collection;
8. import java.util.HashMap;
9. import java.util.Iterator;
10.  
11. public class IterateValuesOfHashMapExample {
12.  
13. public static void main(String[] args) {
14.  
15. //create HashMap object
16. HashMap hMap = new HashMap();
17.  
18. //add key value pairs to HashMap
19. hMap.put("1","One");
20. hMap.put("2","Two");
21. hMap.put("3","Three");
22.  
23. /*
24.   get Collection of values contained in HashMap using
25.   Collection values() method of HashMap class
26.   */
27. Collection c = hMap.values();
28.  
29. //obtain an Iterator for Collection
30. Iterator itr = c.iterator();
31.  
32. //iterate through HashMap values iterator
33. while(itr.hasNext())
34. System.out.println(itr.next());
35. }
36. }
37.  
38. /*
39. Output would be
40. Three
41. Two
42. One
43. */

3.Java, sorting, ArrayList example, generics

A Java ArrayList holds an ordered sequence of items like an array, but there are differences:

1. An ArrayList has no fixed size but can be extended by adding elements later
2. An ArrayList can only hold objects (not primitives)
3. ArrayList elements are addressed by methods and not by square bracket notation.

Here's an example from yesterday - showing a typical use of an ArrayList; I was reading a file
but didn't know how many lines it contained, so an ArrayList gave me the flexibility I needed.

import java.io.*;
import java.util.*;
 
public class Pesort {
 
public static void main (String [] args) throws Exception {
 
   // Following line up to Java 1.4 then gives warnings
   //ArrayList Stuff = new ArrayList();
 
   // OR following line from Java 1.5;
   // this specifies that the ArrayList is to contain Strings
 
   ArrayList <String> Stuff = new ArrayList<String>();
 
   // Above lines show use of "Generics" - compare to
   // Templates in C++
 
   BufferedReader Source = new BufferedReader(
      new FileReader("../request.txt"));
 
   System.out.println("---------- UnSorted");
 
   while (Source.ready() ) {
      String Line = Source.readLine();   
      System.out.println(Line);
      Stuff.add(Line);
      }
 
   System.out.println("---------- Alphabetic Sort");
   
   Collections.sort(Stuff);
 
   Iterator stepper = Stuff.iterator();
   while (stepper.hasNext()) {
      String current = (String)stepper.next();
      System.out.println(current);
      }
   
 
   System.out.println("---------- Sort by line length");
 
   Collections.sort(Stuff, new byLineLength());
 
   stepper = Stuff.iterator();
   while (stepper.hasNext()) {
      String current = (String)stepper.next();
      System.out.println(current);
      }
   }
 
}

4.This example shows you how we can sort items of an ArrayList using the
Collections.sort() methods. Beside accepting the list object to be sorted we can also pass a
Comparator implementation to define the sorting behavior.

view source
print?
01.package org.kodejava.example.util;
02. 
03.import java.util.ArrayList;
04.import java.util.Arrays;
05.import java.util.Collections;
06.import java.util.List;
07. 
08.public class ArrayListSortExample {
09.    public static void main(String[] args) {
10.        /*
11.         * Create a collections of colours
12.         */
13.        List colours = new ArrayList();
14.        colours.add("red");
15.        colours.add("green");
16.        colours.add("blue");
17.        colours.add("yellow");
18.        colours.add("cyan");
19.        colours.add("white");
20.        colours.add("black");
21. 
22.        /*
23.         * We can sort items of a list using the Collections.sort() method.
24.         * We can also reverse the order of the sorting by passing the
25.         * Collections.reverseOrder() comparator.
26.         */
27.        Collections.sort(colours);
28.        System.out.println(Arrays.toString(colours.toArray()));
29. 
30.        Collections.sort(colours, Collections.reverseOrder());
31.        System.out.println(Arrays.toString(colours.toArray()));
32.    }
33.}
1.what is serialization in java?

Serialization involves saving the current state of an object to a stream, and restoring an equivalent
object from that stream

Serialization is the process of saving an object in a storage medium (such as a file, or a memory buffer)
or to transmit it over a network connection  in binary form.  The serialized objects are JVM independent
and can be re-serialized by any JVM. In this case the "in memory" java objects state are converted into a
byte stream. This type of the file can not be understood by the user. It is a special types of object i.e.
reused by the JVM (Java Virtual Machine). This process of serializing an object is also called deflating or
marshalling an object.

import java.io.*;

  public class SerializingObject{
 
  public static void main(String[] args) throws IOException{
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Please enter File name : ");
 
    String file = in.readLine();
 
   System.out.print("Enter extention : ");
 
    String ext = in.readLine();
  
  String filename = file + "." + ext;
 
   File f = new File(filename);
  
  try{
   
   ObjectOutput ObjOut = new ObjectOutputStream(new FileOutputStream(f));
 
     ObjOut.writeObject(f);
  
     ObjOut.close();
 
     System.out.println(
     "Serializing an Object Creation completed successfully.");
 
    }
    
catch(IOException e){
   
   System.out.println(e.getMessage());

      }
  
}

  }
Output of the Program:

C:\nisha>javac
SerializingObject.java

C:\nisha>java SerializingObject
Please enter File name :
Filterfile
Enter extention : txt
Serializing an Object Creation is
completly Successfully.

C:\nisha>

What is transient keyword in Java?


What is Serilization?

If you want to understand what is transient, then first learn what is serilization concept in Java
if you are not familiar with that. Serilization is the process of making the object's state
persistent. That means the state of the object is converted into stream of bytes and stored in a file.
In the same way we can use the de-serilization concept to bring back the object's state from
bytes. This is one of the important concept in Java programming because this serilization is
mostly used in the networking programming. The object's which are needs to be transmitted
through network has to be converted as bytes, for that purpose ever class or interface must
implements Serilization interface. It is a marker interface without any methods.

What is Transient?

By default all the variables in the object is converted into the persistent. In some cases, you may
want to avoid persisting some variables because you don't have the necesscity to persist those
varibale. So, you can declare those variables as transient. if the variable is declared as transient,
then it will not be persisted. It is the main purpose of the transient keyword.

Transient Keyword Example

Look into the following example to understand the purpose of transient keyword:

package javabeat.samples;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class NameStore implements Serializable{


private String firstName;
private transient String middleName;
private String lastName;
public NameStore (String fName, String mName, String lName){
this.firstName = fName;
this.middleName = mName;
this.lastName = lName;
}
public String toString(){
StringBuffer sb = new StringBuffer(40);
sb.append("First Name : ");
sb.append(this.firstName);
sb.append("Middle Name : ");
sb.append(this.middleName);
sb.append("Last Name : ");
sb.append(this.lastName);
return sb.toString();
}
}
public class TransientExample{
public static void main(String args[]) throws Exception {
NameStore nameStore = new NameStore("Steve","Middle","Jobs");
ObjectOutputStream o = new ObjectOutputStream(new
FileOutputStream(
"nameStore"));
// writing to object
o.writeObject(nameStore);
o.close();

// reading from object


ObjectInputStream in =new ObjectInputStream(
new FileInputStream("nameStore"));
NameStore nameStore1 = (NameStore)in.readObject();
System.out.println(nameStore1);
}
}

// output will be : First Name : SteveMiddle Name : nullLast Name : Jobs

Transient:

The transient is a keyword defined in the java programming language. Keywords are basically
reserved words which have specific meaning relevant to a compiler in java programming
language likewise the transient keyword indicates the following :
-- The transient keyword is applicable to the member variables of a class.
-- The transient keyword is used to indicate that the member variable should not be serialized
when the class instance containing that transient variable  is needed to be serialized.

Example to use the transient keyword with a variable:

public class Class1{

private transient String password;

}  
Voltail VS Transient;
Java defines two interesting type modifiers: transient and volatile. These modifiers are used to
handle somewhat specialized situations.

When an instance variable is declared as transient, then its value need not persist when an object
is stored. For example:

class T {

transient int a; // will not persist

int b; // will persist

Here, if an object of type T is written to a persistent storage area, the contents of a would not be
saved, but the contents of b would. The volatile modifier tells the compiler that the variable
modified by volatile can be changed unexpectedly by other parts of your program. One of these
situations involves multithreaded programs.  In a multithreaded program, sometimes, two or
more threads share the same instance variable. For efficiency considerations, each thread can
keep its own, private copy of such a shared variable. The real (or master) copy of the variable is
updated at various times, such as when a synchronized method is entered. While this approach
works fine, it may be inefficient at times. In some cases, all that really matters is that the master
copy of a variable always reflects its current state. To ensure this, simply specify the variable as
volatile, which tells the compiler that it must always use the master copy of a volatile variable
(or, at least, always keep any private copies up to date with the master copy, and vice versa).
Also, accesses to the master variable must be executed in the precise order in which they are
executed on any private copy.

volatile Java Keyword


The volatile is a keyword defined in the java programming language. Keywords are basically
reserved words which have specific meaning relevant to a compiler in java programming
language likewise the volatile keyword indicates the following :

-- The volatile keyword is mostly used to indicate that a member variable of a class may get
modified asynchronously by more than one thread.
-- This thing is noticable that the volatile keyword is not implemented in many Java Virtual
Machines.
-- The volatile keyword from the side of compiler tries to guarantee that all the threads should
see the same value of a specified variable.

Example to use the volatile keyword in a class:

public class Cla

volatile int sharableValue;

 
1.How could Java classes direct program messages to the system console, but error
messages, say to a file?

The class System has a variable out that represents the standard output, and the variable err that
represents the standard error device. By default, they both point at the system console. This how
the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream(“output.txt”)); System.setErr(st);
System.setOut(st);

2.How would you create a button with rounded edges?

There’s 2 ways. The first thing is to know that a JButton’s edges are drawn by a Border. so you
can override the Button’s paintComponent(Graphics) method and draw a circle or rounded
rectangle (whatever), and turn off the border. Or you can create a custom border that draws a
circle or rounded rectangle around any component and set the button’s border to it.

3.Why should the implementation of any Swing callback (like a listener) execute quickly?

A: Because callbacks are invoked by the event dispatch thread which will be blocked processing
other events for as long as your method takes to execute.

4. Question: How you can force the garbage collection?


Garbage collection automatic process and can’t be forced. You could request it by calling
System.gc(). JVM does not guarantee that GC will be started immediately.

Garbage collection is one of the most important feature of Java, Garbage collection is also called
automatic memory management as JVM automatically removes the unused variables/objects
(value is null) from the memory. User program can’t directly free the object from memory,
instead it is the job of the garbage collector to automatically free the objects that are no longer
referenced by a program. Every class inherits finalize() method from java.lang.Object, the
finalize() method is called by garbage collector when it determines no more references to the
object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use.
I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but
there is no guarantee when all the objects will garbage collected.

5. What’s the difference between constructors and normal methods?

Constructors must have the same name as the class and can not return a value. They are only
called once while regular methods could be called many times and it can return a value or can be
void.

6. When should the method invokeLater()be used?

This method is used to ensure that Swing components are updated through the event-dispatching
thread.

7.Explain the usage of Java packages.

This is a way to organize files when a project consists of multiple modules. It also helps resolve
naming conflicts when different packages have classes with the same names. Packages access
level also allows you to protect data from being used by the non-authorized classes.

8.What are some advantages and disadvantages of Java Sockets?

Some advantages of Java Sockets:


Sockets are flexible and sufficient. Efficient socket based programming can be easily
implemented for general communications. Sockets cause low network traffic. Unlike HTML
forms and CGI scripts that generate and transfer whole web pages for each new request, Java
applets can send only necessary updated information.

Some disadvantages of Java Sockets:


Security restrictions are sometimes overbearing because a Java applet running in a Web browser
is only able to establish connections to the machine where it came from, and to nowhere else on
the network   Despite all of the useful and helpful Java features, Socket based communications
allows only to send packets of raw data between applications. Both the client-side and server-
side have to provide mechanisms to make the data useful in any way.

9.What is Collection API?


The Collection API is a set of classes and interfaces that support operation on collections of
objects. These classes and interfaces are more flexible, more powerful, and more regular than the
vectors, arrays, and hashtables if effectively replaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.

10.Explain the usage of the keyword transient?

Transient keyword indicates that the value of this member variable does not have to be serialized
with the object. When the class will be de-serialized, this variable will be initialized with a
default value of its data type (i.e. zero for integers).

11.What’s the difference between the methods sleep() and wait()

The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a
wait of up to one second. A thread could stop waiting earlier if it receives the notify() or
notifyAll() call. The method wait() is defined in the class Object and the method sleep() is
defined in the class Thread.

12.Why would you use a synchronized block vs. synchronized method?

Synchronized blocks place locks for shorter periods than synchronized methods.

13.Can an inner class declared inside of a method access local variables of this method?
It’s possible if these variables are final.

14.Explain the user defined Exceptions?

User defined Exceptions are the separate Exception classes defined by the user for specific
purposed. An user defined can created by simply sub-classing it to the Exception class. This
allows custom exceptions to be generated (using throw) and caught in the same way as normal
exceptions.

Example:

class myCustomException extends Exception {


/ The class simply has to exist to be an exception
}

15.Describe the wrapper classes in Java.

Wrapper class is wrapper around a primitive data type. An instance of a  wrapper class contains,
or wraps, a primitive value of the corresponding type.

Following table lists the primitive types and the corresponding wrapper classes:
Primitive Wrapper
boolean  – java.lang.Boolean
byte – java.lang.Byte
char – java.lang.Character
double – java.lang.Double
float – java.lang.Float
int – java.lang.Integer
long – java.lang.Long
short – java.lang.Short
void – java.lang.Void

16.Which of the following are valid definitions of an application’s main( ) method?

a) public static void main();


b) public static void main( String args );
c) public static void main( String args[] );
d) public static void main( Graphics g );
e) public static boolean main( String args[] );

1. What is garbage collection? What is the process that is responsible for doing that in java? –
Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this
process
2. What kind of thread is the Garbage collector thread? – It is a daemon thread.
3. What is a daemon thread? – These are the threads which can run without user intervention.
The JVM can exit when there are daemon thread by killing them abruptly.
4. How will you invoke any external process in Java? – Runtime.getRuntime().exec(….)
5. What is the finalize method do? – Before the invalid objects get garbage collected, the JVM give
the user a chance to clean up some resources before it got garbage collected.
6. What is mutable object and immutable object? – If a object value is changeable then we can
call it as Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the value of an
object, it is immutable object. (Ex., String, Integer, Float, …)
7. What is the basic difference between string and stringbuffer object? – String is an immutable
object. StringBuffer is a mutable object.
8. What is the purpose of Void class? – The Void class is an uninstantiable placeholder class to
hold a reference to the Class object representing the primitive Java type void.
9. What is reflection? – Reflection allows programmatic access to information about the fields,
methods and constructors of loaded classes, and the use reflected fields, methods, and
constructors to operate on their underlying counterparts on objects, within security restrictions.
10. What is the base class for Error and Exception? – Throwable
11. What is the byte range? -128 to 127
12. What is the implementation of destroy method in java.. is it native or java code? – This
method is not implemented.
13. What is a package? – To group set of classes into a single unit is known as packaging. Packages
provides wide namespace ability.
14. What are the approaches that you will follow for making a program very efficient? – By
avoiding too much of static methods avoiding the excessive and unnecessary use of
synchronized methods Selection of related classes based on the application (meaning
synchronized classes for multiuser and non-synchronized classes for single user) Usage of
appropriate design patterns Using cache methodologies for remote invocations Avoiding
creation of variables within a loop and lot more.
15. What is a DatabaseMetaData? – Comprehensive information about the database as a whole.
16. What is Locale? – A Locale object represents a specific geographical, political, or cultural region
17. How will you load a specific locale? – Using ResourceBundle.getBundle(…);
18. What is JIT and its use? – Really, just a very fast compiler… In this incarnation, pretty much a
one-pass compiler — no offline computations. So you can’t look at the whole method, rank the
expressions according to which ones are re-used the most, and then generate code. In theory
terms, it’s an on-line problem.
19. Is JVM a compiler or an interpreter? – Interpreter
20. When you think about optimization, what is the best way to findout the time/memory
consuming process? – Using profiler
21. What is the purpose of assert keyword used in JDK1.4.x? – In order to validate certain
expressions. It effectively replaces the if block and automatically throws the AssertionError on
failure. This keyword should be used for the critical arguments. Meaning, without that the
method does nothing.
22. How will you get the platform dependent values like line separator, path separator, etc., ? –
Using Sytem.getProperty(…) (line.separator, path.separator, …)
23. What is skeleton and stub? what is the purpose of those? – Stub is a client side representation
of the server, which takes care of communicating with the remote server. Skeleton is the server
side representation. But that is no more in use… it is deprecated long before in JDK.
24. What is the final keyword denotes? – final keyword denotes that it is the final implementation
for that method or variable or class. You can’t override that method/variable/class any more.
25. What is the significance of ListIterator? – You can iterate back and forth.
26. What is the major difference between LinkedList and ArrayList? – LinkedList are meant for
sequential accessing. ArrayList are meant for random accessing.
27. What is nested class? – If all the methods of a inner class is static then it is a nested class.
28. What is inner class? – If the methods of the inner class can only be accessed via the instance of
the inner class, then it is called inner class.
29. What is composition? – Holding the reference of the other class within some other class is
known as composition.
30. What is aggregation? – It is a special type of composition. If you expose all the methods of a
composite class and route the method call to the composite method through its reference, then
it is called aggregation.
31. What are the methods in Object? – clone, equals, wait, finalize, getClass, hashCode, notify,
notifyAll, toString
32. Can you instantiate the Math class? – You can’t instantiate the math class. All the methods in
this class are static. And the constructor is not public.
33. What is singleton? – It is one of the design pattern. This falls in the creational pattern of the
design pattern. There will be only one instance for that entire JVM. You can achieve this by
having the private constructor in the class. For eg., public class Singleton { private static final
Singleton s = new Singleton(); private Singleton() { } public static Singleton getInstance() { return
s; } // all non static methods … }
34. What is DriverManager? – The basic service to manage set of JDBC drivers.
35. What is Class.forName() does and how it is useful? – It loads the class into the ClassLoader. It
returns the Class. Using that you can get the instance ( “class-instance”.newInstance() ).
36. Inq adds a question: Expain the reason for each keyword ofpublic static void main(String args[])
37. Can there be an abstract class with no abstract methods in it? - Yes
38. Can an Interface be final? - No
39. Can an Interface have an inner class? - Yes.
40. public interface abc
41. {
42. static int i=0; void dd();
43. class a1
44. {
45. a1()
46. {
47. int j;
48. System.out.println("inside");
49. };
50. public static void main(String a1[])
51. {
52. System.out.println("in interfia");
53. }
54. }
55. }
56. Can we define private and protected modifiers for variables in interfaces? - No
57. What is Externalizable? - Externalizable is an Interface that extends Serializable
Interface. And sends data into Streams in Compressed Format. It has two methods,
writeExternal(ObjectOuput out) and readExternal(ObjectInput in)
58. What modifiers are allowed for methods in an Interface? - Only public and abstract
modifiers are allowed for methods in interfaces.
59. What is a local, member and a class variable? - Variables declared within a method are
“local” variables. Variables declared within the class i.e not within any methods are
“member” variables (global variables). Variables declared within the class i.e not within
any methods and are defined as “static” are class variables
60. What are the different identifier states of a Thread? - The different identifiers of a
Thread are: R - Running or runnable thread, S - Suspended thread, CW - Thread waiting
on a condition variable, MW - Thread waiting on a monitor lock, MS - Thread suspended
waiting on a monitor lock
61. What are some alternatives to inheritance? - Delegation is an alternative to
inheritance. Delegation means that you include an instance of another class as an instance
variable, and forward messages to the instance. It is often safer than inheritance because
it forces you to think about each message you forward, because the instance is of a
known class, rather than a new class, and because it doesn’t force you to accept all the
methods of the super class: you can provide only the methods that really make sense. On
the other hand, it makes you write more code, and it is harder to re-use (because it is not a
subclass).
62. Why isn’t there operator overloading? - Because C++ has proven by example that
operator overloading makes code almost impossible to maintain. In fact there very nearly
wasn’t even method overloading in Java, but it was thought that this was too useful for
some very basic methods like print(). Note that some of the classes like
DataOutputStream have unoverloaded methods like writeInt() and writeByte().
63. What does it mean that a method or field is “static”? - Static variables and methods
are instantiated only once per class. In other words they are class variables, not instance
variables. If you change the value of a static variable in a particular object, the value of
that variable changes for all instances of that class. Static methods can be referenced with
the name of the class rather than the name of a particular object of the class (though that
works too). That’s how library methods like System.out.println() work. out is a static
field in the java.lang.System class.
64. How do I convert a numeric IP address like 192.18.97.39 into a hostname like
java.sun.com?
65. String hostname =
InetAddress.getByName("192.18.97.39").getHostName();
66. Difference between JRE/JVM/JDK?
67. 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.
68. 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.
69. Is null a keyword? - The null value is not a keyword.
70. 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.
71. 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.
72. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8
characters? - Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII
character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents
characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
73. What are wrapped classes? - Wrapped classes are classes that allow primitive types to
be accessed as objects.
74. 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).
75. What is the difference between preemptive scheduling and time slicing? - Under
preemptive 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 reenters the pool of ready tasks. The
scheduler then determines which task should execute next, based on priority and other
factors.
76. What is a native method? - A native method is a method that is implemented in a
language other than Java.
77. 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.
Associatity determines whether an expression is evaluated left-to-right or right-to-left
78. 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.
79. 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.
80. What is the range of the char type? - The range of the char type is 0 to 2^16 - 1.

You might also like