Friday, 27 December 2013

Why we use constructor in Java?

Some people think that Constructor are used to create object , they are totally wrong. In actual constructor are used to construct the object, you cannot make object without invoking a constructor in java.

You cannot make a new object without invoking not only constructor of object's  actual class type but also the constructor of each of its superclasses

Constructor are the code that runs whenever you use the keyword new .

So every class must have constructor including Abstract classes.
Points to remember for constructors are
1. dont have return type
2. name must match the class name

So why we use them ?
Actually constructors are used to initialize the instance variable state as follows

class Demo{
 int age;
Demo(int age)
{
this.age=age;
}
}

Do you know each constructor must call their super constructor.

in the previous code block compiler will automatically add super() after this.age=age; line.

If we dont write any constructor in our java class then compiler automatically create default constructor .

Thursday, 26 December 2013

Why we need encapsulation in Java?

Why we need Encapsulation in Java ?

Suppose many programmer in your company wrote program that used your class.Now imagine later on you want to change an instance variable's value because the value set(by some other programmer using you class) to those variable are producing errors for you. Lets take an example

your class Demo1
{
int age;
getCalculatedAge()
{
//Code for calculation of age
}
}

Now suppose another programmer using your code

Demo2()
{
Demo1 d1=new Demo1();
d1.age= -4; // Suppose this causes some problem
d1.getCalculatedAge();
}
And now you're in trouble. How are you going to change the class in a way that lets you handle the issues that come up when somebody changes the age variable to a value that causes problems?

Your only choice is to go back a write a method setAge(int) for getting the age and handle the problem as well as you have to protect your age variable with private access modifier.

But as soon as you make your changes you break everyone else's code.

The ability to make changes in your implementation code without breaking the 
code of others who use your code is a key benefit of encapsulation.

If you want maintainability, flexibility, and extensibility (and of course, you do),your design must include encapsulation. How do you do that?

1. Keep instance variable protected (e.i private )
2.Make public setter or getter method so you can access and set the value to those variable.

public void setAge(int a)
{
age=a;
}
 
public int getAge()
{
return age;
}

This will prevent the direct access of your instance variable.Wait a minute...how useful is the previous code? 

Now what benefit can be there from getter and setter, Now in future if you want any processing or validation while getting the age from the setAge method you can do that without affecting anyone else's code which are using your class. Even if today you don't think you really need validation or processing of the data, good OO design dictates that you plan for the future. To be safe, force calling code to go through your methods rather than going directly to instance variables. Always. Then you're free to rework your method implementations later, without risking the wrath of those dozen programmers who know where you live.

Thursday, 12 December 2013

What is String Literal or Constant pool?



If you've done any preparation for the SCJP exam (and quite possibly even if you haven't), you've probably heard of the "String Literal Pool." What is the String Literal Pool? Most often, I hear people say that it is a collection of String objects. Although that's close, it's not exactly correct. Really, it's a collection of references to String objects. Strings, even though they are immutable, are still objects like any other in Java. Objects are created on the heap and Strings are no exception. So, Strings that are part of the "String Literal Pool" still live on the heap, but they have references to them from the String Literal Pool.

Yeah, so that doesn't really explain what the pool is, or what it's for, does it? Well, because String objects are immutable, it's safe for multiple references to "share" the same String object. Take a look at this example:


Source Code

public class ImmutableStrings {
 public static void main(String[] args)
 {
 String one = "techArcher";
 String two = "techArcher"; 
 System.out.println(one.equals(two)); 
 System.out.println(one == two); } } 

 // Output true true




In such a case, there is really no need to make two instances of an identical String object. If a String object could be changed, as a StringBuffer can be changed, we would be forced to create two separate objects. But, as we know that String objects cannot change, we can safely share a String object among the two String references, one and two. This is done through the String literal pool. Here's how it is accomplished:

When a .java file is compiled into a .class file, any String literals are noted in a special way, just as all constants are. When a class is loaded (note that loading happens prior to initialization), the JVM goes through the code for the class and looks for String literals. When it finds one, it checks to see if an equivalent String is already referenced from the heap. If not, it creates a String instance on the heap and stores a reference to that object in the constant table. Once a reference is made to that String object, any references to that String literal throughout your program are simply replaced with the reference to the object referenced from the String Literal Pool.

So, in the example shown above, there would be only one entry in the String Literal Pool, which would refer to a String object that contained the word "techArcher". Both of the local variables, one andtwo, would be assigned a reference to that single String object. You can see that this is true by looking at the output of the above program. While the equals() method checks to see if the String objects contain the same data ("techArcher"), the == operator, when used on objects, checks for referential equality - that means that it will return true if and only if the two reference variables refer to the exact same object. In such a case, the references are equal. From the above output, you can see that the local variables, one and two, not only refer to Strings that contain the same data, they refer to the same object.

Graphically, our objects and references would look something like this:




Note, however, that this is a special behavior for String Literals. Constructing Strings using the "new" keyword implies a different sort of behavior. Let's look at an example:


Source Code
public class ImmutableStrings 

 public static void main(String[] args) 
 {
 String one = "techArcher"; 
 String two = new String("techArcher"); 
 System.out.println(one.equals(two)); 
 System.out.println(one == two); 
 }
 } 

 // Output true false




In this case, we actually end up with a slightly different behavior because of the keyword "new." In such a case, references to the two String literals are still put into the constant table (the String Literal Pool), but, when you come to the keyword "new," the JVM is obliged to create a new String object at run-time, rather than using the one from the constant table.

In such a case, although the two String references refer to String objects that contain the same data, "techArcher", they do not refer to the same object. That can be seen from the output of the program. While the equals() method returns true, the == operator, which checks for referential equality, returns false, indicating that the two variables refer to distinct String objects.

Once again, if you'd like to see this graphically, it would look something like this. Note that the String object referenced from the String Literal Pool is created when the class is loaded while the other String object is created at runtime, when the "new String..." line is executed.




If you'd like to get both of these local variables to refer to the same object, you can use the intern() method defined in String. Invoking two.intern() will look for a String object referenced from the String Literal Pool that has the same value as the one you invoked the intern method upon. If one is found, a reference to that String is returned and can be assigned to your local variable. If you did so, you'd have a picture that looks just like the one above, with both local variables, one and two, referring to the same String object, which is also referenced from the String Literal Pool. At that point, the second String object, which was created at run-time, would be eligible for garbage collection.

String is immutable?

This is one of the most popular String interview question in Java, this question some time may be asked as Why String is final in Java.

There may be many reason for this according to the creator of String in Java but few of my points are as:

1. String pool :- It is a special memory area in heap for storing the String literals. if the instance is already exist in the String constant pool then this new instance is mapped to the already existing instance,If not then a new Java String instance is created and stored in the pool.
There are several way to create an object of String, the only way to use the String Constant pool is using Literals

When the compiler encounters a String literal, it checks the pool to see if an identical String already exists.
Lets take an example

String literal = "techArcher"; 
String one = new String(literal);
String two = "techArcher"; 
System.out.println(literal == two); //true 
System.out.println(one == two); //false

String is immutable means String object cannot be changed lets take another example

public class ImmutableStrings 
 public static void main(String[] args)
 { 
    String start = "Hello"; 
    String end = start.concat(" World!"); 
    System.out.println(end); 
 }
 } 
 // Output Hello World!

Well look at that, the String changed...or did it? In that code, no String object was ever changed. We start by assigning "Hello" to our variable, start. That causes a new String object to be created on the heap and a reference to that object is stored in start. Next, we invoke the method concat(String) on that object. Well, here's the trick, if we look at the API Spec for String, you'll see this in the description of the concat(String) method:

Concatenates the specified string to the end of this string. 

If the length of the argument string is 0, then this String object is returned. Otherwise, a new String object is created, representing a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string.

Notice the part I've highlighted in bold. When you concatenate one String to another, it doesn't actually change the String object, it simply creates a new one that contains the contents of both of the original Strings, one after the other. That's exactly what we did above. The String object referenced by the local variable start never changed. In fact, if you added the statementSystem.out.println(start); after you invoked the concat method, you would see that start still referenced a String object that contained just "Hello". And just in case you were wondering, the '+' operator does the exact same thing as the concat() method.

Strings really are immutable.

Wednesday, 11 December 2013

Java Programming interview questions

Sometimes in interviews you may asked to solve some programming questions based on the oops concept, so some questions related to the OOPs concepts are given below.

1.What would be the output of the given code snippets.

public static void methodA(Object o)
{
System.out.println("called from object");
}
public static void methodA(String s)
{
System.out.println("Called from string ");
}
public static void main(String[] a)
{
methodA(null);
}


So the answer would be
Called from string


because
Whenever there's Method Overloading, the JVM will search for the method from the most specific type to least specific type.


2.What would be the output of given program
class A
{
public void display()
{
System.out.println("class A");
}
}
public class B extends A
{
public void display()
{
System.out.println("class B");
}
public static void main(String[] args)
{
A a=new B();
a.display();
}
}



Ans:
class B

what happened here, we are calling the method from class A's reference variable but called the B's display method why?

This concept is called dynamic method dispatch, which is basically used by runtime environment for checking the actual type of objects.So here reference variable a contains the class B object actual so runtime called the method from class B.

Polymorphic method invocations apply only to instance methods. You can always refer to an object with a more general reference variable type (a superclass or interface),
but at runtime, the ONLY things that are dynamically selected based on the actual object (rather than the reference type) are instance methods. Not static methods. Not variables. Only overridden instance methods are dynamically invoked based on the real object's type.

3.What would be the output of the given question.

class A
{
public void show()
{
System.out.println("hi");
}
}
public class B extends A
{
public void display()
{
System.out.println("hi display");
}
public static void main(String[] args)
{
A a=new B();
a.show();
a.display();
}
}


Ans.
Compile time error

But why we are getting compile time error a reference variable referring B class object and B class has both the method then why this error.
Reason for this error is that at compile time, compiler don't check the type of the Object referred by the reference variable a, compiler only see the reference variable's class and checks whether called method through this reference variable exist in the class or not,If not found error occurred.


4.Why Java does not support multiple inheritance.

As we know that multiple inheritance is not supported in Java but the question is Why they did not introduce multiple inheritance like C++.
Lets clear one thing what is multiple inheritance ?
Multiple Inheritance:- This is the capability which allow a class to extend more than one other class.

Note:- Inheritance is used for code re-usability.

The reason that Java's creators chose not to allow multiple inheritance is that it can become quite messy.

The problem is that if a class extended two other classes,and both super classes had, say, a doStuff() method, which version of doStuff() would the subclass inherit? This issue can lead to a scenario known as the "Deadly Diamond of Death" because of the shape of the class diagram that can be created in a multiple inheritance design. The diamond is formed when classes B and C both extend A, and both B and C inherit a method from A. If class D extends both B and C, and both B and C have overridden the method
in A, class D has, in theory, inherited two different implementations of the same method. Drawn as a class diagram, the shape of the four classes looks like a diamond.



So the compiler will be confused which version of doStuff() will be called, That's why multiple inheritance is not allowed in Java.


5. Some Rules for overriding a method


  • The argument list must exactly match that of the overridden method
  • The return type must be the same as, or a subtype of, the return type declared in the original overridden method in the superclass
  • The access level can't be more restrictive than the overridden method's. e.g You cann't use protected access level if superclass method have public access.
  • The access level CAN be less restrictive than that of the overridden method.
  • The overriding method CAN throw any unchecked (runtime) exception,regardless of whether the overridden method declares the exception.
  • The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method. For example, a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception, or any other non-runtime exception unless it's a subclass of FileNotFoundException.
  • The overriding method can throw narrower or fewer exceptions. Just because an overridden method "takes risks" doesn't mean that the overriding subclass's exception takes the same risks. Bottom line: an overriding method doesn't have to declare any exceptions that it will never throw, regardless of what theoverridden method declares.
  • You cannot override a method marked final.
  • If a method can't be inherited, you cannot override it. Remember that overriding implies that you're reimplementing a method you inherited!
6.Rules for method overloading
Overloaded methods must change the argument list.
Overloaded methods can change the return type
Overloaded methods can change the access modifier
Overloaded methods can declare new or broader checked exception.
Remember one thing that the reference type not actual object type determines which overloaded method is invoked but which overridden version of the method to call is decided at runtime based on object type.
But which overloaded version of the method to call is based on the reference type of the argument list at compile time.

6.Why we used abstract class even if we have interfaces?

Both abstract class and interface are used to achieve abstraction in java.But what to choose is very good interview question. So abstract class is used where we want to provide some default behaviour , But interface is used where we are not providing any default behaviour , user can give any implementation for the behaviour of the interface .

One more thing that interface have all the method public if you want to make any method more restrictive then you can use abstract class.

But we also know that java doesn't provide multiple inheritance so its better to go for interface.


Tuesday, 26 November 2013

Why Java is preferred for Application programming?

Java is one of the best high level language.Application development is not only task of software engineers, they are supposed to build and structure products for clients that meet their expectations, provide the features they need and be supported by strong backup.


In earlier times, writing code for developing applications was, essentially, rocket science. There were very few people who could actually write programs that were useful and functional.
The concept of object-oriented languages changed that by allowing programming to be related and to map to real-world entities in terms of actors and actions. The object-oriented paradigm of software programming encompasses all the features of object-oriented languages. These include:

1.Polymorphism :- One general interface acts as a multiple class of actions. It is usually seen in the case of methods in Java.
2.Inheritance: Promotes code re-usability and building stronger subsystems on top of existing structures
3.Encapsulation: Binding the code and data together to keep it safe from outside interference and prevent information abuse
4.Abstraction: Intrinsic details are hidden with an interface-based layer for users. The removes the concern for deep diving into lower-level information pertaining to the system.

These features are more or less common to all the languages that follow or support the object-oriented model.

 However, the degree to which they conform to the above specifications is what sets them apart from their counterparts. The way they can be modulated and work in favor of both the developer and the end users is something that matters a lot.

Simple


  • Looks familiar to existing programmers: related to C and C++:
  • Omits many rarely used, poorly understood, confusing features of C++, like operator overloading, multiple inheritance, automatic coercions, etc.
  • Contains no goto statement, but break and continue
  • Has no header files and eliminated C preprocessor
  • Eliminates much redundancy (e.g. no structs, unions, or functions)
  • has no pointers
  • Added features to simplify:

  • Garbage collection, so the programmer won't have to worry about storage management, which leads to fewer bugs.
  • A rich predefined class library

  • Object-Oriented

    Java is an object-oriented language, which means that you focus on the data in your application and methahods tt manipulate that data, rather than thinking strictly in terms of procedures.
    In an object-oriented system, a class is a collection of data and methods that operate on that data. Taken together, the data and methods describe the state and behavior of an object. Classes are arranged in a hierarchy, so that a subclass can inherit behavior from its superclass.
    Java comes with an extensive set of classes, arranged in packages, that you can use in your programs.

    Distributed


  • It has a spring-like transparent RPC system
  • Now uses mostly tcp-ip based protocols like ftp & http
  • Java supports various levels of network connectivity through classes in the java.net package (e.g. the URL class allows a Java application to open and access remote objects on the internet).

    Interpreted

    The Java compiler generates byte-codes, rather than native machine code. To actually run a Java program, you use the Java interpreter to execute the compiled byte-codes. Java byte-codes provide an architecture-neutral object file format. The code is designed to transport programs efficiently to multiple platforms.

  • rapid turn-around development
  • Software author is protected, since binary byte streams are downloaded and not the source code

  • Robust

    Java has been designed for writing highly reliable or robust software:

  • language restrictions (e.g. no pointer arithmetic and real arrays) to make it impossible for applications to smash memory (e.g overwriting memory and corrupting data)
  • Java does automatic garbage collection, which prevents memory leaks
  • extensive compile-time checking so bugs can be found early; this is repeated at runtime for flexibilty and to check consistency

  • Secure

    Security is an important concern, since Java is meant to be used in networked environments. Without some assurance of security, you certainly wouldn't want to download an applet from a random site on the net and let it run on your computer. Java's memory allocation model is one of its main defenses against malicious code (e.g can't cast integers to pointers, so can't forge access). Furthermore:

  • access restrictions are enforced (public, private)
  • byte codes are verified, which copes with the threat of a hostile compiler

  • Architecture-Neutral


  • compiler generates bytecodes, which have nothing to do with a particular computer architecture
  • easy to interpret on any machine

  • Portable

    Java goes further than just being architecture-neutral:

  • no "implementation dependent" notes in the spec (arithmetic and evaluation order)
  • standard libraries hide system differences
  • the Java environment itself is also portable: the portability boundary is POSIX compliant

  • High-Performance

    Java is an interpreted language, so it will never be as fast as a compiled language as C or C++. In fact, it is about 20 times as slow as C. However, this speed is more than enough to run interactive, GUI and network-based applications, where the application is often idle, waiting for the user to do something, or waiting for data from the network.

    Multi threaded

    Java allows multiple concurrent threads of execution to be active at once. This means that you could be listening to an audio clip while scrolling the page and in the background downloading an image. Java contains sophisticated synchronization primitives (monitors and condition variables), that are integrated into the language to make them easy to use and robust. The java.lang package provides a Thread class that supports methods to start, run, and stop a thread, and check on its status.

    Dynamic

    Java was designed to adapt to an evolving environment:

  • Even after binaries have been released, they can adapt to a changing environment
  • Java loads in classes as they are needed, even from across the network
  • It defers many decisions (like object layout) to runtime, which solves many of the version problems that C++ has



  • Dynamic linking is the only kind there is


  • Wednesday, 13 November 2013

    Setup Eclipse With Phonegap or Cordova-2.7.0

    This post describes  how to setup your development environment for Cordova and run a simple application.


    Requirements
    Eclipse 3.4+

    Install SDK + Cordova
    Download and install Eclipse Classic
    Download and install Android SDK
    Download and install ADT Plugin
    Download the latest copy of [PhoneGap and extract its contents. We will be working with the Android directory.


    Setup New Project
                                                  Launch Eclipse, and select menu item New > Android Project. Fill out the three panels of the New Android Project wizard shown below.


    1.Enter Application Name and click Next
    .



    2.Now don't change anything just click Next again.




    3. In this window you will see Configure launcher icon , Here you can set your icon for application.After selecting icon,Click Next. 






    4.Now again click Next



    5.click Next

    6. Now you can see your project structure given below.

     

    And the magic of cordova will start now .See the below steps for integrate cordova with android app.


    In the root direct
    ory of your project, create two new directories:
    /libs
    assets/www 

    Note :- If libs and assets are already there then only create www subfolder in assets.

    Copy
    cordova-2.7.0.js from your Cordova download earlier to assets/www
    Copy cordova-2.7.0.jar from your Cordova download earlier to /libs
    Copy xml folder from your Cordova download earlier to /res

    * Verify that cordova-2.7.0.jar is listed in the Build Path for your project. Right click on the /libs folder and go to Build Paths/ > Configure Build Path.... Then, in the Libraries tab, add cordova-2.7.0.jar to the project. If Eclipse is being temperamental, you might need to refresh (F5) the project once again.
    ***Note:- You can find xml folder in phonegap-2.9.1\lib\android\example\res when you will extract
    phonegap-2.9.1 zip, In this folder you will get a config.xml.









    • Now if cordova-x.x.x is not added in Libraries then Click-> Add Jars.. and select cordova-x.x.x jar from libs.
      Edit your project's main Java file found in the src folder in Eclipse:
      Add import org.apache.cordova.*;
      Change the class's extend from Activity to DroidGap
      Replace the setContentView() line with super.loadUrl("file:///android_asset/www/index.html");








      Right click on AndroidManifest.xml and select Open With > XML Editor
      Paste the following permissions between the <uses-sdk.../> and <application.../> tags.

      <supports-screens
      android:largeScreens="true"
      android:normalScreens="true"
      android:smallScreens="true"
      android:resizeable="true"
      android:anyDensity="true" />
      <uses-permission android:name="android.permission.VIBRATE" />
      <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
      <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
      <uses-permission android:name="android.permission.READ_PHONE_STATE" />
      <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.RECEIVE_SMS" />
      <uses-permission android:name="android.permission.RECORD_AUDIO" />
      <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
      <uses-permission android:name="android.permission.READ_CONTACTS" />
      <uses-permission android:name="android.permission.WRITE_CONTACTS" />
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
      <uses-permission android:name="android.permission.GET_ACCOUNTS" />
      <uses-permission android:name="android.permission.BROADCAST_STICKY" />







    • Now  Support orientation changes by pasting the following inside the <activity> tag. 
      • android:configChanges="orientation|keyboardHidden|screenSize"
             You can see the android-manifest.xml changed below..


    *Hello World

    Create a new file index.html in  assets/www folder with below code..

      <!DOCTYPE HTML>
      <html>
      <head>
      <title>JavaArc Hello Phone Gap</title>
      <script type="text/javascript" charset="utf-8" src="cordova-2.7.0.js"></script>
      </head>
      <body>
      <h1>Hello Phone Gap</h1>
      </body>
      </html>


     Deploy to Simulator
     Right click the project and go to Run As > Android Application
     Eclipse will ask you to select an appropriate AVD. If there isn't one, then you'll need to create it.

     Deploy to Device
     Make sure USB debugging is enabled on your device and plug it into your system. (Settings > Applications  > Development)
     Right click the project and go to Run As > Android Application
    Done!