public class CurrentSystemDate {
public static void main(String[] args) {
SimpleDateFormat sysForm = new SimpleDateFormat("yyyy/MM/DD HH:mm:ss");
Date curdate= new Date();
System.out.println(sysForm.format(curdate));
}
}
All about studying for a Java interview in the Financial and trading services industry. I am a software engineer working with trading systems. 20 years experience coding and all things IT.
Sunday, June 15, 2014
‘SimpleDateFormat’ - use it to display the current system date in ‘yyyy/MM/DD HH:mm:ss’ format?
Explain the difference between an ITERATOR AND an ENUMERATION INTERFACE
- Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
- Iterator actually adds one method that Enumeration doesn’t have: remove ().
What is the exact difference between these two interfaces? Does
Enumeration have benefits over using Iterator? If anyone could elaborate, a reference article would be appreciated.
The bottom line is, both
Iterators are fail-fast . i.e. when one thread changes the collection by add / remove operations , while another thread is traversing it through an Iterator using
Enumeration and Iterator will give successive elements, but Iterator is improved in such a way so the method names are shorter, and has an additional remove method. Here is a side-by-side comparison: Enumeration Iterator
---------------- ----------------
hasMoreElement() hasNext()
nextElement() next()
N/A remove()
As also mentioned in the Java API Specifications, for newer programs, Iterator should be preferred over Enumeration, as "Iterator takes the place of Enumeration in the Java collections framework." (From the Iterator specifications.)Iterators are fail-fast . i.e. when one thread changes the collection by add / remove operations , while another thread is traversing it through an Iterator using
hasNext() or next() method, the iterator fails quickly by throwing ConcurrentModificationException . The fail-fast behavior of iterators can be used only to detect bugs. The Enumerations returned by the methods of classes like Hashtable, Vector are not fail-fast that is achieved by synchronizing the block of code inside the nextElement() method that locks the current Vector object which costs lots of time.What is the difference between an ArrayList and a LinkedList ?
| Arraylist | Linklist |
| Random access. | Sequential access.The control traverses from the first node to reach the indexed node. |
| Only objects can be added. | The LinkedList is implemented using nodes linked to each other. Each node contains a previous node link, next node link, and value, which contains the actual data |
What are FileReader and FileWriter ? here are examples
FileReader and FileWriter read and write charactors not bytes
its for text
new file
new file writer
write rite rite
flush (ensures on disk not in memory)
close
reader can asynch read files
writer creates file if not in existence
an example
Usage of FileWriter can be explained as follows :
Usage of FileWriter and FileReader used in conjunction is as follows:
its for text
new file
new file writer
write rite rite
flush (ensures on disk not in memory)
close
reader can asynch read files
writer creates file if not in existence
an example
Usage of FileWriter can be explained as follows :
File file = new File("fileWrite2.txt");
FileWriter fw = new FileWriter(file);
for(int i=0;i<10;i++){
fw.write("Soham is Just Awesome : "+i);
fw.flush();
}
fw.close();
|
int c;
FileReader fread = new FileReader("xanadu.txt");
FileWriter fwrite = new FileWriter("characteroutput.txt");
while ((c = fread.read()) != -1)
fwrite.write(c);
|
What are FileInputStream and FileOutputStream
FileInputStream : It contains the input byte from a file and implements an input stream.
FileOutputStream : It uses for writing data to a file and also implements an output stream.
FileInputStream, FileOutputStream
byte[] bucket = new Byte[16];
x = is.read(bucket);
os.write(bucket, 0, x);
close close
FileOutputStream : It uses for writing data to a file and also implements an output stream.
FileInputStream, FileOutputStream
byte[] bucket = new Byte[16];
x = is.read(bucket);
os.write(bucket, 0, x);
close close
public class FileHandling {
public static void main(String [ ] args) throws IOException
{
FileInputStream inputStream = new FileInputStream ("Input.txt") ;
FileOutputStream outputStream = new FileOutputStream("Output.txt",true) ;
byte[] buffer = new byte[1024];
//For larger files we specify a buffer size which defines the chunks size for data
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1)
outputStream.write(buffer, 0, bytesRead);
inputStream.close() ;
outputStream.close() ;
}
}
|
Difference between byte stream and Character streams?
dealing with File Operations.
used
To generate User reports, send attachments through mails and spill out data files from Java programs. And a sound knowledge on File Operation becomes even more important while dealing with Java questions.
byte stream : For reading and writing binary data, byte stream is incorporated. Programs use byte streams to perform byte input and output.
used
To generate User reports, send attachments through mails and spill out data files from Java programs. And a sound knowledge on File Operation becomes even more important while dealing with Java questions.
byte stream : For reading and writing binary data, byte stream is incorporated. Programs use byte streams to perform byte input and output.
- Performing InputStream operations or OutputStream operations means generally having a loop that reads the input stream and writes the output stream one byte at a time.
- You can use buffered I/O streams for an overhead reduction (overhead generated by each such request often triggers disk access, network activity, or some other operation that is relatively expensive).
the difference between Throw and Throws in Java Exception Handling
at some point in the method /code tree you can handle a situation by throwing an exception
eg throw new MyFancyExceptionforThisSituationIwantToHandleProperly
up the tree i will catch it with a catch (MyFancyExceptionforThisSituationIwantToHandleProperly e)
and then handle it.
so you can make one enclosing struct to deal with multiple exceptions
like an if but call try catch catch catch catch
i guess they (java deigners, who are devs, who are nerds, who have egos) needed to name it something different to be cool...
What is Java Exception Handling? What is the difference between Errors, Unchecked Exception and Checked Exception?
- An Unchecked Exception inherits from RuntimeException (which extends from Exception). The JVM treats RuntimeException differently as there is no requirement for the application-code to deal with them explicitly.
- A Checked Exception inherits from the Exception-class. The client code has to handle the checked exceptions either in a try-catch clause or has to be thrown for the Super class to catch the same. A Checked Exception thrown by a lower class (sub-class) enforces a contract on the invoking class (super-class) to catch or throw it.
- Errors (members of the Error family) are usually thrown for more serious problems, such as OutOfMemoryError (OOM), that may not be so easy to handle.
Throwable has two sub class routes, Error and Exception
Error is thown and no checked - eg for out of mem errors - unhandled unexpected exceptions
Exception has two defined subclass logics
unchecked exceptions - you dont have to handle this in the code - jvm treats it different
checl exeptions need to be handled by try eventuallyand can be thrown up the calling method stack chain- eg defined int he method signature as throws
What is Constructors, Constructor Overloading in Java and Copy-Constructor?
java has defualt no arument constructors
WRONG if you make one with parameters you also need to write a no arg default const (no you dont - tested) thanks random internet blog for incorrect info..!!
can be public, private or protected
called once to instantiate
same name as class
no return value and dont need void
dont have to write one as java creates a default one
just use new Classname();
Copy Constructor: A copy constructor is a type of constructor which constructs the object of the class from another object of the same class. The copy constructor accepts a reference to its own class as a parameter.
WRONG if you make one with parameters you also need to write a no arg default const (no you dont - tested) thanks random internet blog for incorrect info..!!
can be public, private or protected
called once to instantiate
same name as class
no return value and dont need void
dont have to write one as java creates a default one
just use new Classname();
Copy Constructor: A copy constructor is a type of constructor which constructs the object of the class from another object of the same class. The copy constructor accepts a reference to its own class as a parameter.
Java - overriding
overriding supports polyorphism
Define overriding. Explain it with an example
Overriding is done in a child class for a method that is written in the parent class. To override a method a new method is defined in the child class with exactly the same signature as the one in the parent class. Due to this the functionality of the parent class becomes inaccessibleJava - overloading
Over-Loading: define multiple methods with the same name, but with different parameters.
Functions in Java could be overloaded by two mechanisms :
Functions in Java could be overloaded by two mechanisms :
- Varying the number of arguments.
- Varying the Data Type.
also defined as different method signatures
can make code hard to read
overloading does not fully support polymorphism
overriding does though as its one type with different behaviors roughly
overriding does though as its one type with different behaviors roughly
What is Function Over-Riding and Over-Loading in Java?
Snippet below should explain things better.
public class Car {
public static void main (String [] args) {
Car a = new Car();
Car b = new Ferrari(); //Car ref, but a Ferrari object
a.start(); // Runs the Car version of start()
b.start(); // Runs the Ferrari version of start()
}
}
class Car {
public void start() {
System.out.println("This is a Generic start to any Car");
}
}
class Ferrari extends Car {
public void start() {
System.out.println("Lets start the Ferrari and go out for a cool Party.");
}
}
|
Saturday, June 14, 2014
Why is String is Immutable in Java ?
the answer depends on good understanding of memory, synchronization, data structures,
every manip u do to a java String object will return a COPY of that manipulated String.
this is so anything pointing (pointers/ref) to a string in memory will still have the same String there.
your NEW variable will have a new string but it will be at another address in the heap.
String pool (String intern pool) is a special storage area in Java heap. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.
The following code will create only one string object in the heap.
Here is how it looks:

If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.
2. Allow String to Cache its Hashcode
The hashcode of string is frequently used in Java. For example, in a HashMap. Being immutable guarantees that hashcode will always the same, so that it can be cashed without worrying the changes.That means, there is no need to calculate hashcode every time it is used. This is more efficient.
3. Security
String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to serious security threat. The method thought it was connecting to one machine, but was not. Mutable strings could cause security problem in Reflection too, as the parameters are strings.
4. collection safety. maps don't support mutations of keys, and strings are the most popular object to use as a key
5. defensiveness, you don't have to worry about a method you are calling changing the string out from under you
6. performance, there is an additional level of indirection needed to support sharing strings across some mutations (like growing the string)
7. thread safety/performance. the easiest way to guarantee safety and to cut down on use of synchronized blocks is to make your data immutable.
every manip u do to a java String object will return a COPY of that manipulated String.
this is so anything pointing (pointers/ref) to a string in memory will still have the same String there.
your NEW variable will have a new string but it will be at another address in the heap.
String pool (String intern pool) is a special storage area in Java heap. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.
The following code will create only one string object in the heap.
1.String string1 = "abcd";2.String string2 = "abcd";Here is how it looks:
If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.
2. Allow String to Cache its Hashcode
The hashcode of string is frequently used in Java. For example, in a HashMap. Being immutable guarantees that hashcode will always the same, so that it can be cashed without worrying the changes.That means, there is no need to calculate hashcode every time it is used. This is more efficient.
3. Security
String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to serious security threat. The method thought it was connecting to one machine, but was not. Mutable strings could cause security problem in Reflection too, as the parameters are strings.
4. collection safety. maps don't support mutations of keys, and strings are the most popular object to use as a key
5. defensiveness, you don't have to worry about a method you are calling changing the string out from under you
6. performance, there is an additional level of indirection needed to support sharing strings across some mutations (like growing the string)
7. thread safety/performance. the easiest way to guarantee safety and to cut down on use of synchronized blocks is to make your data immutable.
the stupid old java question What is the difference between STRINGBUFFER and STRING?
Really who cares!
Well people who are concerned about performance - eg high message throughput - low latency trading apps.
we need to talk about immutable
Strings are immutabool !
using Strings fields creates a performance hit. although the compiler will remove this for you and replace it with StringBuffer if it can.
its still faster to use StringBuffer - i have tested - well my colleague did it to prove me wrong in an argument.
StringBuffer/StringBuilder objects are mutable: StringBuffer/StringBuilder objects are mutable; we can make changes to the value stored in the object. What this effectively means is that string operations such as append would be more efficient if performed using StringBuffer/StringBuilder objects than String objects.
The Output of the code snippet would be: Be Happy With Your Salary. Because Increments are a myth.
SO TRUE!
Well people who are concerned about performance - eg high message throughput - low latency trading apps.
we need to talk about immutable
Strings are immutabool !
using Strings fields creates a performance hit. although the compiler will remove this for you and replace it with StringBuffer if it can.
its still faster to use StringBuffer - i have tested - well my colleague did it to prove me wrong in an argument.
StringBuffer/StringBuilder objects are mutable: StringBuffer/StringBuilder objects are mutable; we can make changes to the value stored in the object. What this effectively means is that string operations such as append would be more efficient if performed using StringBuffer/StringBuilder objects than String objects.
String str = “Be Happy With Your Salary.'' str += “Because Increments are a myth"; StringBuffer strbuf = new StringBuffer(); strbuf.append(str); System.out.println(strbuf); |
The Output of the code snippet would be: Be Happy With Your Salary. Because Increments are a myth.
SO TRUE!
Java - autoboxing and unboxing - my interview notes
this is conversion from primitive types to the java wrapper classes made to elegantly handle the primitive data types
e.g.
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.
e.g. converting an int to an Integer, a double to a Double, and so on.
If the conversion goes the other way, this is called unboxing.
Here is the simplest example of autoboxing:
The Java compiler applies autoboxing when a primitive value is:
e.g.
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.
e.g. converting an int to an Integer, a double to a Double, and so on.
If the conversion goes the other way, this is called unboxing.
Here is the simplest example of autoboxing:
Character ch = 'a';
The Java compiler applies autoboxing when a primitive value is:
- Passed as a parameter to a method that expects an object of the corresponding wrapper class.
- Assigned to a variable of the corresponding wrapper cla
Converting an object of a wrapper type (Integer) to its corresponding primitive (int) value is called unboxing. The Java compiler applies unboxing when an object of a wrapper class is:
- Passed as a parameter to a method that expects a value of the corresponding primitive type.
- Assigned to a variable of the corresponding primitive type.
Here is the table as declared by oracle
| Primitive type | Wrapper class |
|---|---|
| boolean | Boolean |
| byte | Byte |
| char | Character |
| float | Float |
| int | Integer |
| long | Long |
| short | Short |
| double | Double |
Subscribe to:
Posts (Atom)
