Thursday, June 19, 2014

java sets

Sets

  • HashSet – a set implementation based on a HashMap with dummy values (same Object is used for every value). Has the same properties as a HashMap. Due to such implementation, consumes more memory than actually required for this data structure.
  • EnumSet – a set of enum values. Each enum in Java is mapped into an int: one distinct int for each enum value. This allows to use a BitSet-like structure for this collection, where each bit is mapped to a distinct enum value. There are 2 actual implementations – RegularEnumSet backed up by a single long (and capable to store up to 64 enum values, which covers 99.9% use cases) and JumboEnumSet backed by a long[].
  • BitSet – a bit set. You should always keep in mind that you may use a BitSet for representing a dense set of integers (like ids starting from a number known in advance). This class uses a long[] for bit storage.
  • LinkedHashSet – like HashSet, this class is implemented on top of a LinkedHashMap. This is the only set which keeps its elements in the insertion order.
  • TreeSet – like HashSet, this class is based on a TreeMap instance. This is the only sorted set in the single threaded part of the standard JDK. 

design patterns

singleton
object pool - re-use -save on obkect creation
factory

commands
chain of resp
iterator


punlicsh subscribe


gang of four patts - authors fo a book - 23 design patterns

Design Patterns: Elements of Reusable Object-Oriented Software
From WIKI:
Design Patterns: Elements of Reusable Object-Oriented Software is a software engineering book describing recurring solutions to common problems in software design. The book's authors are Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides with a foreword by Grady Booch. The authors are often referred to as the Gang of Four, GoF,or Go4


Creational eg factory
Structural adaptor
berhaviour - iterator, command, chain, observer

Swotting threads in Java

Threads are sometimes called lightweight processes

subclass thread

implement runnable - pass it to a thread object

Thread class has static methods - tools for threading

Sleep  - to millis and nanos -suspends execution

Thread. interupted

Join - if ont thread calls another threads, join - it waits for theat thread to complete before continueing.

Synchronization - overhead

synch on method locks class

suynch on code locks a local object - faster - more complex

need to make it findegrained

  • Reads and writes are atomic for reference variables and for most primitive variables (all types except long and double).
  • Reads and writes are atomic for all variables declared volatile (including long and double variables).
Atomic actions cannot be interleaved, so they can be used without fear of thread interference.

deadlock, starvation, livelock

loops needs waits

More sophisticated locking idioms are supported by the java.util.concurrent.locks package.

private final Lock lock = new ReentrantLock();
The biggest advantage of Lock objects over implicit locks is their ability to 
back out of an attempt to acquire a lock. The tryLock method backs out if the 
lock is not available immediately or before a timeout expires (if specified). 

----

there's a close connection between the task being done by a new thread, as defined by its Runnable object, and the thread itself, as defined by a Thread object. This works well for small applications, but in large-scale applications, it makes sense to separate thread management and creation from the rest of the application. Objects that encapsulate these functions are known as executors

The Executor Interface = 

e.execute(r); - r is a runnable

The ScheduledExecutorService Interface

Trhead pool - specifed number fo threads active, pulling ona queue of tasks/events.
Java 7 has fork/join - work stealing - divides work, waits for result, carries on
recursive task and recursive action
Java 8 uses frosk join on mutiple processors in a "parallelSort" in Arrays Class - leverages concurrency and processors
fork join is use in the lamda framework.
Home Page > Essential Classes > Concurrency

Concurrent Collections

The java.util.concurrent package includes a number of additions to the Java Collections Framework. These are most easily categorized by the collection interfaces provided:
  • BlockingQueue defines a first-in-first-out data structure that blocks or times out when you attempt to add to a full queue, or retrieve from an empty queue.
  • ConcurrentMap is a subinterface of java.util.Map that defines useful atomic operations. These operations remove or replace a key-value pair only if the key is present, or add a key-value pair only if the key is absent. Making these operations atomic helps avoid synchronization. The standard general-purpose implementation of ConcurrentMap is ConcurrentHashMap, which is a concurrent analog of HashMap.
  • ConcurrentNavigableMap is a subinterface of ConcurrentMap that supports approximate matches. The standard general-purpose implementation of ConcurrentNavigableMap is ConcurrentSkipListMap, which is a concurrent analog of TreeMap.
All of these collections help avoid Memory Consistency Errors by defining a happens-before relationship between an operation that adds an object to the collection with subsequent operations that access or remove that object.

Preparing for a FIX protocol interview

Gotta prepare for an interview and need to brush up on the FIX protocol

FIX protocol - Common messages and their types.

FIX protocol - Common fields and their types

35 = order type


FIX protocol - Session level messages

on the header section

34 msgseqnum
52 sending time

56TargetCompID
49SenderCompID

SOA - service orientated architecture

Table 1. Web services and SOA
Enabled by Web servicesTechnology neutralEndpoint platform independence.
StandardizedStandards-based protocols.
ConsumableEnabling automated discovery and usage.
Enabled by SOAReusableUse of Service, not reuse by copying of code/implementation.
AbstractedService is abstracted from the implementation.
PublishedPrecise, published specification functionality of service interface, not implementation.
FormalFormal contract between endpoints places obligations on provider and consumer.
RelevantFunctionality presented at a granularity recognized by the user as a meaningful service.
If the principles summarized in Table 1 are complied with, we get some interesting benefits:

Summary

The goal for a SOA is a world wide mesh of collaborating services, which are published and available for invocation on the Service Bus. Adopting SOA is essential to deliver the business agility and IT flexibility promised by Web Services. These benefits are delivered not by just viewing service architecture from a technology perspective and the adoption of Web Service protocols, but require the creation of a Service Oriented Environment that is based on the following key principals we have articulated in this article;
  • Service is the important concept. Web Services are the set of protocols by which Services can be published, discovered and used in a technology neutral, standard form.
  • SOA is not just an architecture of services seen from a technology perspective, but the policies, practices, and frameworks by which we ensure the right services are provided and consumed.
  • With SOA it is critical to implement processes that ensure that there are at least two different and separate processes—for provider and consumer.
  • Rather than leaving developers to discover individual services and put them into context, the Business Service Bus is instead their starting point that guides them to a coherent set that has been assembled for their domain

Tuesday, June 17, 2014

enerics in a nutshell


meh no time - essetially can get compile time erros and not runtime.

things to study

generics
fix protocol
collections
sets
maps
jdbc

message streaming

gang of four - development patterns

testing

inheritance

@Override helps the compiler check your actually overriding

overriding method cna reurn a subtype

can change the code, can call the super code/

Static.

define an identical signature, and you hide the parent static method


Interfaces - cribnotes for the interview exam

Reference type - you can pass interface around

cool to use in jsf and annotation - jboss will wire your implementation to an interface usign a annotation. Weld baby

Only constants, method sigs, default methods, static ,methods, nested types

interface can be extended by another interface

example from orACLE

Defining an interface is similar to creating a new class:
public interface OperateCar {

   // constant declarations, if any

   // method signatures
   
   // An enum with values RIGHT, LEFT
   int turn(Direction direction,
            double radius,
            double startSpeed,
            double endSpeed);
   int changeLanes(Direction direction,
                   double startSpeed,
                   double endSpeed);
   int signalTurn(Direction direction,
                  boolean signalOn);
   int getRadarFront(double distanceToCar,
                     double speedOfCar);
   int getRadarRear(double distanceToCar,
                    double speedOfCar);
         ......
   // more method signatures
}
Note that the method signatures have no braces and are terminated with a semicolon.


COMMON USAGE
callbacks
events same thing
clone
serialize
Runnable
etc

abstract class in java

declared abstract - mixture of implemented and abstract methods


abstract void dddd(a a,s s,s s,a s);


abstract method means class must be declared abstract

abstact keyword not needed in an interface

abstract is for code sharing

interface is for behaviour describibing to unrelated classes

an example is abstractMap - Collections framework

note abstract calls can implement an interface but you dont have to do the implementation - just the subclass

Java- oo concepts to beat the interview

1) Encapsulation - data hiding, private fields, getters and setters
2) Encapsulation - benifit?  stops other people from breaking code - users of the class. Allows class writes to change the private algos on the data/class and not break other code. (unless we mess the logic/data)


A way to restrict access to an object components

A way to aggregate copmplaex stuff and provide a simple interface to a user of a class/object



Monday, June 16, 2014

Java - GC - garbage collection

Man this is a question always asked at a interview.

everyone reels out the standard - it cant be initiated, the garbage collector gets objects that are not referenced.

Heap - memory allocated to the JVM

-Xmx1024m max size
-Xms512m min size available

the VM tracks live objects. the rest is ok for GC

There are four kinds of GC roots in Java:
  1. Local variables are kept alive by the stack of a thread. This is not a real object virtual reference and thus is not visible. For all intents and purposes, local variables are GC roots.
  2. Active Java threads are always considered live objects and are therefore GC roots. This is especially important for thread local variables.
  3. Static variables are referenced by their classes. This fact makes them de facto GC roots. Classes themselves can be garbage-collected, which would remove all referenced static variables. This is of special importance when we use application servers, OSGi containers or class loaders in general. We will discuss the related problems in the Problem Patterns section.
  4. JNI References are Java objects that the native code has created as part of a JNI call. Objects thus created are treated specially because the JVM does not know if it is being referenced by the native code or not. Such objects represent a very special form of GC root, which we will examine in more detail in the Problem Patterns section below.

jvm runs a mark and  sweep algo

  1. The algorithm traverses all object references, starting with the GC roots, and marks every object found as alive.
  2. All of the heap memory that is not occupied by marked objects is reclaimed. It is simply marked as free, essentially swept free of unused objects.

java algo is impacted by live objects. not dead/free ones - the more live objects the more impact the gc has on the system

GC also does compaction  (packs stuff in heap mem) affects perf

  • Compacting is executed not for every GC cycle, but only once a certain level of fragmentation is reached (e.g., if more than 50% of the free memory is not continuous).
  • One can configure a target fragmentation. Instead of compacting everything, the garbage collector compacts only until a designated percentage of the free memory is available as a continuous block


reduce impact- use concurrent mark and sweep

reduce number of objects if poss


Generation oldies and youngies

new objects are traversed a lot, old objects are moved to the geriatrix divsion and skipped


Copy Garbage collection

two spaces - copy live from one to the other - free the not live area

Oracle hotspot

three areas

Eden, survivor/survivor, tenured (survived multi gc cycles)
things like classes and app code go straight to tenured. not necessary for gc cycle




Sunday, June 15, 2014

The java object - great interview question

Tell me about the Java Object

Well its what everything in java inherits from.

lt's like the super of all objects




  • Method Summary

    Methods 
    Modifier and TypeMethod and Description
    protected Objectclone()
    Creates and returns a copy of this object.
    booleanequals(Object obj)
    Indicates whether some other object is "equal to" this one.
    protected voidfinalize()
    Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
    Class<?>getClass()
    Returns the runtime class of this Object.
    inthashCode()
    Returns a hash code value for the object.
    voidnotify()
    Wakes up a single thread that is waiting on this object's monitor.
    voidnotifyAll()
    Wakes up all threads that are waiting on this object's monitor.
    StringtoString()
    Returns a string representation of the object.
    voidwait()
    Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
    voidwait(long timeout)
    Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
    voidwait(long timeout, int nanos)
    Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

Java initialization -- Static vs code block

Static code block gets called once

code block gets called on each instantiation

simples

non static block actually get copied into the compiler

Java Destructor/Deconstructor/finalizer

you cant make memory leaks in Java unless you are holding references to objects - poor programming
or you use a third partyu library from c++ or something

GC cannot always Keep up.

There is no destructor in Java

you can set an object to null and at some point it will get cleaned up by the GeeCee

If you want to clean up somehting use a a method by coding it - eg close();

Rule of them - dont use - some people say use in buggy situation. Code around it,,

Use Finalize() as a backstop to close an external resource.

its on the Java object class - override it

Objects with finalizers (those that have a non-trivial finalize() method) have significant overhead compared to objects without finalizers, and should be used sparingly. Finalizeable objects are both slower to allocate and slower to collect. At allocation time, the JVM must register any finalizeable objects with the garbage collector, and (at least in the HotSpot JVM implementation) finalizeable objects must follow a slower allocation path than most other objects. Similarly, finalizeable objects are slower to collect, too. It takes at least two garbage collection cycles (in the best case) before a finalizeable object can be reclaimed, and the garbage collector has to do extra work to invoke the finalizer. The result is more time spent allocating and collecting objects and more pressure on the garbage collector, because the memory used by unreachable finalizeable objects is retained longer. Combine that with the fact that finalizers are not guaranteed to run in any predictable timeframe, or even at all, and you can see that there are relatively few situations for which finalization is the right tool to use.

Whats is a Java package?

its a namespace

namspace follow a directory folder structure

holds interfaces and classes

namespaces prevent name clashing


Java studies for interview - default modifier

class sosandso {}

its default

visible / public to the package only

Java top level classes

Good luck to me

Top LEVEL

must be at least one public top level classes

shit i did not know we can have multiple top level classes!! wow, new stuff after a zillion years of java

Top level  - public, abstract, final yeah yeah

not private duh, nor protected nor static


More than one top-level class can be defined in a Java source file, but there can be at most one public top-level class declaration. The file name must match the name of the public class. The file name can be anything, provided there is not a public class definition. If there is more than one class declaration in a source file, each will be compiled into separate .class files. The following example has more than one source file. It must be divided into separate source files that have at most one public class declaration. The compiler will complain if there are two public classes at the same file.

//Inner class examples with
//Class Modifiers   

//A top level class
public
class Point {}

abstract class Point {}
final class Point {}
class Point {}
//Some variations
public final class Point{}
public abstract class Point{}
//Error conditions
public public class Point{}//ERROR!
private class Point{}//ERROR! 
protected class Point{}//ERROR!

AbStRaCt Classes

love the colors!!

An abstract class is a class which may have incomplete implementations for its methods, some of the methods can have implementation and some others can be empty method declarations. If an abstract class is going to be subclassed, all of its incomplete method implementations must be implemented in the subclass, or the subclass must be declared as abstract too; otherwise the compiler will complain.

// An abstract class 
abstract class Shape {
    int x,y; 

    abstract void draw();
    void setX(int _x){ x=_x; }
    void setY(int _y){ y=_y; }
}

you can make abstract classes fromn abstract classes

Interface ezeesez


An interface is the same as an abstract class, but you cannot define any method implementations at all. Abstract classes allow having some method implementations. Method implementations cannot be defined when an interface is concerned. Interfaces are defined with the interface keyword. An interface doesn't need abstract and class keywords. Member variables are implicitly defined as public static final. An abstract class can have a constructor(s), but the constructor(s) must be implemented. An Interface must not have a constructor at all.
public interface class Shape {
  // note that abstract
  // is not used in here
  void draw() ;
}

Java studying for interview - Top level and inner class crib notes


Reference Card

 
Top level nested class
Non static inner class
Local class
Anonymous class
Declaration ContextAs static class memberAs non-static class memberIn block with non-static contextIn block with non-static context
Accessibility ModifiersAllAllNoneNone
Outer instanceNoYesYesYes
Direct Access to enclosing contextStatic members in enclosing contextAll members in enclosing contextAll members in enclosing context + local final variablesAll members in enclosing context + local final variables
Defines static or non-static membersBoth static and non-staticOnly non-staticOnly non-staticOnly non-static
ConstructorsYesYesYesNo
Can use extends or implements clauses?YesYesYesNo

Java Inner classes - local, inner, anonymous

There are three types of inner classes.
  • Member Classes
  • Local Classes
  • Anonymous Classes

Member Classes (Non-static Inner Classes)


  1. A member class can access all the fields and methods (even private) of an enclosing class. 
  2. A member class can be declared as public, protected, private, abstract, final, or static. 
  3. When you declare a member class with a static modifier it will not be an inner class anymore. It will be a top-level nested class.


They are declared within a normal class

class Outer { // Top-level class
   class Inner {// without static modifier 
                // Member or Non-static inner
                // class
   }
}

They must have a INSTANCE of an outer class

Outer.Inner theInner = new Outer().new Inner();//or
Outer
theOuter = new Outer();
Outer.Inner theInner = theOuter.new Inner();


Inner class METHODS cannot be static. 

//First code snippet with a static member.
class Outer1 { // Top-level class
   class Inner1 {// without static modifier 
                // Member or Non-static inner
                // class
                static int x; // ERROR!
   }
}


this is ok

class Outer2 { // Top-level class
   class Inner2 {// without static modifier 
                // Member or Non-static inner
                // class
               int x; // OK!
   }
}

this is also ok

class Outer3 { // Top-level class
   class Inner3 {// without static modifier 
                // Member or Non-static inner class.
                // compile-time constant
               static final int x = 0; // OK!
   }
}

LOCAL Classes  (like a local variable, when accessing local variables they must be final)

Declared in Method, constructor, static initializer or a instance initializer

Can access everything in the enclosing class but only the final vars of the method

enclosing class cannot see it...

can be in a static method but not declared static

e.g.

class Outer { // Top-level class
   void method() { // Method declaration
      class Inner {// Local class 
      }
     }
}

Anonymous Class (why do we have this sturff)

has no name duh anonymous - 
since it has no name there is no contructor - try it... um err

Anonymous classes do not allow the use of extends and implements clauses and access modifiers
but...
they can either extend or implement an interface not both
general form is:
//interface implementation
 new InterfaceName() {}//extends a class
 new ClassName() {} 

The interface name is the name of the interface that is going to be implemented, and the class name is the name of the class that is going to be extended. They are not the name of our newly created class. It is the name of the class that we intend to implement or extend.


Exampool!  example noob

//...
   void initUserInterface() { // Method                                     //declaration
      //... 
      addWindowListener(//Method begins 
                  //class delaration 
                  new WindowAdapter(){  
                         //implemetion for the method 
                      public windowClosing(WindowEvent e)             {  
                              System.exit(0);  
                         }  
                  }  

            );//Method ends 
      //... 
      }
     }
//...








Java interfaces - crib notes

interface - no method implementations - only signatures
cannot instantiate
interface member variables are 
no contructor - its not a class its a behaviour/pact

no such thing as an inner interface - wwwoop

Java class modifiers - examples short and sweet

A top level class

public class Point {}
abstract class Point {}
final class Point {}
class Point {}

Some variations

public final class Point{}
public abstract class Point{}

Error conditions

public public class Point{}//ERROR!
private class Point{}//ERROR! 
protected class Point{}//ERROR!
static class Point{}//ERROR!

Top level class modifiers

Public(anyone can use it), abstract(must be implemented, not instantiable), final (cant be inherited)

top level !






Big O notation - java

Sometimes comes up

Big-Oh (the "O" stands for "order of") notation is concerned with what happens for very large values of N, therefore only the largest term in a polynomial is needed. All smaller terms are dropped.

Lets brush up on this

Big O notation is used in Computer Science to describe the performance or complexity of an algorithm. Big O specifically describes the worst-case scenario, and can be used to describe the execution time required or the space used (e.g. in memory or on disk) by an algorithm.

O(1) describes an algorithm that will always execute in the same time (or space) regardless of the size of the input data set. e.g reading the first element of an array

O(N) describes an algorithm whose performance will grow linearly and in direct proportion to the size of the input data set - e.g. searching for a string in a linked lisst

O(N2) represents an algorithm whose performance is directly proportional to the square of the size of the input data set. This is common with algorithms that involve nested iterations over the data set. eg. comparing strings in a 2d array = 3d array will be O(N3)

O(2N) denotes an algorithm whose growth will double with each additional element in the input data

Logarithm
This type of algorithm is described as O(log N). The iterative halving of data sets described in the binary search example produces a growth curve that peaks at the beginning and slowly flattens out as the size of the data sets increase e.g. an input data set containing 10 items takes one second to complete, a data set containing 100 items takes two seconds, and a data set containing 1000 items will take three seconds. Doubling the size of the input data set has little effect on its growth as after a single iteration of the algorithm the data set will be halved and therefore on a par with an input data set half the size. This makes algorithms like binary search extremely efficient when dealing with large data sets.


cpu or memory resources an algorithm requires - complexity is another term

Here is a table of typical cases, showing how many "operations" would be performed for various values of N. Logarithms to base 2 (as used here) are proportional to logarithms in other base, so this doesn't affect the big-oh formula.
 constantlogarithmiclinear quadraticcubic
nO(1)O(log N)O(N)O(N log N)O(N2) O(N3)
11 1 1 1 1 1
21 1 2 2 4 8
41 2 4 8 16 64
81 3 8 24 64 512
161 4 16 64 256 4,096
1,0241101,02410,2401,048,5761,073,741,824
1,048,5761201,048,57620,971,52010121016


Why big-oh notation isn't always useful (I like this)

Complexity analysis can be very useful, but there are problems with it too.
  • Too hard to analyze. Many algorithms are simply too hard to analyze mathematically.
  • Average case unknown. There may not be sufficient information to know what the most important "average" case really is, therefore analysis is impossible.
  • Unknown constant. Both walking and traveling at the speed of light have a time-as-function-of-distance big-oh complexity of O(N). Altho they have the same big-oh characteristics, one is rather faster than the other. Big-oh analysis only tells you how it grows with the size of the problem, not how efficient it is.

Typical big-oh values for common algorithms

Searching

Here is a table of typical cases.
Type of SearchBig-OhComments
Linear search array/ArrayList/LinkedList O(N)  
Binary search sorted array/ArrayList O(log N) Requires sorted data.
Search balanced treeO(log N)  
Search hash table O(1)  

Other Typical Operations

Algorithmarray
ArrayList
LinkedList
access front O(1)O(1)
access back O(1)O(1)
access middle O(1)O(N)
insert at front O(N) Yeah!O(1)
insert at back O(1)O(1)
insert in middleO(N) or n/2 ? meh
O(1)


intelligent comment

Time-space tradeoffs

Sometimes it's possible to reduce execution time by using more space, or reduce space requirements by using a more time-intensive algorithm.

another way to describe it

Big-O:
  • Describes how the algorithm scales and performs, in terms of either the execution time required or the space used.
  • Is relative representation of complexity. This allows you to reduce an algorithm to a variable which in turn allows you to easily compare it to another.
  • Describes an upper limit on the growth of a function, in the other words the “worst case scenario”.
There is also Big-Omega notation which looks at the lower bound / “best case scenario” stating that the algorithm will take at least X amount of time and Big-Theta which is tight bound to both lower and upper / “average”.

‘SimpleDateFormat’ - use it to display the current system date in ‘yyyy/MM/DD HH:mm:ss’ format?

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));
}
}

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 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 ?





ArraylistLinklist
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 :
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();
Usage of FileWriter and FileReader used in conjunction is as follows:
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

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.
  • 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).
Character streams: Character streams work with the characters rather than the byte. In Java, characters are stored by following the Unicode (allows a unique number for every character) conventions. In such kind of storage, characters become the platform independent, program independent, language independent.

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?

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.


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 inaccessible

Java - overloading

Over-Loading: define multiple methods with the same name, but with different parameters. 

 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

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.

1.String string1 = "abcd";
2.String string2 = "abcd";

Here is how it looks:
java-string-pool
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.

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:
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 typeWrapper class
booleanBoolean
byteByte
charCharacter
floatFloat
intInteger
longLong
shortShort
doubleDouble


What are the Data Types supported by Java?

The eight Primitive Data types supported by Java are:
  • Byte : 8-bit signed two’s complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive)
  • Short : 16-bit signed two’s complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive).
  • Int : 32-bit signed two’s complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive)
  • Long : 64-bit signed two’s complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive)
  • Float
    • If you want to create a float, you should end your number with f (i.e.: 3.6f). 
    • float b= 3.6;
      will give you this error.
      Error:Unresolved compilation problem: 
          Type mismatch: cannot convert from double to float
      

    • float b= 3.6; without the f will mean java thinks its 
    • a double and it will fail
so 3.6 is seen as a decimal and does not convert to float!

  • Double
  • double b= 3.6; will give you a Double no problem

more info about java double and float

double is a 64-bit precision IEEE 754 floating point, while floatis a 32-bit precision IEEE 754 floating point. As a floatis less precise than a double, the conversion cannot be performed implicitly.


Autoboxing: The Java compiler brings about an automatic transformation of primitive type (int, float, double etc.) into their object equivalents or wrapper type (Integer, Float, Double,etc) for the ease of compilation.

Unboxing: The automatic transformation of wrapper types into their primitive equivalent is known as Unboxing.