Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Sunday, February 16, 2014

Sorting Collections

Sorting of Java Objects in Collections is done in two ways.They are:

1)Implementing Comparable interface :

           Comparable Interface in java is used to define the natural sort order of a class.It is defined in lang package.Comparable interface provides one method "compareTo()" to implement in any class so that two instances of that class can be compared. compareTo() method compares the two object of the same type and returns a numerical result based on  the comparison.

In a Student list if we need to sort the list, based on the student roll no, its best  way to implement with Comparable interface.

Example :

public class Student implements Comparable {
private int rollNo;
private String firstName;
private String lastName;
// getter and setter for the properties
@Override
public int compareTo(Student s) {
return this.rollNo- s.rollNo;
}
}

Usage:
   List studentList=new ArrayList();
     //add student objects to studentList 
       Collections.sort(studentList);



2)Implementing Comparator interface :

          Comparator interface is used to order the objects of user-defined class.It is defined in util package.it provides multiple sorting sequence i.e. you can sort the elements based on any data member. Comparators can also be used to control the order of certain structures(such as TreeSet or TreeMap). For instance it may be rollno, name, age or anything else.             

This method is more like generics type if you have to sort with more option.
1) sort based on the firstNamne
2) sort based on the lastName

Example :

Sorting student collection by firstName.

public class FirstNameSorter implements Comparator{
@Override
public int compare(Student s1, Student s2) {
return s1.getFirstName().compareTo(s2.getFirstName());
}


Usage:
List studentList=new ArrayList();
     //add student objects to studentList 
       Collections.sort(studentList, new FirstNameSorter());


Sorting student collection by lastName.

public class LastNameSorter implements Comparator{
@Override
public int compare(Student s1, Student s2) {
return s1.getLastName().compareTo(s2.getLastName());
}
}

Usage:
     List studentList=new ArrayList();
     //add student objects to studentList 
    Collections.sort(studentList, new LastNameSorter());






Wednesday, September 11, 2013

JodaTime

Free, open-source Java library for working with dates and times

Supported Concepts
Instant
 “An instant in the datetime continuum specified as a number of milliseconds from 1970-01-01T00:00Z”
  Within Joda-Time an instant is represented by the ReadableInstant interface.
  There are four implementations of the interface provided.

 Instant - A simple immutable implementation which is restricted to the UTC time zone and is intended for   time zone and calendar neutral data transfer
 DateTime - The most commonly used class in the library, and an immutable representation of a date and time with calendar and time zone
 DateMidnight - Similar to DateTime and also immutable but with the time component forced to be midnight (at the start of a day)
 MutableDateTime - A mutable representation of date and time with calendar and time zone.

Partial
 a partial date/time representation (subset of fields) with no time zone
Interval
 “an interval of time from one millisecond instant to another”
Duration
 “a duration of time measured in milliseconds”
Period
 “a period of time defined in terms of fields, for example, 3 years 5 months 2 days and 7 hours”
Chronology “a pluggable calendar system

Tuesday, February 22, 2011

Coding Convention in Java


1. Proper Names
  • Should give correct spellings
  • All meaningful names should have to give. Method should have to do same or more what they say..
  • Try to Avoid abbreviations.
  • Don't give java keywords as variable and method names
  • Package name should be lower case.
  • Ex: com.challa.action

Thursday, February 10, 2011

Multithreading in Java

Multithreading in Java

Some times we do multple tasks at a particular period of time to complete the unit of work ASAP.
For example: If your working on one issue in the middle you came to know that this issue is dependent on DB. You need help from
DB guy if DB guy is not available at this point of time, you will not keep waiting for him. you will switch to some other task to work on.
ones he come back you can finish the task which is dependent on DB.

Java also perform muti tasking using Multithreading, so that it will improve the performance of the appilication.

We can see how to implement multithreading in java.

In Java We have two types of multi tasking.
1. Thread based multi tasking.
2. Process based multi tasking.

Processed based multi threading:
The best way to remeber is Multiple programs running at a time
ex: adding and subtracting.

Thread based multi tasking.

Multiple tasks in one program.
if we take one example adding numbers 1+2+3+4=9

if one thread is processing this program if we assume for each operation it is taking 1ms it will take 3ms to add this .
if we perform multithreading first two numbers will add by one thread and the last two numbers will add thread this task will in 1 sec by using multi threading
the result of two threads can added in another secong we can complete this in two seconds, so we are able to save 33% of the time.


Java run time environment manages threads, Threads are processed asynchrously this means that one thread can wait while other thread can continue process.
A thread can be in one of four states:
• Running A thread is being executed.
• Suspended Execution is paused and can be resumed where it left off.
• Blocked A resource cannot be accessed because it is being used by
another thread.
• Terminated Execution is stopped and cannot be resumed.

Thread Priority: In a mutlithreaded programing few threads can be dependent on the result of anthor thread so by giving the priority
we can decide which thread have to excute first.





We can see how to implement multithreading in java.

Creating Thread
Multiple Threads in a Program
Synchronization Concept
Thread Communication

Saturday, February 21, 2009

Interface

We use interface to achieve polymorphism. In simple english, the users of your class will have a reference of the interface rather than the class which actually implement that method. This is an object oriented principle that enforce 'keeping the concerns separate' and 'program to super class/interface rather than sub class'. For example: assuming Calculator is an interface, the users of your controller are allowed to call getCalculator to get it. Now, for users, the point of contact is 'Calculator', they shouldn't be interested which class actually implemented the Calculator interface to provide the logic.
public Calculator getCalculator() {
return new BasicCalculator();
}
In future version, you can change the logic, and your users will not be bothered, for example, in an overridden method:
public Calculator getCalculator()
{return new EnhancedCalculator();}
Take an example of T.V, you will see that the remote control is the Interface to your T.V functions. If some Functions are subjected to change/enhanced there should be no effect on the interface/remote control in this example.
Plus if you don't want to expose your logic to some one, (means you don't some one to share your code) you can give him you interface, a standard way to use your logic.

"Interface is like defining some protocol.
When you start building some module or package you must code it into some proper manner so if someone else wants to update or work on it, its working is clear for them. Means it should be generic code. So instead of starting whole thing into single class, you thing about some generic methods, constants your module needed, without thinking of its implementation. So here comes the concept of Interface and Abstract Classes.
When you start implementing method define in Interface you start working with classes which implementing your interface. "

Tricky Questions

1)Can I get Session object from servlet or jsp to simple java class?
2)What is a singleton class?
3)What is the difference between sendRedirect and forward in servlet ?
4)What happened if i clone a singleton object?
5)What is the difference between PrintWriter and JspWriter class?
6)Can I call a static variable with object?
7)What are the collection framework hibernate supports?
8)How to get variable value from javascript in to jsp page?
9)What is the difference between pageContext and SevletContext?
10)Why java doesnot support multiple inheritance?
11) Can we use a ResultSet object after closing the Connection??
Actually not, but you can use RowSet in connectionless mode
12) By default java will import java.lang
println() is the method of class PrintStream and in the package java.io.*
Why how we are able to use println() without importing java.io.*
we dont use println() directly :P , instead we use System.out.println() where out is a final static member of type PrintStream in System class, and System class imports java.io.* for us so we need not bother to import java.io package.
11) Explain Memory leak in java ?
12) Write a program of Dead Lock condition in java .
13) What is the difference between sleep(1000) and wait(1000) ?
15) What is delegation in Java?

Friday, February 20, 2009

Marker Interface and Reflection Mechanism

Marker Interface
The marker interface is just an empty interface. Its purpose is to "mark". That is, a class is suppose to contain certain capability so it "marks" itself with a marker interface -- for example a class capable of cloning itself marks itself with 'Cloneable' interface. Its just a way of Object Oriented Programming. A certain framework (for example RMI) will only deal with classes which are "mark" with their required interfaces (for example Remote).
Reflection Mechanism
Reflection enables Java code to discover information about the fields, methods and constructors of loaded classes, and to use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions. The API accommodates applications that need access to either the public members of a target object (based on its runtime class) or the members declared by a given class.
Ex.
import java.lang.reflect.*;
class B
{
private int val=10;
}
class A
{
public static void main(String[] args) throws Exception
{
B bob=new B();
Field fld=bob.getClass().getDeclaredField("val");fld.setAccessible(true);
System.out.println("value:"+fld.getInt(bob));}}

Tuesday, February 10, 2009

What is scoped memory and why java uses it?

In java, a frequent occurence of a common phenomenon related to memory management is creation and destruction of temporary objects. What are java temporary objects? For example in java, when two strings are concatenated, a StringBuffer object is created. As two Java String objects cannot be added directly (immutable property), a helper object StringBuffer is used to construct a resultant java String object. This StringBuffer object is a temporary object, which is of no direct interest to the programmer. Most of the programming constructs are built in this type of model. Result of it is there are lot of garbage left behind.
Now the question is, what happens to the temporary java object and such garbage after the intended operation completes? Will it be saved for the life time of the program, or JVM (java virtual machine) or what is the underlying policy to destroy it? In automatic memory management the hassles of allocating and deallocating memory is no more a part of programmer’s job in java. But the downside of it is you never know, when an object will be freed. The java garbage collector (GC) doesnot provide any defined time boundaries.
This is where the java scoped memory concept comes into picture. Scoped memory concept is declaring to the JVM that, I am going to use this much amount of memory and those can be freed after this period. That is defining a boundary and bringing predictability. This predictability is needed the most for real time programming. Where you need to be certain about the cycles, time and cost of the operation.
In java scoped memory, the memory is preallocated for the task. This will ensure that the program will not get struck in the mid of operation because of memory resource shortage and constraints. Memory is deallocated and freed when the associated task gets completed. Therefore the recycling process of the memory is fast. But, all the objects related to that task and comes under that designated scope will disappear. If some objects are needed for future reference then that particular object needs to be associated to a different memory mechanism.
This is one of the latest feature in java adding power to the real-time java implementation. For more detail look into the Sun Java Real-Time System (Java RTS). It is Sun’s commercial implementation of the Real-Time Specification for Java (JSR-001).

Friday, February 6, 2009

Serialization

Serialization is used to persist the state of an object into any permanent storage device (or) serialization is the technique of transporting objects over a data stream. It involves serializing of the object's state i.e. packing the data state of the object into bytes and then sending them over a stream to a reciever.
To make a class or a bean serializable we hv to implement either the java.io.Serializable interface, or the java.io.Externalizable interface. As long as one class in a class's inheritance hierarchy implements Serializable or Externalizable, that class is serializable.
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).

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).THE ROLE OF SERIALIZATION IN EJB-------->A big part of EJB is that it is a framework for underlying RMI: remote method invocation. You’re invoking methods remotely from JVM space ‘A’ on objects which are in JVM space ‘B’ – possibly running on another machine on the network. To make this happen, all arguments of each method call must have their current state plucked out of JVM ‘A’ memory, flattened into a byte stream which can be sent over a TCP/IP network connection, and then deserialized for reincarnation on the other end in JVM ‘B’ where the actual method call takes place. If the method has a return value, it is serialized up for streaming back to JVM A. Thus the requirement that all EJB methods arguments and return values must be serializable. The easiest way to do this is to make sure all your classes implement java.io.Serializable.

http://en.wikipedia.org/wiki/Serialization

Monday, January 26, 2009

Features of Java

Here we list the basic features that make Java a powerful and popular programming language:
  • Platform Independence
    • The Write-Once-Run-Anywhere ideal has not been achieved (tuning for different platforms usually required), but closer than with other languages.

  • Object Oriented
    • Object oriented throughout - no coding outside of class definitions, including main().
    • An extensive class library available in the core language packages.

  • Compiler/Interpreter Combo
    • Code is compiled to bytecodes that are interpreted by a Java virtual machines (JVM) .
    • This provides portability to any machine for which a virtual machine has been written.
    • The two steps of compilation and interpretation allow for extensive code checking and improved security.

  • Robust
    • Exception handling built-in, strong type checking (that is, all data must be declared an explicit type), local variables must be initialized.

  • Several dangerous features of C & C++ eliminated:
    • No memory pointers
    • No preprocessor
    • Array index limit checking

  • Automatic Memory Management
    • Automatic garbage collection - memory management handled by JVM.

  • Security
    • No memory pointers
    • Programs runs inside the virtual machine sandbox.
    • Array index limit checking
    • Code pathologies reduced by
      • bytecode verifier - checks classes after loading
      • class loader - confines objects to unique namespaces. Prevents loading a hacked "java.lang.SecurityManager" class, for example.
      • security manager - determines what resources a class can access such as reading and writing to the local disk.

  • Dynamic Binding
    • The linking of data and methods to where they are located, is done at run-time.
    • New classes can be loaded while a program is running. Linking is done on the fly.
    • Even if libraries are recompiled, there is no need to recompile code that uses classes in those libraries.

      This differs from C++, which uses static binding. This can result in fragile classes for cases where linked code is changed and memory pointers then point to the wrong addresses.

  • Good Performance
    • Interpretation of bytecodes slowed performance in early versions, but advanced virtual machines with adaptive and just-in-time compilation and other techniques now typically provide performance up to 50% to 100% the speed of C++ programs.

  • Threading
    • Lightweight processes, called threads, can easily be spun off to perform multiprocessing.
    • Can take advantage of multiprocessors where available
    • Great for multimedia displays.

  • Built-in Networking
    • Java was designed with networking in mind and comes with many classes to develop sophisticated Internet communications.