Showing posts with label Java FAQs. Show all posts
Showing posts with label Java FAQs. Show all posts
Friday, April 18, 2014
Today I am going to take you through the basics of annotation. This feature was introduce in JDK 5. Most of the time while writing programs you may have to provide some meta information along with your codes. In those cases annotations come into picture.
What is an annotation ?
Annotation is a metadata that provides data or information about a program which is not a part of the program itself with no direct effect on the code it annotates.

Uses of annotation

  • Information used by compiler : They can be used which carries special meaning to the compiler and helps in detecting any compile time errors.
  • Deployment-time processing : They can be used by softwares, servers to generate codes, files and also to deploy codes as in case of servlets.
  • Runtime processing : They can be used to carry information during runtime.
Annotations can be applied to declarations : declaration of classes, fields, methods etc. From Java 8, annotations can also be applied to use of types as below
  • Class intance types
  • Type-Cast
  • implements clause
  • throes exception declaration
Depending on the usage of annotation, the retention policy and target of an annotation declared is mentioned.Before we create our own annotaions, these two things must be kept in mind
  • Retention Policy - There is an enum to define named RetentionPolicy. The constants are used to define how long the annotations should be retained. It has three values : SOURCE, CLASS, RUNTIME .
  • Target - This is used to define which part of the program can be annotated with that particular annotation. There is an enum ElementType which has several constants PACKAGE, FIELD, METHOD, LOCAL_VARIABLE etc., to define which part should be targeted.
In our next tutorial we will deal with pre-defined annotations in java.
Thursday, April 17, 2014
Today I am going to deal with the new feature of Java 8 - Lambda Expression. Here we will go through a short introduction on lambda expression and follow up with a simple example to start with it before going into complex ones in our next articles.
Why Lambda Expressions ?
Earlier befor Java 8, when we didn't have this awesome feature we had to use anonymous inner classes. Suppose you are writing a GUI application where you write anony mous class very often to specify what action is to be taken when a button is clicked. But  now we can use lambdas in places of anonymous classes having a single method. Alternatively you can use them for functional interfaces.In those cases normally we try to pass funtionality as function arguments using anonymous classes. But those codes are cumbersome and look very unclear. So Lambda Expressions has been introduced which allows you to pass functionality as arguments with very simple syntax.


What is the syntax of Lambda Expression ?
Suppose you have a functional interfacelike below which takes a string argument and returns void.
interface IDemo{
   public void action(String s);
}
Now your lambda expression syntax in place of anonymous class is
(a) -> System.out.println(s)
Now if you have more than one parameter then give them seperated by commas as (a,b,c) and so on. As in our case we have only one parameter, you can omit the parenthesis.

Here in our sample example we will create a Song class which will have different attrbutes like tile,album etc. There will be a functional interface that takes a Song object and returns a boolean value. Now there will be a method which takes in a Collection of songs and performs a particular action when they satisfy a particular criteria. Now earlier, you woula have to pass the criteria while calling that function as an anonymous class; but with Java 8 we will do it using Lambda Expression.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
package lambda;

import java.util.List;
import java.util.ArrayList;

public class Song {
 //instance variables
 private String title,artist,album;
 private short year,bitrate;
 //constructor to set values
 public Song(String title, String artist, String album, short year, short bitrate) {
  super();
  setTitle(title);
  setArtist(artist);
  setAlbum(album);
  setYear(year);
  setBitrate(bitrate);
 }
  
 public String getTitle() {
  return title;
 }
 public void setTitle(String title) {
  this.title = title;
 }

 public String getArtist() {
  return artist;
 }
 public void setArtist(String artist) {
  this.artist = artist;
 }

 public String getAlbum() {
  return album;
 }
 public void setAlbum(String album) {
  this.album = album;
 }

 public short getYear() {
  return year;
 }
 public void setYear(short year) {
  this.year = year;
 }

 public short getBitrate() {
  return bitrate;
 }
 public void setBitrate(short bitrate) {
  this.bitrate = bitrate;
 }

 @Override
 public String toString() {
  return "Music [title=" + title + ", artist=" + artist + ", album="
    + album + ", year=" + year + ", bitrate=" + bitrate + "]";
 }
 //prints all songs of the list which satisfies the criteria of tester
 public static void printSongs(List<Song> tracks, CheckSong tester){
  for(Song mt : tracks)  //for-each loop
   if(tester.test(mt))  //testing criteria
    System.out.println(mt);  //printing if satisfies
 }
}

//functional interface to check the criteria
interface CheckSong{
        boolean test(Song song);
}
Now earlier you had to mention the criteria by anonymous class like this while calling printSongs() method. Here we are trying to print all songs in list that are released after year 2010.
printSongs(tracks, 
               new CheckSong() {
   @Override
   public boolean test(Song song) {
    return song.getYear() > 2010;
   }
});
But now with lambda expression the whole thing looks much simpler as shown below
printSongs(tracks, mt -> mt.year > 2010);
The main method of the Song class where both approaches are shown
public static void main(String... args){
 List<Song> tracks = new ArrayList<>();
 Song m = new Song("Waka Waka","Shakira","FIFA",(short)2010,(short)320);
 tracks.add(m);
 m = new Song("La La La","Shakira","FIFA",(short)2014,(short)320);
 tracks.add(m);
 System.out.println("With anonymous class");
 printSongs(tracks, 
   new CheckSong() {
    @Override
    public boolean test(Song song) {
     return song.getYear() > 2010;
    }
 });
 System.out.println("With lambda expression");
 printSongs(tracks, mt -> mt.year > 2010); 
}

-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------
Download comlete source from below links which contains Song class with main method where both anonymous class and lambda expressions are used at the same time for better understanding.
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared
Saturday, April 12, 2014
One of the frequent question related to Java is whether Java a pure object oriented language or not is often asked in an interview. The answer is NO. There are many things in Java which are not objects e.g. primitive data types like boolean, int, float etc., different kinds of arithmetic, logical and bitwise operator e.g. +, -. *, /, &&, || etc. Few pure OO languages are Smalltalk and Eiffel. Though Java is one of the most successful Object oriented programming language, which also got some functional programming touch in Java 8 is never considered 100% or pure object-oriented programming language. If it were, all its primitives would be objects. It actually moves half-way in this direction with String and Array, but it doesn't quite go far enough.

There are seven qualities to be satisfied for a programming language to be pure Object Oriented.

  • Encapsulation/Data Hiding
  • Inheritance
  • Polymorphism
  • Abstraction
  • All predefined types are objects
  • All operations are performed by sending messages to objects
  • All user defined types are objects.
Java supports Encapsulation at class and package level, It supports Abstraction, Inheritance and Polymorphism, and all user defined types are also objects. What it doesn't support is #5 and #6.

Why Java is not Pure Object Oriented language? 
Smalltalk is often considered one of the purest Object oriented language and comparing Java with Smalltak will give sufficient reasons, why Java is not pure OO language.
  • Primitive data types are either stored directly in fields or on the stack rather than on the heap.
  • "Primitive types" in Smalltalk are actually "Primitive Classes" and in Smalltalk all "procedures" or "functions" are really messages
Though you can make your program pure object oriented by using Autoboxing, but Java compiler supports primitive data types, so Java cannot be Pure OO unless it makes everything objects.
Monday, March 24, 2014
Today I  will show you "how to save objects to file" and "how to read objects from file". This is a very important thing which you may need while writing an application in Java. You might have an application where you would like to save the state of an object which you may require later. You can think of using databases, but it is very odd to use it for saving small number of objects. Also it may be that you dont have access to databases. So it is best to use the local file systemand save objects in files. This will make the application more light and have freater performance.
     This is very easy to do. Just as you write and read all other things from file, similarly this can be done. You have to do just these two things

  • The class whose object you want to save must  implement the interface java.io.Serializable. This interface is a tagging interface and has no abstract methods. As you knowobjects have existence only in JVM and they have no meaning in the external world. So making a class Serializable is quite like signing a contract with JVM that it can be taken outside it but it will be broken into bytes which will be actually saved in file. Similarly while reading the series of bytes from file will be read and the object will be reconstructed.
  • Wgile writing an object you need a stram to write it. The class java.io.ObjectOutputStream will help to write objects while java.io.ObjectInputStream will help to read objects.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;


public class Student implements Serializable{
 private long roll;
 private String name;
 private static final long serialVersionUID = 1L;
 
 public Student(long roll, String name){
  this.roll = roll;
  this.name = name;
 }

 @Override
 public String toString() {
  return "Student [roll=" + roll + ", name=" + name + "]";
 }
}

class SerializableDemo{
 public static void main(String[] args) throws ClassNotFoundException, IOException {
     //creating instance of Student to save to file
  Student s = new Student(11004L,"Aditya Goyel");
  System.out.println("Before saving in file >>\n"+s);
  //creating the stream to write to file
  ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("out.dat"));
  oos.writeObject(s);  //writing the object
  oos.close();  //closing the stream
  //creating the stream to read from file
  ObjectInputStream ois = new ObjectInputStream(new FileInputStream("out.dat"));
  Object o = ois.readObject();  //reading from file
  if(o instanceof Student)  //checking if it is a Student object
   o = (Student)o;  //type-cast to Student
  System.out.println("\nAfter reading from file >> \n"+o);
  ois.close();  //closing stream
 }
}
-------------------------------------------------------------------------------------------------------------------------
Output
-------------------------------------------------------------------------------------------------------------------------
Before saving in file >>
Student [roll=11004, name=Aditya Goyel]

After reading from file >>
Student [roll=11004, name=Aditya Goyel]

-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------
Sunday, March 23, 2014
This is a very popular question often asked in an interview. You also might be in a situation where you have to store the current date retrieved by java.util.Date in a database table where the datatype of the column is DATE . In that case you have to convert it to java.sql.Date . Also you might have to fetch date from database and then store it in a java.util.Date object . So this is a very important topic. Since both of these classes store the value of date in long milliseconds, so it is very easy to convert from one type to the other. Both of these classes have a method called getTime() which is used for conversion.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
public class DateConverter {

    public static void main(String[] args) {
      
        //creating instances of java.util.Date representing current date and time
        java.util.Date now = new java.util.Date();
        System.out.println("Value of java.util.Date : " + now);
      
        //converting java.util.Date to java.sql.Date in Java
        java.sql.Date sqlDate = new java.sql.Date(now.getTime());
        System.out.println("Converted value of java.sql.Date : " + sqlDate);
      
        //converting java.sql.Date to java.util.Date back
        java.util.Date utilDate = new java.util.Date(sqlDate.getTime());
        System.out.println("Converted value of java.util.Date : " + utilDate);
    }
}
-------------------------------------------------------------------------------------------------------------------------
Output
-------------------------------------------------------------------------------------------------------------------------
Value of java.util.Date : Sun Mar 23 11:35:46 IST 2014
Converted value of java.sql.Date : 2014-03-23
Converted value of java.util.Date : Sun Mar 23 11:35:46 IST 2014


Hope this helps. Happy coding :)
Wednesday, July 31, 2013
In current times, we are always trying to complete our tasks in least possible amount of time. This has given rise to the need for multithreading. In multithreaded application, we have more than one threads running at the same time.  We can see that when we are writing some document in Microsoft Word we can write as well as run the spell-checker at the same time. This is done by multithreading. But the real problem arises when a shared resource is being accessed by more than one thread at the same time.
     For an example, let us consider that we we are in a situation where a couple Williams and Jennifer, both have an access to the same bank account but have two ATM cards one for each. Now, both of them are trying to withdraw a certain amount from the same account. Now here arises the problem. Suppose, they have now currently $1000 in account and can withdraw a maximum of $300. Before withdrawing, they must check balance and then withdraw. Now Williams checks the balance and waits for withdrawing while in the meantime Jennifer checks balance and sees that she can also withdraw a maximum of $300. Since both have the information that they can withdraw a maximum of $300, it results in "inconsistency" of data. This should be avoided. So we need synchronization.
      Synchronization will help in atomic operation. If we take our previous example then Jennifer should not be allowed to access the account until and unless Williams has completed his operation. So, she should be locked from accessing it.
      Object locking in Java can be done in two way - intrinsic locks and explicit locks. Intrinsic lock is achieved using the "synchronized" keyword in Java. On using this in a method or block will ensure that all the operations done inside that method or block will be done in a single operation. Explicit locks is done using Lock objects.
      We will discuss in detail on intrinsic and explicit locks using Producer-Consumer example in our next posts. Keep in touch with us.
Saturday, June 15, 2013
Today I will show you how to install Java on Ubuntu. New Linux users may find it difficult to install, so I will be sharing this post to help you people out. There are two procedures to do that. First is do it directly from terminal and the second is do it manually if you already have the binaries. We will show you the second procedure.

Step 1 : Download Java from Oracle Java SE Downloads . Download the appropriate version according to your platform architecture. [NOTE : The download link is subject to change. If dead please report it. ]

Step 2 ; Unpack the archive using the following command
tar xvzf <file-name> [ e.g. jdk-7u21-linux-x64.tar.gz ]
You will get a folder something named jdk1.7.0. 

Step 3 : Next we will have to create a directory named jvm and copy the extracted folder into it with following command.

mkdir jvm
cp -r <extracted-folder-name> jvm [ e.g. cp -r jdk1.7.0 jvm ]
Now we will have to move this jvm folder to /usr/lib directory.
sudo mv jvm /usr/lib . Enter password when asked.

Step 4 : Since we have successfully copied the folder, now we will only have to tell the Linux system where your Java is installed.

sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.7.0/bin/java" 1
  -It will tell that JRE is available
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.7.0/bin/javac" 1
  -It will tell Java Compiler is available
sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/lib/jvm/jdk1.7.0/bin/javaws" 1
  -It will tell Java Web Start is available

NOTE : There are many more executables that you may need to install like jar, javap, appletviewer and so on. Just perform the step 4 for installing any other features. We have just mentioned about java, javac and javaws. Also note that it is not mandatory to name the folder as jvm.

Hope this helps you. Keep coding   :)
Thursday, October 4, 2012
 Reasons for introducing the concept of packages in Java-->
1 : for better organizing of resources
2 : to avoid class name conflicts i.e. if there were no packages then it wouldn't have been possible to declare duplicate class names;
Convention of declaring packages--> package names are generally given according to reverse domain name. e.g.if your domain is javaingrab.blogspot.com then package is com.blogspot.javaingrab followed by your project and so on. This will prevent package name conflicts.
How to use packages--> First of all you will have to create a directory structure according to packages. e.g. for package com.blogspot.javaingrab directory structure is com/blogspot/javaingrab and so on. There is a keyword in java called package to declare a package. Now package statement should be the first line of your code. take a look at following code

package com.blogspot.javaingrab.xamples;
public class MyClass{
   public MyClass(){
      Sysytem.out.println("Package Demo");
   }
   public static void main(String[] args){
       new MyClass();
   }
}

How to compile with packages--> Generally sources are kept in a separate folder named src and classes in classes directory.Considering above example the directory would be like this /project/classes and /project/src/ and within src it will be src/com/blogspot/javaingrab/xamples and inside it will be MyClass.java file. Now if you are compiling from project directory command will be
C:\project javac -d classes -cp src src\com\blogspot\javaingrab\xamples\MyClass.java
-d switch : it is optional and is used if you want to place class files in a separate directory. This helps in automatic creation of directories according to your packages.
-cp switch : it means classpath. This is necessary only when your source requires other classes which may or may not reside in the same packages. Using this you can compile a particular class even if the dependent class resides in a different drive.
How to run with packages--> While running you will have to give the -cp switch followed by the dependent class file directory and then the fully qualified class name with package which you want to run. for the above class the command should be
C:\project java -cp classes com.blogspot.javaingrab.xamples.MyClass

WARNING : Do not mention about any package named directory as java compiler or JVM searches for the particular package inside the classpath. Yf you do this then it will be disastrous,so be careful.
Sunday, September 2, 2012
The answer to this question is NO. You cannot override static methods in Java. In order to show this,have a look at code below :

public class SuperClass{
   public static void show(){
      System.out.println("Static SuperClass Method");
   }
}

public class SubClass extends SuperClass{
    public static void show(){
       System.out.println("Static SubClass Method");
    }
}

public class Demo{
    public static void main(String[] args){
        SuperClass ob1=new SuperClass();
         SuperClass ob2=new SubClass();
        SubClass ob3=new SubClass();
         ob1.show();
         ob2.show();
         ob3.show();
    }    
}
The above code will give output as below :
Static SuperClass Method
 Static SuperClass Method
 Static SubClass Method
 If the static method had been overridden then the second line of the output would have been same as that of third line. So the method has not been overridden and a brand new method has been created in sub class. To understand it more deeply just rewrite the sub class as shown below :
public class SubClass extends SuperClass{
    @Override
    public static void show(){
       System.out.println("Static SubClass Method");
    }
}
If you write the latter one you won't be able to compile it. The compiler will tell that there is no such method in super class. So it is recommended that you always use the @Override annotation to verify that whether you have correctly overridden the method or not. So instead of getting an unexpected output you will get a compile time error which is better and easy for debugging. This is possible only with jdk1.5.0 and above.
REASON : The reason why static methods cannot be overridden is that the concept of inheritance is a concept of object. Now static methods and variables are class specific features and not object specific while non-static things are object specific features and for that reason only you can access static things directly using class name. Though static things can be accessed through objects yet they are related to classes and bound with them. Many of you may confuse with this. That's why C# does not allow you to access any static things with objects and thus have removed this confusing feature of Java.
Monday, August 13, 2012
AWT:
Pros

1.  Speed: use of native peers speeds component performance. 
2. Applet Portability: most Web browsers support AWT classes so
AWT applets can run without the Java plugin.
3. Look and Feel: AWT components more closely reflect the look
and feel of the OS they run on.
Cons 
1. Portability: use of native peers creates platform specific
limitations. Some components may not function at all on some
platforms.
2. Third Party Development: the majority of component makers,
including Borland and Sun, base new component development on
Swing components. There is a much smaller set of AWT
components available, thus placing the burden on the programmer
to create his or her own AWT-based components.
3.  Features: AWT components do not support features like icons and tool-tips.
Swing:
Pros 

1. Portability: Pure Java design provides for fewer platform specific
limitations.
2. Behavior: Pure Java design allows for a greater range of behavior
for Swing components since they are not limited by the native peers that AWT uses.
3. Features: Swing supports a wider range of features like icons and
pop-up tool-tips for components.
4. Vendor Support: Swing development is more active. Sun puts
much more energy into making Swing robust.
5. Look and Feel: The pluggable look and feel lets you design a
single set of GUI components that can automatically have the look
and feel of any OS platform (Microsoft Windows, Solaris,
Macintosh, etc.). It also makes it easier to make global changes to
your Java programs that provide greater accessibility (like picking
a hi-contrast color scheme or changing all the fonts in all dialogs,
etc.).
Cons
1. Applet Portability: Most Web browsers do not include the Swing
classes, so the Java plugin must be used.
2. Performance: Swing components are generally slower and buggier than AWT, due to both the fact that they are pure Java and to video issues on various platforms. Since Swing components handle their own painting (rather than using native API's like DirectX on Windows) you may run into graphical glitches.
3. Look and Feel: Even when Swing components are set to use the
look and feel of the OS they are run on, they may not look like
their native counterparts.
Tuesday, August 7, 2012
This post is for all who has just started learning java or planning to do so. If you are from a C/C++ background then you will see that you didn't have to do all these things. You only had to install TurboC. But in Java it is necessary to set the path as without it you cannot compile or run a java program from command prompt if your source file resides in a different location as that of the compiler. At that situation windows won't be able to recognize javac as a command. Many of you will think that they can compile or run from an IDE like Eclipse,NetBeans,JCreator or BlueJ. But you will understand later that many things can't be done from here which can be done from your command prompt. Follow these steps carefully :




1 : Download and install the latest version of jdk(i.e. jdk7) in order to keep yourself always updated.
2 : Go to the location where you have installed jdk and look for bin folder. the path may look like this C:\Program Files\Java\jdk1.7.0\bin. Just copy this path from the location bar.
 3 : Now right click on My Computer and select Properties. It will open the system window.
  
4 : Now select Advanced System Settings from the window as shown
5 : Now select Environment variables
6 : Now look for Path under System Variable. Either double click it or select edit after choosing it.
7 : Now go the beginning and paste the path that you have copied earlier and then give a semi-colon.
WARNING : Do not change any other things and don't forget to give the semi-colon as either of this will cause system problems.
8 : Now press OK and give Administrator permission while doing it. You will have to press OK for two times to close the other dialogs that were already open. That's it. You have successfully set the path and compile from anywhere with javac command. If still windows can't recognize the javac command then you have done some mistake in the procedure. Plz check it.
Saturday, August 4, 2012
#include directive makes the compiler go to the C/C++ standard library and copy the code from the header files into the program. As a result, the program size increases, thus wasting memory and processor’s time.
import statement makes the JVM go to the Java standard library, execute the code there , and substitute the result into the program. Here, no code is copied and hence no waste of memory or processor’s time.hence import is an efficient mechanism than #include.
Sunday, July 29, 2012
It is not allowed since static nature of the method will give permission to access it directly by class name only. But contrarily abstract nature will prohibit it from doing so. This results in a conflicting nature (based on meaning of two modifiers) of the method. Due to this reason Java does not allow you to declare a method both static and abstract. If you try to do this you will get a compile error as illegal combination of modifiers : abstract and static.
Saturday, July 28, 2012
An abstract class is one which cannot be instantiated. Its properties and characteristics cannot be used until and unless it is not inherited by a concrete class. So in order to use such type of classes you will have to extend that class and override its methods.
A final class is one that cannot be inherited i.e. a class defined as final cannot be extended and redefined using the software reusability concept of inheritance.
Now if you try to combine both of these two things, then the class declared final and abstract cannot be inherited as being declared final and since it is abstract we cannot use it directly by creating its object. Hence such a class is of no use and makes no sense at all. For this reason only it is not possible to declare a class both final and abstract.
Friday, July 27, 2012
 A method is a function that is written in a class. We do not have functions in java; instead we have methods. This means whenever a function is written in java,it should be written inside the class only. But if we take C++, we can write the functions inside as well as outside the class . So in C++, they are called member functions and not methods.
As you know C/C++ supports pointers. But Java doesn't. This is because of the following reasons :
1) Pointers can result in a crash of your program. So it helps in stabilizing yor code in Java without pointers.
2) Pointers can cause programmers to become confused.
3) Java was developed to make system more secure. So keeping security in mind it was decided to omit pointers as pointers can be used very efficiently to create VIRUS/Malware programs.
In Java program execution starts from main method. And the main method should look like this public static void main(String[] args). Here it is declared static. This is due to following reasons :
1) It can be called directly by the class name without creating its instance.
2) If the class containing main have more than one constructor then JVM won't be able to understand which constructor to use while creating the object.
3) Again if there is a parameterized constructor in the class containing main then also JVM won't understand what value to pass while creating the object.

Total Pageviews

Followers


Labels

Popular Posts

free counters