Archive

Archive for the ‘Java’ Category

Interview Questions : Java Fundamentals

June 30th, 2009

1. Give a few reasons for using Java?

a.  Java is a fun language. Let’s look at some of the reasons:

  • Built-in support for multi-threading, socket communication, and memory management (automatic garbage collection).
  • Object Oriented (OO).
  • Better portability than other languages across operating systems.
  • Supports Web based applications (Applet, Servlet, and JSP), distributed applications (sockets, RMI. EJB etc) and network protocols (HTTP, JRMP etc) with the help of extensive standardised APIs (Application Program Interfaces).

2. What is the main difference between the Java platform and the other software platforms?

a.  Java platform is a software-only platform, which runs on top of other hardware-based platforms like UNIX, NT etc. ava Virtual Machine (JVM) – ‘JVM’ is a software that can be ported onto various hardware platforms.  Byte codes are the machine language of the JVM.

3. What is the difference between C++ and Java?

a.  Both C++ and Java use similar syntax and are Object Oriented, but:

  • Java does not support pointers. Pointers are inherently tricky to use and troublesome.
  • Java does not support multiple inheritances because it causes more problems than it solves. Instead Java supports multiple interface inheritance, which allows an object to inherit many method signatures from different interfaces with the condition that the inheriting object must implement those inherited methods. The multiple interface inheritance also allows an object to behave polymorphically on those methods.
  • Java does not support destructors but rather adds a finalize() method. Finalize methods are invoked by the garbage collector prior to reclaiming the memory occupied by the object, which has the finalize() method. This means you do not know when the objects are going to be finalized. Avoid using finalize() method to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these resources through the finalize() method.
  • Java does not include structures or unions because the traditional data structures are implemented as an object oriented framework (Collection Framework)
  • All the code in Java program is encapsulated within classes therefore Java does not have global variables or functions.
  • C++ requires explicit memory management, while Java includes automatic garbage collection.

4. What are the advantages of Object Oriented Programming Languages (OOPL)?

a. The Object Oriented Programming Languages directly represent the real life objects like Car, Jeep, Account, Customer etc. The features of the OO programming languages like polymorphism, inheritance and encapsulation make it powerful.

[Tip: remember pie which, stands for Polymorphism, Inheritance and Encapsulation are the 3 pillars of OOPL]

5. What is the difference between aggregation and composition?

a.  Aggregation is an association in which one class belongs to a collection. This is a part of a whole relationship where a part can exist without a whole.
For example a line item is a whole and product is a part. If a line item is deleted then corresponding product need not be deleted. So aggregation has a weaker relationship.

Composition is an association in which one class belongs to a collection. This is a part of a whole relationship where a part cannot exist without a whole. If a whole is deleted then all parts are deleted.
For example An order is a whole and line items are parts. If an order deleted then all corresponding line items for that order should be deleted. So composition has a stronger relationship.

6. How does the Object Oriented approach improve software development?

a. The key benefits are:

  • Re-use of previous work: using implementation inheritance and object composition.
  • Real mapping to the problem domain: Objects map to real world and represent vehicles, customers, products etc: with encapsulation.
  • Modular Architecture: Objects, systems, frameworks etc are the building blocks of larger systems.

The increased quality and reduced development time are the by-products of the key benefits discussed above. If 90% of the new application consists of proven existing components then only the remaining 10% of the code
have to be tested from scratch.

7. Why there are some interfaces with no defined methods (i.e. marker interfaces) in Java?

a. The interfaces with no defined methods act like markers. They just tell the compiler that the objects of the classes implementing the interfaces with no defined methods need to be treated differently. Example Serializable, Cloneable etc

8. When is a method said to be overloaded and when is a method said to be overridden?
a. Method Overloading :

  • Overloading deals with multiple methods in the same class with the same name but different method signatures.

class MyClass {
public void initParams(int param) {…}
public void initParams(int param1, long param2)
{ … }
}

  • Both the above methods have the same method names but different method signatures, which mean the methods are overloaded.
  • Overloading lets you define the same operation in different ways for different data.

Method Overriding:

  • Overriding deals with two methods, one in the parent class and the other one in the child class and has the same name and signatures.

class BaseClass{
public void initParams(int param) {…}
}
class MyClass extends BaseClass {
public void initParams(int param) { …}
}

  • Both the above methods have the same method names and the signatures but the method in the subclass MyClass overrides the method in the superclass BaseClass.
  • Overriding lets you define the same operation in different ways for different object types.

9. What is the main difference between an ArrayList and a Vector? What is the main difference between Hashmap and Hashtable?

a. Vector/Hashtable: Original classes before the introduction of Collections API. Vector & Hashtable are synchronized. Any method that touches their contents is thread-safe.
ArrayList/Hashmap: So if you don’t need a thread safe collection, use the ArrayList or Hashmap. Why pay the price of synchronization unnecessarily at the expense of performance degradation.

10. So which is better?

a. As a general rule, prefer ArrayList/Hashmap to Vector/Hashtable. If your application is a multithreaded application and at least one of the threads either adds or deletes an entry into the collection then use new Java collection API‘s external synchronization facility as shown below to temporarily synchronize your collections as needed:

Map myMap = Collections.synchronizedMap (myMap);
List myList = Collections.synchronizedList (myList);

Java arrays are even faster than using an ArrayList/Vector and perhaps therefore may be preferable. ArrayList/Vector internally uses an array with some convenient methods like add(..), remove(…) etc.

S.Chandru Java , , , , ,

interview Questions : Java

June 15th, 2009

1. what are the Native methods in Java?

a. When you want to call functions or subroutines which are written in some other language other than Java like C, C++ or VB6 etc.., These methods are Native methods in Java.

2. Explain Garbage Collection in Java?

a. Garbage collection is the process of automatically freeing object that are no longer referenced by the program. This frees the programmer from having to keep track of when to free allocated memory, thereby preventing many bugs. Thus making programmers more productive as they can put more effort in coding rather than worrying about memory management. The only disadvantage of garbage collector is it adds overheads. Because the JVM has to keep a constant track of the objects which are not referenced and then free these unreferenced objects on fly. This whole process has slight impact on the application performance.

3. How can we force the garbage collector to run?

a. Garbage collector can be run forcibly using “System.gc()” or “Runtime.gc()”

4. What is use of method “finalize()” in Java?

a. Sometimes the objects needs to perform some action before the object is destroyed. For instance object is holding some non-java resources such as file handle which you might want to make sure are released before the object is destroyed. For such conditions java provides mechanism called finalization. You can add finalizer in a class by simply defining the “finalize()” method. JVM calls that method whenever it is about to recycle an object of that class.

5. Are String objects immutable, can you explain the concept?

a. Yes String object is immutable, Once you have assigned a String a value, that value can never change. Lets try to understand the concept by the below code snippet

String s1 = “hello”;

s1 = s1 + ” World”;

The VM took the value of String s (which was “hello”), and tacked ” world” onto the end, giving us the value “abcdef more stuff”. Since Strings are immutable, the VM couldn’t stuff this new value into the old String referenced by s1, so it created a new String object, gave it the value “hello world”,and made s1 refer to it. At this point in our example, we have two String objects: the first one we created, with the value “hello”, and the second one with the value ” world”. Technically there are now three String objects, because the literal argument to concat, ” world”, is itself a new String object.

6. Why String objects are immutable in Java?

a.To make Java more memory efficient, the JVM sets aside a special area of memory called the “String constant pool.” When the compiler encounters a String literal, it checks the pool to see if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created. (The existing String simply has an additional reference.) Now we can start to see why making String objects immutable is such a good idea. If several reference variables refer to the same String without even knowing it, it would be very bad if any of them could change the String’s value.

You might say, “Well that’s all well and good, but what if someone overrides the String class functionality; couldn’t that cause problems in the pool?” That’s one of the main reasons that the String class is marked final. Nobody can override the behaviors of any of the String methods, so you can rest assured that the String objects you are counting on to be immutable will, in fact, be immutable.

7. What is StringBuffer class and how does it different from String class?

a. StringBuffer is a peer class of String that provides almost all functionality of Strings. String represent fixed-length, immutable character sequences. Comparatively StringBuffer represents mutable, growable and write-able character sequences. But StringBuffer does not create new instance as String so it’s more efficient when it comes to intensive concatenation operation.

8. What is the difference between StringBuilder and StringBuffer class?

a. StringBuffer is synchronized and StringBuilder is not.

9. What are the packages?

a. Packages group related class and interfaces together and thus avoiding any name conflicts. Classes are group together in package using “package” keyword.

10. What is use of JAVAP tool?

a. “javap” disassembles compiled Java files and spits out the representation of the Java program. This is a useful option when the original source code is unavailable.

S.Chandru Java ,

Creating a Flex 3 Web application in Tomcat integrated Server in MyEclipse

April 24th, 2009

This article is continuation of my previous article on Installing Flex Builder Plugin in MyEclipse In this article I’ve focused on how to create and deploy a Flex 3.0 and Java Web application using BlazeDS in Tomcat integrated server in MyEclipse.

Prerequisites:
  • Should have integrated Flex Builder with MyEclipse.
  • Download latest release of binary version of BlazeDS from Adobe Open source site - Point to be noted BINARY DISTRIBUTION TO BE DOWNLOADED NOT ‘TURNKEY’ VERSION - Turnkey version has Tomcat & Samples in built.
  • After download, unzip the zip file & further unzip the “blazeDS.war” file to a temp folder.
  • The temp folder contains two folders “META-INF” & “WEB-INF”. Keep this in one place.

Creating and Deploying Flex web application step by step:

  • Open MyEclipse
  • Create a new Web Project, not Flex Project as shown below.new-web-project
  • New Web Project Window screen appears. Fill in all credentials as shown in below image.webprojdetails
  • [Note: Below are the credentials which are used in this document]
  1. Project Name: “FlexSampleWeb”
  2. Location: “use default location”, or user can have their choice of directory here
  3. Source Folder: “src”
  4. Web root folder: “WebRoot”
  5. Context root url: “/FlexSampleWeb”.
  6. If user has JDK or Java EE 5.0 Version of Java installed, it might alert for the same, click Ok button. It basically means to use JDK 1.4 or whatever default version selected to be used for this project [Make sure it should be JDK 1.4 or higher - as it is required for BlazeDS]
  • Click Finish to See Web Project being created.
  • Now minimize MyEclipse, and go to “FlexSampleWeb” Project root directory which is created just few steps before. In general scenario it would be present in “[WorkSpace Folder] > FlexSampleWeb” directory or path.
  • Also open the blazeDS.war extracted directory
  • Copy both “META-INF” & “WEB-INF” directories from blazeDS extracted directory to “FlexSampleWeb” project’s “WebRoot” directory.
  • Probably it will ask user for existences of few files & and asks for confirming the operation.
  • Click YES button to overwrite the files. (Don’t panic this operation is not harmful)
  • Now open or maximize the MyEclipse Editor
  • Refresh “FlexBlazeDSSample” project
  • The latest files along with “BlazeDS” config files under “WEB-INF > flex” directory are seen
  • And checking the properties of project & moving to java build path > library should also show blazeDS libraries
  • Below snapshots should be the outcomeproperties-for-flexsampleweb
  • Close all properties windows or any windows opened.
  • Go to Windows, Open Server Window View, you would basically see “Tomcat” Server with stopped status
  • Click Start to Start the Server
  • Deploy the web project which is created just now
  • Right Click on Tomcat Server on Server Panel
  • Click Manage Deployments to deploy
  • New Deployment screen appears.
  • Click Finish to deploy the web project.
  • Now, create a Flex Project which will integrate with the web project which was created earlier.
  • Either from File Menu or through right click options being Flex Development Perspective, Create new project.new-flex-project
  • Fill in the credentials as shown in above image
  • Project Name - “FlexSampleUi”
  • Project location - “use default location” - user can choose directory of their choice
  • Application Type - “Web Application”
  • Server Technology
    1. Application Server Type - “J2EE”
    2. Check on “use remote object access service”
    3. “LiveCycle Data Service” Radio button being selected
    4. Uncheck “Create combined Java/Flex project using WTP” option.
  • Click Next to continue and below screen appears.configure-j2ee-server
  • Fill in the form as shown in below picture or snapshotconfigure-j2ee-server-step-2
  • For those who cannot see the above image, follow below steps
  • Server Location - Uncheck “Use default location”
  • Root directory - Browse through folder structure of your system to Web-Project’s “WebRoot” directory [Above created web project]
  • Root Url - type in the full fledge url to access the web project on server for me it was “http://localhost:8080/FlexSampleWeb “
  • Context Root - “/FlexSampleWeb” - if you have different context root, specify that here
  • Leave compilation options as is.
  • Compiled Flex application location - output folder - would have full path of WebRoot followed by “FlexSampleUi-debug”
  • Remove “FlexSampleUi-debug” and live it as shown in next snapshotconfigure-j2ee-server-step-3
  • Click Validate Configuration button to validate the configuration.
  • This operation will result in below snapshotconfigure-j2ee-server-step-4
  • Click Finish to complete Project creation and expand the directory structure in Navigator or File Explorer should look like belowflex-development
  • Click on Run Button selecting Flex Project to see that it opens up url “http://localhost:8080/FlexSampleWeb//FlexSampleUi.html”
  • The Screen should be empty as it has no source at all.
  • Now create a Java class called “HelloWorld” in “com.test” package in “FlexSampleWeb” Web Project
  • Copy the below code into the java file

    package com.test;
    import java.util.Date;

    public class HelloWorld
    {
    private String userSaid;

    public String repeat( String said )
    {
    this.userSaid = “Reply from server: ” + said;
    return this.userSaid;
    }

    public String sayHello()
    {
    Date now = new Date();
    return “Hello World ” + now;
    }
    }

  • Open Flex Mxml file and copy below code.

    <?xml version=”1.0″ encoding=”utf-8″?>

    <mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute”>

    <mx:RemoteObject id=”myservice” fault=”faultHandler(event)” showBusyCursor=”true” destination=”Hello”>

    <mx:method name=”sayHello” result=”resultHandler(event)” />

    <mx:method name=”repeat” result=”resultHandler(event)” />

    </mx:RemoteObject>

    <mx:Script>

    <![CDATA[

    import mx.managers.CursorManager;

    import mx.rpc.events.ResultEvent;

    import mx.rpc.events.FaultEvent;

    private function faultHandler(fault:FaultEvent):void

    {
    CursorManager.removeBusyCursor();
    result_text.text = "code:\n" + fault.fault.faultCode + "\n\nMessage:\n" + fault.fault.faultString + "\n\nDetail:\n" + fault.fault.faultDetail;
    }
    private function resultHandler(evt:ResultEvent):void
    {
    result_text.text = evt.message.body.toString(); // same as: evt.result.toString();
    }

    ]]>

    </mx:Script>

    <mx:Button x=”250″ y=”157″ label=”sayHello” width=”79″ click=”myservice.getOperation(’sayHello’).send();”/>

    <mx:Button x=”250″ y=”187″ label=”Repeat” click=”myservice.getOperation(’repeat’).send(myText.text); “/>

    <mx:TextArea x=”10″ y=”36″ width=”319″ height=”113″ id=”result_text”/>

    <mx:Label x=”10″ y=”10″ text=”Result:”/>

    <mx:TextInput x=”82″ y=”187″ id=”myText” text=”Sent to Server”/>

    </mx:Application>

  • BlazeDS server-side configuration:
    On the sever side, need to extend a BlazeDS configuration file to enable the Java service to be accessed later from the Flex client. Open the “remoting-config.xml” file in the project folder “FlexSampleWeb\WebRoot\WEB-INF\flex” and overwrite the content with the following:

    <?xml version=”1.0″ encoding=”UTF-8″?>
    <service id=”remoting-service”
    class=”flex.messaging.services.RemotingService”>

    <adapters>
    <adapter-definition id=”java-object” class=”flex.messaging.services.remoting.adapters.JavaAdapter” default=”true”/>
    </adapters>

    <default-channels>
    <channel ref=”my-amf”/>
    </default-channels>

    <!– Flex Demo application –>

    <destination id=”Hello”>
    <properties>
    <source>com.test.HelloWorld</source>
    </properties>
    </destination>

    </service>

  • Save, Select web project back, refresh once, it should deploy the latest files on web project,
  • And start the tomcat server.
  • Now by selecting Flex Project, click on Run button to see the flex application the screen shown in snapshot below appears.output
  • Click on say hello button to see its functionality
  • Type in some message in text box & click on Repeat button to see the same on text area, which is returned from server

Source, Reference and Credit : Srinivas’s Blog

S.Chandru Adobe Flex, Java

How Java Annotations Works

April 20th, 2009

java_annotationsThis article explains what are Java Annotations, How to define and use Java Annotation and how Java Annotations works. Java annotations are meta data provides data about a program that is not part of the program itself. They have no direct impact on the operations of the code they annotate. An annotation indicates that the declared element( can be field, class, method, package etc..,) should be processed in some special way by a compiler, development tool, deployment tool, or during runtime. To develop APIs require a fair amount of coding. For example, in order to write a JAX-RPC web service, we must provide a paired interface and implementation. This code could be generated automatically by a tool if the program were “decorated” with annotations indicating which methods were remotely accessible.

We can make our APIs less error-prone using annotations. Many APIs require additional files to be maintained in parallel with programs. For example, “JavaBean” requires a “AdditionalInfo” class to be maintained in parallel with it and Enterprise Java Bean (EJB) requires deployment descriptor.

The Java platform has always had various ad hoc annotation mechanisms. For example, the @deprecated javadoc tag is an ad hoc annotation indicating that the method should no longer be used, and the transient modifier is an ad hoc annotation indicating that the field should be ignored during serialization. Java 5.0 has general purpose annotatons (aka metadata) allows you to define and use your own annotation type. The facility consists of a syntax for declaring annotation types, a syntax for annotating declarations, APIs for reading annotations, a class file representation for annotations, and an annotation processing tool.

Annotation do not have direct impact on program semantics, but they do affect the way programs are treated by tools and libraries, which can in turn affect the semantics of the running program. Annotations can be read from source files, class files, or reflectively at run time. Annotations complement javadoc tags. In general, if the markup is intended to affect or produce documentation, it should probably be a javadoc tag; otherwise, it should be an annotation.

Annotation type declaration:

Annotation type declarations are similar to interface declarations. An at-sign (@) precedes the interface keyword. Each method declaration defines the element of the annotation type, and method must not have any parameters or any throw clause. Return types are restricted to primitives, String, enum, annotations and array of the mentioned types. Method can also have default values.

Here is an illustration to declare annotation type.

package com.thetechhournals.annotation;

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ChangeRequest
{
int    id();
String title();
String designer() default “[unassigned]“;
String status();    default “[unassigned]“;
}

The @interface in the code indicates that the interface itself is an annotation, It is required to be import java.lang.annotation package.

The next thing to be noted about the ChangeRequest annotation is @Retention(RetentionPolicy.RUNTIME) indicates that the @ChangeRequest is compiled into class file and made available to Java Virtual Machine at run time. This makes it possible for development tool to look for @ChangeRequest annotation through reflection at run time and to perform a specific task because the annotation was present in the code.

The other possible values for the @Retention annotation are:
  • The RetentionPolicy.SOURCE constant indicates that the annotation should be discarded by the compiler, and is usable by any development tools at coding time only.
  • The RetentionPolicy.CLASS constant indicates that the annotation is useful to the compiler, and should be retained in the .class file for use by the compiler at compile time.
Note: nless you are writing your own Java compiler, it is not possible to create your own useful compile-time annotations.

One more interesting part of the ChangeRequest annotation is @Target(ElementType.METHOD) indicates that the annotation should appear only on a method declaration but not on a class, a constructor, would generate a compiler error. It is possible to specify that an annotation appear on one or more elements within Java program, including on constructors, fields, local variables, method declarations, package declarations, parameter declarations; and class, interface, or enumeration declarations. Have look at below given example:

@Target({ElementType.CONSTRUCTOR,
ElementType.FIELD,
ElementType.METHOD,
ElementType.PACKAGE,
ElementType.TYPE})

How to use Java Annotation:

Once the annotation type is defined, you can use it to annotate declarations. An annotation is a special kind of modifier, and can be used anywhere that other modifiers (such as public, static, or final) can be used. By convention, annotations precede other modifiers. Annotations consist of an at-sign (@) followed by an annotation type and a parenthesized list of element-value pairs. The values must be compile-time constants. Here is a method declaration with an annotation corresponding to the annotation type declared above:

@ChangeRequest(
id    = 226724,
title = “Enable - Express shipping”,
designer = “S. Chandru”,
status = “Work in progress”
)
public boolean expressShipping(){…}

An annotation type with no elements is termed a marker annotation type, for example:

public @interface Basic{ }

It is permissible to omit the parentheses in marker annotations, as shown below:

@Basic
public class Shipping{ ... }

In annotations with a single element, the element should be named value, as shown below:

public @interface Copyright
{
    String value();
}

It is permissible to omit the element name and equals sign (=) in a single-element annotation whose element name is value, as shown below:

@Copyright("2009 The Tech Journals")
public class ShippingService{ ... }

How annotations works:

We will build small annotation-based MyAnnotation framework explain how annotation works. First let’s create a marker annotation type and should be run by the testing tool.

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation{ }

Note that the annotation type declaration is itself annotated. Such annotations are called meta-annotations. @Target(ElementType.METHOD) indicate that MyAnnotation should appear on methods and @Retention(RetentionPolicy.RUNTIME) make MyAnnotation available to JVM at run-time.

Here is sample program that uses the above defined annotation type.

package com.thetechjournals.annotation;

public class UsingAnnotation
{
@MyAnnotation
public static void use()
{
System.out.println(”I’m using annotations”);
}
public static void dontUse()
{
System.out.println(”I’m using annotations”);
}
}

and the testing tool:

import java.lang.reflect.*;

public class RunAnnotation
{
public static void main(String[] args) throws Exception
{
for (Method m : Class.forName(”com.thetechjournals.annotation.UsingAnnotation”).getMethods())
{
if (m.isAnnotationPresent(MyAnnotation.class))
{
System.out.println(”Annotated elements process in special way”);
m.invoke(null);
}
}
}
}

Using reflection we are dynamically loading UsingAnnotation class and iterates over all the methods of the class. Invoking each method that is annotated with the MyAnnotation annotation type. isAnnotationPresent( annotationType ) returns true if an annotation for the specified type is present on this element, else false. We can now process all the annotated elements in special way e.g., we can perform some operation before and after executing only annotated element.

Source and reference : Sun Official Site

S.Chandru Java , , ,

Interview Questions : OOPs and Core Java

April 16th, 2009

OOPS and CORE JAVA

1. What is JVM (Java Virtual Machine)?

a. JVM is software implementation which stands on top of the hardware platform and OS.  It provides abstraction compiled java program and the hardware and OS. The Java virtual machine executes instructions that a Java compiler generates. All the Java programs are compiled into bytecodes(.class files). JVM  interpret Java bytecodes into instructions understandable by the particular processor.

2. What is OOPs?

a. Object-Oriented Programming (OOP) is a programming language model orgnized around the “Objects” rather than the “actions” and data rather than the logic. Programming techniques may include data abstraction, encapsulation, inheritance, information hiding, modularity and polymorphism.

3. What is Class?

a. Class is a template that describes the kinds of state and behavior that object of its type supports.

4. What is Object?

a. Object is run time entity and will have its own state and access to all of its behaviors defined by its class. At run time when JVM encounters the “new” keyword , it will use appropriate class create a object which is instance its class.

5. What is Interface?

a. Interface is 100% abstract super class that defines the methods a subclass must support, but not how they supported. A powerful companion to inheritance is the use of Interfaces.

6. What is abstract class?

a. Abstract class can never be instantiated, its sole purpose is to be extended(to subclassed). It is incomplete class.

7. What is the purpose of abstract class?

a. Consider a abstract class represent Person, it has three methods “numOfEyes”, “numOfLegs” and “sex”. Now conceptually all humans have to two legs and two eyes, but sex is something which can vary from person to person. So write implementaton for methods “numOfEyes” and “numOfLegs” and leave the method “sex” implemetation to subclass. Now class Male and class Female extends Person, implementation for method “sex” of Female is implemented in class Female and of Male is implemented in class Male.

8. What are the abstract methods?

a. Abstract methods do not have implementation. Abstrct methods should be implemeted in the subclass which inherits them. The class inherits abstract class should implement all the abstract methods or else java compiler will throw an error. Abstract class can have abstract methods. Abstract methods defined using “abstract” keyword.

9. What is state (instance variables) in Java?

a. State (instance variables) Each object (instance of a class) will have its own unique set of instance variables as defined in the class. Collectively, the values assigned to an object’s instance variables make up the object’s state.

10. What is Behavior (methods) in Java?

a. Behavior (methods) When a programmer creates a class, she creates methods for that class. Methods are where the class’ logic is stored. Methods are where the real work gets done. They are where algorithms get executed, and data gets manipulated.

11. What is relation between Classes and Objects?

a. They look very much same but are not same. Class is a definition, while object is instance of the class created. Class is blue print or prototype while objects are actual existing in real world. For example  CAR is class and Mustang is object of the class.

12. What is the difference between “Abstract” classes and “Interfaces”?

a. Abstract classes can only be extended by any class while Interface can not be, it has to be, implemented. Interfaces can not implement methods, whereas an abstract class can have implementation. Class can implement any number of interfaces but only one super class.

13. What is difference between Static and Non-Static fields of class?

a. Static fields are fields per class whereas Non-Static fields are fields per object of the class. Non-Static values are called as instance variables. Each object of the class has its own copy of Non-Static instance variables. So when a new object is created of the same class it will have completely its own copy of instance variable. Where in Static values have only one copy of instance variables and will be shared among all the objects of the class.

14. What is use of “instanceof”  keyword?

a. “instanceof” keyword is used to check what is the type of the object.

15. How do refer to a current instance of object?

a. You can refer the current instance of object using this” keyword.

S.Chandru Java ,