Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Wednesday, June 14, 2017

Java Interview questions index

Java Interview questions index



1. Java Interview Questions ( Set - 1 )

2. Java Interview Questions ( Set - 2 )

3. Java Interview Questions ( Set - 3 )









Available link for download

Read more »

Tuesday, June 13, 2017

Java 2 Micro Edition Conclusion

Java 2 Micro Edition Conclusion


The Good

J2ME is small, actually very small; writing programs for devices with very limited memory capabilities has been made into a reality by J2ME. J2ME allows the programmer to customize his program to the utmost possibility, right from the configuration he wants to work with to the very profile he is using.

Further, the future versions of the KVM will have the capabilities of integrating the present programs with further memory hungry operations.

The Bad

The very strength of J2ME is its biggest weakness. In order to make the KVM small, a lot of compromises had to be made in the Java language itself. Writing complex programs for J2ME requires higher skill and technique than writing one for computers and servers.

Further because of the configurations and profiles, the basic fundamental principle of portability had to be compromised. That is, a program written for a particular profile is portable with other devices following the same profile.

Future Of J2ME

J2ME is still in its blooming stages, and definitely the platform will be evolving. Many more configurations and profiles will be introduced. Further several technologies, such as Jini (network architecture for distributed systems), will arise with the help of J2ME, improving the capabilities of the mobile devices. Needless to say there will be many more devices following the J2ME technology in future.


Available link for download

Read more »

Wednesday, May 31, 2017

jQuery UI Dialog obtain content from Java Servlet AJAX request

jQuery UI Dialog obtain content from Java Servlet AJAX request



Available link for download

Read more »

Sunday, May 28, 2017

Java Servlet example to generate PDF using iText

Java Servlet example to generate PDF using iText



Available link for download

Read more »

Monday, May 22, 2017

Java Date Calculation example Add and Subtract days

Java Date Calculation example Add and Subtract days



Available link for download

Read more »

Tuesday, May 9, 2017

Java sort an ArrayList of objects

Java sort an ArrayList of objects



Available link for download

Read more »

Friday, May 5, 2017

java calculate percentage from decimal values

java calculate percentage from decimal values


public String getAgegt150Per() {
BigDecimal bd3 = agegt150.divide(this.totalPayment,
RoundingMode.HALF_UP);
Integer val = bd3.multiply(new BigDecimal(100)).intValue();
if (val.intValue() == 0)
return "";
else
return val.toString() + "%";
}

Available link for download

Read more »

Friday, April 28, 2017

Java 2 Micro Edition Virtual Machines

Java 2 Micro Edition Virtual Machines


A virtual machine is the immediate layer overlying the operating system and is mainly responsible for running any program written in Java. This is the main reason that codes written in Java are highly portable. The virtual machine interprets the Java byte-code and converts into native system calls. Further as every program runs in the confinement of the virtual machine, no penetration is possible into the operation system, reducing the risk of viruses.

J2ME offers two different virtual machines, namely CVM (for higher end mobile devices) and KVM (for lower end mobile devices). CVM is used for devices which have higher memory capabilities and which are closer to computers whereas KVM is used for devices which have lower memory capabilities, such as mobile phones. KVM and CVM are primarily nothing but the subset of JVM. They can be thought as just shrunken versions of the JVM and are more specific to J2ME.


Available link for download

Read more »

Tuesday, April 11, 2017

java lang CharSequence

java lang CharSequence




It is the only abstract interface in the java.lang package. It is the basic interface containing non-implemented methods all regarding and involving characters only like length() , charAt() etc and a special method i.e toString() method. It is the super class of many of the classes and interfaces, which are shown below.

Implementation class for the abstract method declared in the in the CharSequence interface are:-

AbstractStringBuilder (c)   of [ java.lang package ]

String (c)                             of [ java.lang package ]

StringBuffer (c)                   of [ java.lang package ]

StringBuilder (c)                 of [ java.lang package ]

CharBuffer (c)                     of [ java.nio package ]

Segment (c)                         of [ javax.swing.text package ]

Note : (c) represent the class. All the above mentioned names are java class.


Methods of the CharSequence interface :

public abstract int length();

public abstract char charAt(int i);

public abstract CharSequence subSequence(int i, int j);

public abstract String toString();


Some of the important points of CharSequence interface :

* It was first introduced with the release of JDK 1.4.
* CharSequence is originally is the sequence of character and which combines to form a String only,
so we can call a string as the CharSequence.


Available link for download

Read more »

Sunday, April 9, 2017

Java 2 Micro Edition Configurations

Java 2 Micro Edition Configurations


Configurations define the basic run-time environment as a set of core classes. They add the classes required for the program to be compatible with the virtual machine.

J2ME has two main configurations – Connected Limited Device Configuration (CLDC) and Connected Device Configuration (CDC). These configurations actually specify the main type of the device, which defines how much memory is available for the operations to be performed.

CLDC requires less memory whereas CDC requires at least 2MB of memory to perform its computations. The CLDC configuration consists of classes and a set of libraries more specific to the mobile devices. The CDC configuration is basically a stripped down version of J2SE with the CLDC classes added to this.

The CLDC configuration is supported by KVM and the CDC configuration is supported by CVM. Configurations decide whether optional features such as multi dimensional arrays, threads, JNI and others have to be included or not.

CLDC configuration is used when the memory available is low, such as the case of PDAs and cell phones. CDC configuration is used when the memory available is more than 2MB but less than that available on our computers, such as the case of set-top boxes.


Available link for download

Read more »

Saturday, April 8, 2017

java lang AbstractStringBuilder

java lang AbstractStringBuilder




It is a private class or more specifically we can say its a private - package class i.e it is declared as not public and as abstract. As it was not there before the release of JDK 1.5 and was first introduced in java 5.0 as the superclass for both StringBuffer and StringBuilder.  Initially before JDK 1.5 there was only one class i.e StringBuffer ( which is thread safe ) and was extending Object class, but later with the release of JDK 1.5 AbstractStringBuilder and StringBuilder was introduced and now StringBuffer is extending AbstractStringBuilder . 

What is private - package class ?
If we declare a non-public class in a package whose scope will be within that package only , in other terms we create any instance of the class outside the package and hence can be considered as private class and called as private-package class. 


Aim behind intoducing AbstractStringBuilder ?
As we knowing that there are two identical class i.e StringBuilder and StringBuffer expects StringBuffer is thread safe and where as StringBuilder is not. Thus all the methods and their implementation are almost identical so instead of writing two times for both the classes they introduce a non-public abstract class i.e AbstractStringBuilder class which has same method with implementation and hence both are classes are using its implementation. 


Interesting facts of AbstractStringBuilder 

If we notice in AbstractStringBuilder class many method returns its own class instance only and its sub-classes i,e StringBuffer and StringBuilder both the classes override the methods of AbstractStringBuilder class and restrict the return type to their own class instance, this narrowing the return type by overiding the method in its sub-class is termed as co-variant return , which is seen with the release of JDK 1.5 and with the later versions.    


Constrcutors of AbstractStringBuilder class

  AbstractStringBuilder()

  AbstractStringBuilder(int i)

Instance variables of AbstractStringBuilder class

1. char[]   value;
2. int        count;
3. static final int[]    sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, 2147483647 };

Methods of AbstractStringBuilder class

  public int length()
  
  public int capacity()

  public void ensureCapacity(int i)

  void expandCapacity(int i)

  public void trimToSize()

  public void setLength(int i)

  public char charAt(int i)

  public int codePointAt(int i)

  public int codePointBefore(int i)

  public int codePointCount(int i, int j)

  public int offsetByCodePoints(int i, int j)

  public void getChars(int i, int j, char[] c, int k)

  public void setCharAt(int i, char c)

  public AbstractStringBuilder append(Object obj)

  public AbstractStringBuilder append(String s)

  public AbstractStringBuilder append(StringBuffer sb)

  public AbstractStringBuilder append(CharSequence cs)

  public AbstractStringBuilder append(CharSequence cs, int i, int j)
  
  public AbstractStringBuilder append(char[] ch)
  
  public AbstractStringBuilder append(char[] ch, int i, int j)

  public AbstractStringBuilder append(boolean b)

  public AbstractStringBuilder append(char c)

  public AbstractStringBuilder append(int i)

  static int stringSizeOfInt(int i)

  public AbstractStringBuilder append(long l)

  static int stringSizeOfLong(long l)

  public AbstractStringBuilder append(float f) 

  public AbstractStringBuilder append(double d)

  public AbstractStringBuilder delete(int i, int j)

  public AbstractStringBuilder appendCodePoint(int i)

  public AbstractStringBuilder deleteCharAt(int i)
  
  public AbstractStringBuilder replace(int i, int j, String s)
  
  public String substring(int i)

  public CharSequence subSequence(int i, int j)

  public String substring(int i, int j)

  public AbstractStringBuilder insert(int i, char[] c, int j, int k)
  
  public AbstractStringBuilder insert(int i, Object o)

  public AbstractStringBuilder insert(int i, String s)

  public AbstractStringBuilder insert(int i, char[] c)

  public AbstractStringBuilder insert(int i, CharSequence cs)

  public AbstractStringBuilder insert(int i, CharSequence cs, int j, int k)

  public AbstractStringBuilder insert(int i, boolean b)

  public AbstractStringBuilder insert(inti, char c)

  public AbstractStringBuilder insert(int i, int j)

  public AbstractStringBuilder insert(int i, long l)

  public AbstractStringBuilder insert(int i, float f)

  public AbstractStringBuilder insert(int i, double d)

  public int indexOf(String s)

  public int indexOf(String s, int i)

  public int lastIndexOf(String s)

  public int lastIndexOf(String s, int i)

  public AbstractStringBuilder reverse()

  public abstract String toString();

  final char[] getValue()


Available link for download

Read more »

java How do you upload a file to an FTP server

java How do you upload a file to an FTP server


import java.io.File;
import java.io.FileNotFoundException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;

public void onUpload()
{
String hostName = "xxxxxxx";
String username = "xxxxxxx";
String password = "xxxxxxx";
String ftpfolder = "outbound";

String fileName ="YourLocalFileName";
String remoteFilePath = "/" + ftpfolder + "/" + fileName;
String localFilePath = "YourLocalFilePath";
File file = new File(localFilePath);
if (!file.exists())
throw new RuntimeException("Error. Local file not found");

StandardFileSystemManager manager = new StandardFileSystemManager();
try {
manager.init();

// Create local file object
FileObject localFile = manager.resolveFile(file.getAbsolutePath());

// Create SFTP options
FileSystemOptions opts = new FileSystemOptions();

// SSH Key checking
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
opts, "no");
// Root directory set to user home
SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts,
false);

// Timeout is count by Milliseconds
SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

// Create remote file object
FileObject remoteFile = manager.resolveFile(
createConnectionString(hostName, username, password,
remoteFilePath), opts);

// Copy local file to sftp server
remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
System.out.println("Done");
} catch (Exception e) {
//Catch and Show the exception
} finally {
manager.close();
win.detach();
}
}


public static String createConnectionString(String hostName,
String username, String password, String remoteFilePath) {
return "sftp://" + username + ":" + password + "@" + hostName + "/"
+ remoteFilePath;
}

Maven artifacts for Apache VFS is a Virtual File System library.


<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-vfs2</artifactId>
<version>2.0</version>
</dependency>


Available link for download

Read more »

Sunday, April 2, 2017

Java Interview Questions

Java Interview Questions



Some of the java Interview Questions for the fresher and Experienced ( Set - 1 )

1. What is Java , speak something about Java ?

Ans: Basically few points has to be remembered regarding java :

a) Java is high level language.
b) Java is Compiled and Interpreted language.
c) Java is a Object-Oriented Language but not a pure Object-Oriented.
d) Java is Platform-Independent Language which makes language as Portable.
........ Click here to see more

If interviewer ask you to speak something about java then without any hesitation ,confidently go on explaining from very basic of java till OOPS concept. Still interview wont let you stop speaking then start explaining threading feature of java. But mostly they will let you cover all the basic things of java and then they start asking their next level of question.
You should speak about following points->
i> What is Java?
ii> OOPS features of Java.
iii> Explain in brief about each Oops features.

2. Is Java Platform Independent ? If yes then justify your answer ?

Ans: Yes , java is platform independent. As we know that java is compiled + interpreted language and .class file is the result of compilation and this file is going to be interpreted by JVM so we need JVM to execute this .class file and thus JVM has to be present and designed for each operating System like Windows , Unix etc.So due to the portability to .class file from a machine to another machine makes java platform independent.


3. What are the command for compiling and executing Java program ?

Ans: javac is a command for compiling java file will result in .class file
        java is a command for executing .class file.

4. What is Classpath in Java ?

Ans: Classpath in java means setting path for the .class files. Classpath is a command in java used for setting path for the .class file. Let suppose we have a .class file in a directory and we are currently at another location, now that .class file which is at different location so can be from another location but we need to set the path for the .class file using classpath command.
like this way, set classpath=......directorylocaltion....;

5. Who is the super class of all the Java classes ?

Ans: Object class is super class all the classes.

6. How many keywords does Java have , name few which you have used in your program?

Ans: Java has 50 keywords. Some of the commonly used keywords are :-

public    private     protected    static    final    new    synchronized    class   int   float   long  
byte       double   default     abstract      interface   for   if     import   package   instanceof  
native     return   super    this   strictfp    switch   throw    throws   try   catch   void   while  
transient   volatile   void    implements    goto      finally   enum   do   continue   const  
break    assert   else   short.
null   true   false  ( These 3 words are Reserved word ).

7. What is "this" in Java and what is its use ?

Ans: Few points about this has to be remembered :

a) At very first this is a keyword in java.
b) this points to the current object.
c) Although this is not a variable so it cannot hold any other reference.
...........Click here to know more

Some of the used of "this" keyword -
a) this is the simplest way to use instead of current object reference.
b) As it always points to the current object , so we can perform any task using this for the current object.

8. What is "super" in Java and for what purpose super is being used in Java programs ?

Ans:  Few points about this has to be remembered :

a) At first super is a keyword in java.
b) super refers to the inherited member from super class to its sub-class.
...........Click here to know more

9. How "this" is different from "super" ?

Ans: Point of differences :

a) this refers to the current object where as super refers to the inherited member of the super class.
b) this() is used for constructor chaining where as super() is used for calling super class default constructor.

10. Is Java is pure-object oriented language and why ?

Ans: No java is not a pure-Objected Oriented Language.
Basically there are two strong reason by which we can conclude and say that java is not a pure- Object Oriented Language, they are-

a) Use of static will not involve any Object creation.
b) Use of primitive type. Although respective Wrapper class is there but still primitive is being used for many purposes.

11. Is Java supporting multiple inheritance and why ?

Ans: No java is not supporting Multiple inheritance directly but approached towards performing multiple inheritance using interfaces. There would lead to some issues if java is supporting multiple inheritance directly :
a) Memory wastage problem
b) Ambiguity Problem in calling methods.

12. Is pointer supported by Java and why?

Ans: Yes Pointer are supported by java but is fully abstract from the developer. It is internally implemented by the java vendor. It is not given at the developer level as because to make java secured. As we know that pointer directly goes to the memory address so there may have chance of security threat if pointer is allowed to implement in java.

13. What is the use of  "native" keyword in Java ?

Ans: native is a keyword in java and are used with the method, which says, that method is implemented using some low level language. So if we have to implement something in low level language then we can use the native keyword.

14. What is Constructor ?

Ans: Constructor is like a method but with no return type. Constructor has same name as the class name. It is used to initialize the  instance variable.
..........Click here to know more

15. What is the purpose of making main() as static ? 

Ans: Purpose of main() as static:
a) So that JVM need not to create any object to call main().
.............Clicl here to know more

16. Does Constructor return any value ? 

Ans: As constructor doesnt have any return type so it cannot return any value, bt we can write return in the constructor as writing return simply means returning the control to the caller.

17. What if we write simply "return" statement in constructor?

Ans: Nothing will happen it will simply return the control to the caller.

18. How may types of initialization blocks in java ?

Ans: There are two types of initialization block:
1. Static initialization block
2. Instance initialization block.

19. What is the use of introducing static initializing block in java ?

Ans: Static initialization block can be used for following purposes:

a) It can be used to initialize the final static variable.
b) It can be used to execute some other method before the main() method.
...............Click here to know more

20. What is the use and purpose of instance initialization block in java ?

Ans: Static initialization block can be used for following purposes:

a) It can be used to initialize the final instance variable.












Available link for download

Read more »

Wednesday, March 22, 2017

Java SFTP Apache commons file download upload and delete example

Java SFTP Apache commons file download upload and delete example



Available link for download

Read more »

Java and Lombok

Java and Lombok


If you are an Indonesian, its pretty easy to make a connection between Java and Lombok. However, this post is not about that Java and Lombok, but rather for the Java programming language and Project Lombok.

One of the drawback of Java language is its verbosity. One very easy example can be found in any typical Java POJO.

public class Order{

private long id;
private String name;
private int size;

public Order(){
}

public Order(long id){
this.id = id;
}

public long getId(){
return id;
}

public void setId(long id){
this.id = id;
}

public String getName(){
return name;
}

public void setName(String name){
this.name = name;
}

public int getSize(){
return size();
}

public void setSize(int size){
this.size = size;
}

@Override
public String toString(){
return String.format("%s %d %d", id, name, size);
}
}
Already that much code just for a very simple structure with constructors, getters, setters, and toString method. This is where Lombok comes to save the day! Instead of writing that much code, you can have something like this:

@Data
public class Order{

private long id;
private String name;
private int size;
}
...and thats it! A clean, nice code that is easy to maintain. The @Data annotation will tell Lombok to generate the constructor, getters and setters, toString method (and even equals and hashCode method!) all during compilation time! (instead of hiding the code in other file ala AspectJ). Since Lombok can be integrated with your IDE, you will not lose the nice content assist or any other feature that you currently enjoying.

There are several other features provided by Lombok (see: Lombok features), although personally for me, this one is going to be the one I use the most. I am not too scared of introducing Lombok dependency to my project since Lombok itself presented a nice way to stop using Lombok dependency with a tool called "delombok". By using delombok, all magically generated code will be written to the source code and the dependency to Lombok library will be removed.

The only drawback I can think of is whenever I rename one of the field name and the rest of code which refer to the getter/setter will also need to be updated manually (instead of having them automatically updated using a refactor tool in your IDE), but it is a very small price to pay (I guess).

Available link for download

Read more »

Monday, March 20, 2017

Java Examples

Java Examples


How to get Current Date and Time and store in the bean
Calculate Percentage from two decimal values
How do you upload a file to an FTP server?
Jsch example to copy file to SFTP Server
 

Available link for download

Read more »

Friday, March 3, 2017

Java calculate difference between two dates

Java calculate difference between two dates



Available link for download

Read more »

Saturday, February 25, 2017

Java lang Appendable

Java lang Appendable



It is a public abstract interface. Many classes and interfaces are extending this abstract interface for different purposes.


SuperClass of Appendable:-

From java.lang package -

StringBuffer

StringBuilder

From java.io package -

BufferedWriter

CharArrayWriter

FileWriter

FilterWriter

OutputStreamWriter

PipedWriter

PrintStream

PrintWriter

StringWriter

Writer

From java.nio package - 

CharBuffer

From java.rmi.server package -

LogStream

All the above classes and interfaces are designed for different purposes and used all abstract method defined in the AbstractStringBuilder class for their own way of implementing the code by overriding these four methods.  


Methods of AbstractStringBuilder class


public abstract Appendable append(CharSequence cs) throws IOException;

public abstract Appendable append(CharSequence cs, int i, int j)  throws IOException;

public abstract Appendable append(char cs) throws IOException;




Available link for download

Read more »

Sunday, February 12, 2017

jQuery getJSON example using Java Servlet

jQuery getJSON example using Java Servlet



Available link for download

Read more »

Friday, February 10, 2017

Java 2 Micro Edition Profiles

Java 2 Micro Edition Profiles


A Profile primarily defines the type of device supported. Profiles are built on top of configurations, since they are specific to the memory available. They add an additional layer on the top of the configuration layer providing APIs for a specific class of devices.

Profiles are specific to the configurations selected. For different configurations, different profiles are available.

CDC Configuration

For CDC configuration, a foundation profile is available, which is primarily a skeleton profile over which we can create our own profile.

CLDC Configuration - MIDP, KJava And Doja

For the CLDC configuration, predefined profiles such as MIDP, KJava and Doja are available. The KJava profile is one of the popular profiles for the Palm OS. It consists of Sun specific APIs. Further its not a standard J2ME profile.

The Doja profile is another popular profile, though not widely used in our mobiles; it is a rapidly growing profile, because of its simple user interface and as it easy to understand. This profile is popularly used in Japan for their local cellular phone companies. However its influence on the entire mobile network is still a long way ahead.

The most popular profile used these days in the Mobile Information Device Profile (MIDP). It is mainly based on the CLDC configuration and is widely used in cellular phones and pagers. Currently there are two versions of MIDP that are available for programming - MIDP 1.0 and MIDP 2.0. Mainly the differences between these two profiles are the fact that the MIDP 2.0 has extended features when compared to MIDP 1.0 such as audio and 2D gaming. On the other hand MIDP 1.0 has greater portability when compared to MIDP 2.0. Many of the cellular phone brands such as Nokia, LG, Samsung, and Motorola use these profiles.


Available link for download

Read more »