Top Banner

of 122

java_intr_for_experts.pdf

Feb 10, 2018

Download

Documents

kadir.azam45
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 7/22/2019 java_intr_for_experts.pdf

    1/122

    Java programming languageThe Java programming language is a high-level language that can becharacterized by all of the following buzzwords:

    Simple Architectureneutral

    Objectoriented

    Portable

    Distributed Highperformance

    Multithreaded

    Robust

    Dynamic SecurePortable: Your applications are portable across multiple platforms.Write your applications once, and you never need to port themtheywill run without modification on multiple operating systems andhardware architectures.Robust: Your applications are robust because the Java run-time systemmanages memory for you. Because Java has inbuilt garbage collectorand type safety checks in code. The compiler restricts the typecompatibility when converting data from one type o another.High Performance: Your interactive graphical applications have highperformance because multiple concurrent threads of activity in yourapplication are supported by the multithreading built into the Javalanguage and runtime platform.Secure: Your end users can trust that your applications are secure,even though theyre downloading code from all over the Internet; theJava run-time system has built-in protection against viruses andtampering.

    Each of the preceding buzzwords is explained inThe Java LanguageEnvironment , a white paper written by James Gosling and HenryMcGilton.In the Java programming language, all source code is first written inplain text files ending with the .java extension. Those source files arethen compiled into .class files by the javac compiler. A .class file doesnot contain code that is native to your processor; it instead containsbytecodes the machine language of the Java Virtual Machine1 (Java

    VM). The java launcher tool then runs your application with an instanceof the Java Virtual Machine.

    http://java.sun.com/docs/white/langenv/http://java.sun.com/docs/white/langenv/http://var/www/apps/conversion/tmp/scratch_2/tutorial/getStarted/intro/definition.html#FOOThttp://java.sun.com/docs/white/langenv/http://java.sun.com/docs/white/langenv/http://var/www/apps/conversion/tmp/scratch_2/tutorial/getStarted/intro/definition.html#FOOT
  • 7/22/2019 java_intr_for_experts.pdf

    2/122

    An overview of the software development process.Because the Java VM is available on many different operating systems,the same .class files are capable of running on Microsoft Windows, theSolaris TM Operating System (Solaris OS), Linux, or Mac OS. Somevirtual machines, such as theJava HotSpot virtual machine, perform

    additional steps at runtime to give your application a performanceboost. This include various tasks such as finding performancebottlenecks and recompiling (to native code) frequently used sectionsof code.

    Through the Java VM, the same application is capable of running onmultiple platforms.

    The Java PlatformA platform is the hardware or software environment in which aprogram runs. We've already mentioned some of the most popular

    platforms like Microsoft Windows, Linux, Solaris OS, and Mac OS. Mostplatforms can be described as a combination of the operating systemand underlying hardware. The Java platform differs from most otherplatforms in that it's a software-only platform that runs on top of otherhardware-based platforms.The Java platform has two components:

    The Java Virtual Machine The Java Application Programming Interface (API)

    http://java.sun.com/products/hotspot/http://java.sun.com/products/hotspot/
  • 7/22/2019 java_intr_for_experts.pdf

    3/122

    You've already been introduced to the Java Virtual Machine; it's thebase for the Java platform and is ported onto various hardware-basedplatforms.The API is a large collection of ready-made software components thatprovide many useful capabilities. It is grouped into libraries of related

    classes and interfaces; these libraries are known as packages. Thenext section, What Can Java Technology Do? highlights some of thefunctionality provided by the API.

    The API and Java Virtual Machine insulate the program from the

    underlying hardware.As a platform-independent environment, the Java platform can be a bitslower than native code. However, advances in compiler and virtualmachine technologies are bringing performance close to that of nativecode without threatening portability.

    Why Strings have been made immutable?

    JVM internally maintains the "String Pool". To achieve the memoryefficiency, JVM will refer the String object from pool. It will not createthe new String objects. So, whenever you create a new string literal,JVM will check in the pool whether it already exists or not. If alreadypresent in the pool, just give the reference to the same object orcreate the new object in the pool. There will be many references pointto the same String objects, if someone changes the value, it will affectall the references. So, sun decided to make it immutable.

    It checks only for string literals. If you create a string with new operatorit does not check it directly creates new object.

    String.intern() method lets you the objects created using new operatorto be placed into string pool.

    http://var/www/apps/conversion/tmp/scratch_2/tutorial/getStarted/intro/cando.htmlhttp://var/www/apps/conversion/tmp/scratch_2/tutorial/getStarted/intro/cando.html
  • 7/22/2019 java_intr_for_experts.pdf

    4/122

    Primitive Data TypesThe Java programming language is statically-typed, which means thatall variables must first be declared before they can be used. Thisinvolves stating the variable's type and name, as you've already seen:

    int gear = 1;Doing so tells your program that a field named "gear" exists, holdsnumerical data, and has an initial value of "1". A variable's data typedetermines the values it may contain, plus the operations that may beperformed on it. In addition to int, the Java programming languagesupports seven other primitive data types. A primitive type ispredefined by the language and is named by a reserved keyword.Primitive values do not share state with other primitive values. Theeight primitive data types supported by the Java programminglanguage are:

    byte: The byte data type is an 8-bit signed two's complement

    integer. It has a minimum value of -128 and a maximum value of127 (inclusive). The byte data type can be useful for savingmemory in large arrays, where the memory savings actuallymatters. They can also be used in place of int where their limitshelp to clarify your code; the fact that a variable's range islimited can serve as a form of documentation.

    short: The short data type is a 16-bit signed two's complementinteger. It has a minimum value of -32,768 and a maximumvalue of 32,767 (inclusive). As with byte, the same guidelinesapply: you can use a short to save memory in large arrays, insituations where the memory savings actually matters.

    int: The int data type is a 32-bit signed two's complementinteger. It has a minimum value of -2,147,483,648 and amaximum value of 2,147,483,647 (inclusive). For integral values,this data type is generally the default choice unless there is areason (like the above) to choose something else. This data typewill most likely be large enough for the numbers your programwill use, but if you need a wider range of values, use longinstead.

    long: The long data type is a 64-bit signed two's complementinteger. It has a minimum value of -9,223,372,036,854,775,808and a maximum value of 9,223,372,036,854,775,807 (inclusive).

    Use this data type when you need a range of values wider thanthose provided by int.

    float: The float data type is a single-precision 32-bit IEEE 754floating point. Its range of values is beyond the scope of thisdiscussion, but is specified in section 4.2.3 of the Java LanguageSpecification. As with the recommendations for byte and short,use a float (instead of double) if you need to save memory inlarge arrays of floating point numbers. This data type should

    http://var/www/apps/conversion/tmp/scratch_2/tutorial/java/nutsandbolts/arrays.htmlhttp://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.3http://var/www/apps/conversion/tmp/scratch_2/tutorial/java/nutsandbolts/arrays.htmlhttp://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.3
  • 7/22/2019 java_intr_for_experts.pdf

    5/122

    never be used for precise values, such as currency. For that, youwill need to use thejava.math.BigDecimal class instead.Numbers and Strings covers BigDecimal and other useful classesprovided by the Java platform.

    double: The double data type is a double-precision 64-bit IEEE

    754 floating point. Its range of values is beyond the scope of thisdiscussion, but is specified in section 4.2.3 of the Java LanguageSpecification. For decimal values, this data type is generally thedefault choice. As mentioned above, this data type should neverbe used for precise values, such as currency.

    boolean: The boolean data type has only two possible values:true and false. Use this data type for simple flags that tracktrue/false conditions. This data type represents one bit ofinformation, but its "size" isn't something that's preciselydefined.

    char: The char data type is a single 16-bit Unicode character. It

    has a minimum value of '\u0000' (or 0) and a maximum value of'\uffff' (or 65,535 inclusive).

    In addition to the eight primitive data types listed above, the Javaprogramming language also provides special support for characterstrings via thejava.lang.String class. Enclosing your character stringwithin double quotes will automatically create a new String object; forexample, String s = "this is a string";. String objects are immutable,which means that once created, their values cannot be changed. TheString class is not technically a primitive data type, but considering thespecial support given to it by the language, you'll probably tend tothink of it as such. You'll learn more about the String class in Simple

    Data ObjectsDefault ValuesIt's not always necessary to assign a value when a field is declared.Fields that are declared but not initialized will be set to a reasonabledefault by the compiler. Generally speaking, this default will be zero ornull, depending on the data type. Relying on such default values,however, is generally considered bad programming style.The following chart summarizes the default values for the above datatypes.

    Data TypeDefault Value (forfields)

    byte 0

    short 0

    int 0

    long 0L

    float 0.0f

    double 0.0d

    http://download.oracle.com/javase/7/docs/api/java/math/BigDecimal.htmlhttp://var/www/apps/conversion/tmp/scratch_2/tutorial/java/data/index.htmlhttp://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.3http://download.oracle.com/javase/7/docs/api/java/lang/String.htmlhttp://var/www/apps/conversion/tmp/scratch_2/tutorial/java/data/index.htmlhttp://var/www/apps/conversion/tmp/scratch_2/tutorial/java/data/index.htmlhttp://download.oracle.com/javase/7/docs/api/java/math/BigDecimal.htmlhttp://var/www/apps/conversion/tmp/scratch_2/tutorial/java/data/index.htmlhttp://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.3http://download.oracle.com/javase/7/docs/api/java/lang/String.htmlhttp://var/www/apps/conversion/tmp/scratch_2/tutorial/java/data/index.htmlhttp://var/www/apps/conversion/tmp/scratch_2/tutorial/java/data/index.html
  • 7/22/2019 java_intr_for_experts.pdf

    6/122

    char '\u0000'

    String (or anyobject)

    null

    boolean false

    Local variables are slightly different; the compiler never assigns adefault value to an uninitialized local variable. If you cannot initializeyour local variable where it is declared, make sure to assign it a valuebefore you attempt to use it. Accessing an uninitialized local variablewill result in a compile-time error.LiteralsYou may have noticed that the new keyword isn't used wheninitializing a variable of a primitive type. Primitive types are specialdata types built into the language; they are not objects created from aclass. A literal is the source code representation of a fixed value;literals are represented directly in your code without requiringcomputation. As shown below, it's possible to assign a literal to avariable of a primitive type:boolean result = true;char capitalC = 'C';byte b = 100;short s = 10000;int i = 100000;double d = 23.45;float f = 23.45f;

    * If you assign 23.45 to a literal it takes it as a double value

    Class and Objects:

    Things an object knows about itself are called instance variables. Theyrepresent an objects state (the data), and can have unique values foreach object of that type. Things an object does are methods. Methodsoperate on data.

    A class is not an object but its used to construct them. A class is ablueprint for an object. It tells the virtual machine how to make an

    object of that particular type. Each object made from that class canhave its own values for the instance variables of that class.

    1. Object-oriented programming lets you extend a program withouthaving to touch previously tested, working code.

    2. All Java code is defined in a class.3. A class describes how to make an object of that class type. A

    class is like a blueprint.

  • 7/22/2019 java_intr_for_experts.pdf

    7/122

    4. An object can take care of itself; you dont have to know or carehow the object does it.

    5. An object knows things and does things. Things an object knowsabout itself are called instance variables. They represent thestate of an object. Things an object does are called methods.

    They represent the behavior of an object.6. A class can inherit instance variables and methods from a moreabstract superclass.

    7. At runtime, a Java program is nothing more than objects talkingto other objects.

    8. There is actually no such thing as an object variable. Theresonly an object reference variable.

    9. An object reference variable holds bits that represent a way toaccess an object.It doesnt hold the object itself, but it holdssomething like a pointer. Or an address. Except, in Java we dontreally know what is inside a reference variable. We do know that

    whatever it is, it represents one and only one object. And the JVMknows how to use the reference to get to the object.

    Garbage collector:

    Some object-oriented languages require that you keep track of all theobjects you create and that you explicitly destroy them when they areno longer needed. Managing memory explicitly is tedious and error-prone. The Java platform allows you to create as many objects as youwant (limited, of course, by what your system can handle), and you

    don't have to worry about destroying them. The Java runtimeenvironment deletes objects when it determines that they are nolonger being used. This process is called garbage collection.An object is eligible for garbage collection when there are no morereferences to that object. References that are held in a variable areusually dropped when the variable goes out of scope. Or, you canexplicitly drop an object reference by setting the variable to the specialvalue null. Remember that a program can have multiple references tothe same object; all references to an object must be dropped beforethe object is eligible for garbage collection.The Java runtime environment has a garbage collector that periodically

    frees the memory used by objects that are no longer referenced. Thegarbage collector does its job automatically when it determines thatthe time is right.

    Java takes out the Garbage: Each time an object is created in Java, itgoes into an area of memory known as The Heap. All objectsnomatter when, where, or how theyre created live on the heap. But itsno t just any old memory heap; the Java heap is actually called the

  • 7/22/2019 java_intr_for_experts.pdf

    8/122

    Garbage-Collectible Heap. When you create an object, Java allocatesmemory space on the heap according to how much that particularobject needs. An object with , say, 15 instance variables, will probablyneed more space than an object with only two instance variables. Butwhat happens when you need to reclaim that space ? How do you get

    an object out of the heap when youre done with it? Java manages thatmemory for you! When the JV M can see that an object can never beused again, that object becomes eligible for garbage collection. And ifyoure running low on memory, the Garbage Collector will run, throwout the un reachable objects, and free up the space, so that the spacecanbe reused.

    Reference variables:All references for a given JVM will be the same size regardless of the

    objects they reference, but each JVM might have a different way ofrepresenting references, so references on one JVM may be smaller orlarger than references on another JVM.How big the reference variable is? You dont know. Unless youre cozywith someone on the JVMs development team, you dont know how areference is represented. There are pointers in there somewhere, butyou cant access them. You wont need to. (OK, if you insist, you mightas well just imagine it to be a 64-bit value.) But when youre talkingabout memory allocation issues, your Big Concern should be abouthow many objects (as opposed to object references) youre creating,and how big they (the objects) really are.

    1. Unreachable objects are eligible for garbage collection2. The final variables are not allowed to be assigned again.3. Variables come in two flavors: primitive and reference.4. Variables must always be declared with a name and a type.5. A primitive variable value is the bits representing the value (5,

    a, true, 3.1416, etc.).6. A reference variable value is the bits representing a way to get

    to an object on the heap.7. A reference variable is like a remote control. Using the dot

    operator (.) on a reference variable is like pressing a button on

    the remote control to access a method or instance variable.8. A reference variable has a value of null when it is not referencing

    any object.9. An array is always an object, even if the array is declared to hold

    primitives. There is no such thing as a primitive array, only anarray that holds primitives.

    Difference between instance variables and local variables

  • 7/22/2019 java_intr_for_experts.pdf

    9/122

    Instance variables are declared within the class. Instance variablesalways get a default value if you dont explicitly set a value.Integers ------ 0Floating points --------- 0.0

    Boolean ------ falseReferences--- null

    Local variables are declared within the method. They dont get adefault value if you dont assign a value. They must be initializedbefore they are used. The compiler complains you if you use the localvariables before they are initialized.

    Public void change(){Int x;Int y = x + 4; //error

    X = 10;Int z = x + 4;//Okay

    }

    Method parameters are virtually the same as local variablestheyredeclared inside the method (well, technically theyre declared in theargument list of the method rather than within the body of the method,but theyre still local variables as opposed to instance variables). Butmethod parameterswill never be uninitialized, so youll never get a compiler error tellingyou that a parameter variable might not have been initialized.

    Comparison:The == compares between primitive values. It compares bits withinthe variables.And if the two reference variables are refereeing same object on theheap, == returns true.Foo a = new Foo();Foo b = new Foo();Foo c = a;if (a == b) { // false }if (a == c) { // true }if (b == c) { // false }

    Pass by Value: Java is a pass by value that means pass by copy. Whenthe variables are passed to the methods the bits representing valuesare get actually copied and copies will be passed instead of originals.In the case of primitives the bits are copied and copies are sent tomethod and the original values are remains same after the completionof method execution even though the parameters of the method have

  • 7/22/2019 java_intr_for_experts.pdf

    10/122

    been changed inside the method. The method cant change the bitsthat were in the calling variable.In the case of reference variables, the copies of reference variables aresent to the method. And both the original and copy referring to thesame object in the heap, the modification made on the state of objects

    during the method execution can be accessed by the original referencevariable too.

    class PassByCopyTest{

    static void change(int y){y = y + 10;

    }

    static void change(A obj){obj.x = 15;

    }public static void main(String[] args){

    System.out.println("Pass by copy example");int a = 20;System.out.println("Primitive variable after change: "+a);change(a);System.out.println("Primitive variable after change: "+a);

    A obj = new A();obj.x = 30;

    System.out.println("Object state before change : "+obj.x);change(obj);System.out.println("Object state after change : "+obj.x);

    }}class A{

    int x = 20;}

    ---------- run ----------Pass by copy examplePrimitive variable after change: 20Primitive variable after change: 20Object state before change : 30Object state after change : 15

  • 7/22/2019 java_intr_for_experts.pdf

    11/122

    ArraysArrays are always objects, whether theyre declared to hold primitivesor object references. But you can have an array object thats declaredto hold primitive values. In other words, the array object can haveelements which are primitives, but the array itself is never a primitive.

    Regardless of what the array holds, the array itself is always anobject!. Array of references hold references not objects. Every elementin an array is just a variable. In other words, one of the eight primitivevariable types (think: Large Furry Dog) or a reference variable.Anything you would put in a variable of that type can be assigned to anarray element of that type. So in an array of type int (int[]), eachelement can hold an int. In a Dog array (Dog[]) each element canhold... a Dog? No, remember that a reference variable just holds areference (a remote control), not the object itself. So in a Dog array,each element can hold a remote control to a Dog.

    Encapsulation:Encapsulation is nothing but hiding the details.Encapsulation puts a force-field around my instance variables, sonobody can set them to, lets say, something inappropriate. It is goodpractice, make the instance variables as private and provide publicsetter and getter methods to access them.

    Inheritance1. A subclass extends a superclass.2. A subclass inherits all public instance variables and methods of

    the superclass, but

    3. does not inherit the private instance variables and methods ofthe superclass.

    4. Inherited methods can be overridden; instance variables cannotbe overridden (although they can be redefined in the subclass,but thats not the same thing, and theres almost never a needto do it.)

    5. Use the IS-A test to verify that your inheritance hierarchy is valid.If X extends Y,

    6. then X IS-A Y must make sense.7. The IS-A relationship works in only one direction. A Hippo is an

    Animal, but not all

    8. Animals are Hippos.9. When a method is overridden in a subclass, and that method is

    invoked on an instance of10. the subclass, the overridden version of the method is called. (The

    lowest one wins.)11. If class B extends A, and C extends B, class B IS-A class A,

    and class C IS-A class B, and class C also IS-A class A.What does all this inheritance buy you:

  • 7/22/2019 java_intr_for_experts.pdf

    12/122

  • 7/22/2019 java_intr_for_experts.pdf

    13/122

    }}

    class OverridingTest extends A

    { A one(){return new OverridingTest();

    }public static void main(String[] args){

    System.out.println("Hello World!");}

    }

    ---------- compile ----------

    OverridingTest.java:11: one() in OverridingTest cannot overrideone() in A; attempting to use incompatible return typefound : Arequired: OverridingTest

    A one(){^

    1 error

    Output completed (0 sec consumed)

    Success case:

    class A{

    A one(){return new OverridingTest();

    }}

    class OverridingTest extends A

    {OverridingTest one(){

    return new OverridingTest();}public static void main(String[] args){

    System.out.println("Hello World!");}

    }

  • 7/22/2019 java_intr_for_experts.pdf

    14/122

    2. The method cant be less accessible.The access modifier of overridden method in subclass cant beless than that of the overridden method in superclass.Order of access modifiers : private, default, protected, publicError case

    class A{public A one(){

    return new OverridingTest();}

    }

    class OverridingTest extends A

    {OverridingTest one(){ //OverridingTest.java:11: one() in

    OverridingTest cannot override one() //in A; attempting to assignweaker access privileges; was public

    return new OverridingTest();}public static void main(String[] args){

    System.out.println("Hello World!");}

    }Success case:

    class A{

    A one(A a ){return new OverridingTest();

    }

    A one(OverridingTest a){return new OverridingTest();

    }}//Arguments types are not exactly same.

    3. The throws clause: Every method has RutimeException(unchecked exception) in its throws clause by default. Sub classmethod should not define checked exception in throws clause ifthe super class method didnt. Sub class method can throw itssub class exception not super class exception.

    4. The overriding method (sub class) CAN throw any unchecked(runtime) exception, regardless of whether the overriddenmethod declares the exception. (More in Chapter 5.)

  • 7/22/2019 java_intr_for_experts.pdf

    15/122

    5. The overriding method must NOT throw checked exceptionsthat are new or broader than those declared by the overriddenmethod. For example, a method that declares aFileNotFoundException cannot be overridden by a method thatdeclares a SQLException, Exception, or any other non-runtime

    exception unless it's a subclass of FileNotFoundException.

    6. The overriding method can throw narrower or fewerexceptions. Just because an overridden method "takes risks"doesn't mean that the overriding subclass' exception takes thesame risks. Bottom line: an overriding method doesn't have todeclare any exceptions that it will never throw, regardless ofwhat the overridden method declares.

    Overloading: Method overloading is nothing more than having two

    methods with the same name but different argument lists. Theres nopolymorphism involved with overloaded methods! Overloading lets youmake multiple versions of a method, with different argument lists

    1. The return types can be different.Youre free to change the return types in overloaded methods, as longas the argument lists are different.2. You cant change ONLY the return type.If only the return type is different, its not a valid overloadthecompiler will assume youre trying to override the method. And eventhat wont be legal unless the return type is a subtype of the return

    type declared in the superclass. To overload a method, you MUSTchange the argument list, although you can change the return type toanything.3. You can vary the access levels in any direction.Youre free to overload a method with a method thats more restrictive.It doesnt matter, since the new method isnt obligated to fulfill thecontract of the overloaded method.

    class A{

    A one(){

    return new OverridingTest();}

    OverridingTest one(){ //OverridingTest.java:7: one() is alreadydefined in A

    return new OverridingTest();}

    }

  • 7/22/2019 java_intr_for_experts.pdf

    16/122

    FinalFinal classes and methods provide security. If you need security ofknowing that the methods will always work the way that you wrotethem (because they cant be overridden), a final will help us.

    If you want to protect a specific method from being overridden, markthe method with the final modifier. Mark the whole class as final if youwant to guarantee that none of the methods in that class will ever beoverridden.

    Abstract class: Consider a scenario where Animal is the super class forTiger, Lion and Wolf.We can create objects for Tiger, Lion and Wolf. We cant create objectfor Animal. Because we dont know what color, size and how many oflegs the animal has.

    ENCAPSULATION (data hiding)The technique of hiding the internal implementation detail of an

    object from its external views.Internal structure remains private and services can be accessed byother objects only through messages passed via a clearly definedinterface. Encapsulation ensures that the object providing service canprevent other objects from manipulating its data or proceduresdirectly, and it enables the object requesting service to ignore thedetails of how that service is provided.

    Access specifiers:Protected:The sub class can access protected members of super class onlythrough the inheritance.Once the subclass-outside-the-package inherits the protected member,that member (as inherited by the subclass) becomes private to anycode outside the subclass, with the exception of subclasses of thesubclass.The protected members become private to the subclass and itssubclasses. The bottom line: when a subclass-outside-the-packageinherits a protected member, the member is essentially private inside

    the subclass, such that only the subclass and its subclasses can accessit through the inheritance.

    For years, object-oriented programmers knew that one of the mainOOP features is encapsulation: an ability to hide and protect objectinternals. Private and protected properties were invented to supportthis. But who are we hiding from? From stupid developers who willdecide to use our smart framework classes.

  • 7/22/2019 java_intr_for_experts.pdf

    17/122

    The Private and Protected section of the classes you design shouldcontain

    Abstraction

    "java abstraction is data hiding concepts" this is completely incorrect.Encapsulation is used for data hiding not abstraction. Abstraction is adesign concept on which we only declare functionality doesn't define itbecause we don't know about them at design point. For example if youare designing Server Class you know that there must be start() andstop() method but you don't know the exact way each server will startand stop because that will vary from server to server, so in this casewe will declare Server as abstract. In Java abstraction is implementedusing either abstract class or interface. Interface achieves 100%abstractness.

    what is abstraction ?

    something which is not concrete , something which is incomplete.

    java has concept of abstract classes , abstract method but a variable

    can not be abstract.

    an abstract class is something which is incomplete and you can not

    create instance of it for using it.if you want to use it you need to make

    it complete by extending it.

    an abstract method in java doesn't have body , its just a declaration.

    so when do you use abstraction ? ( most important in my view )

    when I know something needs to be there but I am not sure how

    exactly it should look like.

    e.g. when I am creating a class called Vehicle, I know there should bemethods like start() and Stop() but don't know start and stop

    mechanism of every vehicle since they could have different start and

    stop mechanism e..g some can be started by kick or some can be by

    pressing buttons .

  • 7/22/2019 java_intr_for_experts.pdf

    18/122

    the same concept apply to interface also , which we will discuss in

    some other post.

    so implementation of those start() and stop() methods should be left to

    there concrete implementation e.g. Scooter , MotorBike , Car etc.

    In Java Interface is an another way of providing abstraction, Interfaces

    are by default abstract and only contains public static final constant or

    abstract methods. Its very common interview question is that where

    should we use abstract class and where should we use Java Interfaces

    in my view this is important to understand to design better java

    application, you can go for java interface if you only know the name of

    methods your class should have e.g. for Server it should have start()and stop() method but we don't know how exactly these start and stop

    method will work. if you know some of the behavior while designing

    class and that would remain common across all subclasses add that

    into abstract class.

    InterfacesAn interface is a contract between a class and the outside world. Whena class implements an interface, it promises to provide the behaviorpublished by that interface.

    Implementing an interface allows a class to become more formal aboutthe behavior it promises to provide. Interfaces form a contract betweenthe class and the outside world, and this contract is enforced at buildtime by the compiler. If your class claims to implement an interface, allmethods defined by that interface must appear in its source codebefore the class will successfully compile.

    1. Interface is 100 % abstract.2. Interfaces increase the abstractness by moving one step further

    when compare to abstract class and only allows to declare

    abstract methods and their implementation.3. Interfaces are implicitly abstract.4. Interface methods are by default public and abstract, they can

    not be static, native and strictfp.5. All the member variables in interface are constants, public ,

    static and final.

  • 7/22/2019 java_intr_for_experts.pdf

    19/122

    Difference between String, StringBuffer and StringBuilder

    Methods in String produce new objects rather than modifying the sameobject. So String is immutable(unchanged). String buffer and Stringbuilder is mutable(can be changed). And StringBuffer is thread safe

    (synchronized). StringBuilder is not.

    Nested classesNested classes are divided into two categories: static and non-static.Nested classes that are declared static are simply called static nestedclasses. Non-static nested classes are called inner classes.

    A nested class is a member of its enclosing class. Non-static nestedclasses (inner classes) have access to other members of the enclosingclass, even if they are declared private. Static nested classes do nothave access to other members of the enclosing class. As a member of

    the OuterClass, a nested class can be declared private, public,protected, or package private. (Recall that outer classes can only bedeclared public or package private.)

    Inner classes:1. Inner classes cant have main method to run, because a regular

    inner class can't have static declarations of any kind. The onlyway you can access the inner class is through a live instance ofthe outer class! In other words, only at runtime when there'salready an instance of the outer class to tie the inner classinstance to.

    2. Since being a member of outer class, Inner class can access themembers of outer class even they are private.

    3. Inner class objects always have tied with outer class object. Tocreate an instance of an inner class, you must have an instanceof the outer class to tie to the inner class. There are noexceptions to this rule: an inner class instance can never standalone without a direct relationship to an instance of the outerclass.

    4. You always need to create instance for inner class before youusing the members. Declaring the inner class does not meantthat outer class has a object of inner class.

    5. Inner classes are basically designed to be helper classes forOuter classes.

    6. Sample

    publicclass Outer {

    class Inner{

  • 7/22/2019 java_intr_for_experts.pdf

    20/122

    void display(){System.out.println("Welcome to Inner classes");

    }}

    void showMsg(){Inner inner = new Inner();//Outer.Inner inner1 = this.new Inner();inner.display();

    }

    publicstaticvoid main(String[] args) {Outer.Inner inner = new Outer().new Inner();inner.display();

    }}

    7. Member Modifiers Applied to Inner Classes A regular inner class is amember of the outer class just as instance variables and methods are,so the following modifiers can be applied to an inner class:

    1. I final2. I abstract3. I public4. I private5. I protected6. I staticbut static turns it into a static nested class not an inner

    class7. I strictfp

    Method local Inner Class & Anonymous Inner Class

    Both the classes cannot access outside method local variables unlessthey are final. You must create an instance of this inner class beforeyou use it.

    Static Inner ClassesA static nested class is simply a class that's a static member of theenclosing class:

    The class itself isn't really "static"; there's no such thing as a staticclass. The static modifier in this case says that the nested class is astatic member of the outer class. That means it can be accessed, aswith other static members, without having an instance of the outerclass. Just as a static method does not have access to the instancevariables and nonstatic methods of the class, a static nested class doesnot have access to the instance variables and nonstatic methods of the

  • 7/22/2019 java_intr_for_experts.pdf

    21/122

    outer class. Look for static nested classes with code that behaves like anonstatic (regular inner) class.

    Inner Class Static InnerClass

    MethodLocal InnerClass

    AnonymousInner class

    Can havedeclarationof any kindstatic

    No yes No No

    Can beinstantiated

    from outsideof class ofouter class

    Yes Yes No No

    Can becreated in amethod

    No No Yes Yes

    Enume

    You should use enum types any time you need to represent a fixed set of constants.

    Java programming language enum types are much more powerful thantheir counterparts in other languages. The enu mdeclaration defines a class(called an enum type). The enum class body can include methods andother fields. The compiler automatically adds some special methodswhen it creates an enum. For example, they have a static valumethod thatreturns an array containing all of the values of the enum in the orderthey are declared. This method is commonly used in combination withthe for-each construct to iterate over the values of an enum type.

    The constructor for an enum type must be package-private or private access. Itautomatically creates the constants that are defined at the beginning of the enum body.You cannot invoke an enum constructor yourself.

    Allenums implicitly extend java.lang.En. Since Java does not support multiple inheritance, an enum

    cannot extend anything else.

    publicenum Day {

  • 7/22/2019 java_intr_for_experts.pdf

    22/122

    MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4),FRIDAY(5), SATURDAY(6), SUNDAY(7);

    privateintday;

    private Day(int day){this.setDay(day);

    }

    @Deprecatedpublicvoid setDay(int day) {

    this.day = day;}

    publicint getDay() {

    returnday;}

    publicstatic Day getDay(int day){Day d = null;for(Day d1 : values()){

    if(d1.getDay() == day){d = d1;break;

    }}

    return d;}

    }

    Shutdown HookIn many circumstances, you need a chance to do some clean-up whenthe user shuts down your application. The problem is, the user doesnot always follow the recommended procedure to exit. Java providesan elegant way for programmers to execute code in the middle of theshutdown process, thus making sure your clean-up code is alwaysexecuted. This article shows how to use a shutdown hook to guarantee

    that clean-up code is always run, regardless of how the userterminates the application.

    You may have code that must run just before an applicationcompletely exits. For example, if you are writing a text editor withSwing and your application creates a temporary edit file when it starts,this temporary file must be deleted when the user closes yourapplication. If you are writing a servlet container such as Tomcat or

  • 7/22/2019 java_intr_for_experts.pdf

    23/122

    Jetty, you must call the destroy method of all loaded servlets beforethe application shuts down.

    In many cases, you rely on the user to close the application asprescribed. For instance, in the first example, you may provide a

    JButton that, when clicked, runs the clean up code before exiting.Alternatively, you may use a Window listener that listens to thewindowClosing event. Tomcat uses a batch file that can be executedfor a proper shutdown. However, you know that the user is the king; heor she can do whatever they want with the application. He or shemight be nice enough to follow your instruction, but could just closethe console or log off of the system without first closing yourapplication.

    In Java, the virtual machine shuts down itself in response to two typesof events: first, when the application exits normally, by calling the

    System.exit method or when the last non-daemon thread exits.Second, when the user abruptly forces the virtual machine toterminate; for example, by typing Ctrl+C or logging off from thesystem before closing a running Java program.

    Fortunately, the virtual machine follows this two-phase sequence whenshutting down:

    1. The virtual machine starts all registered shutdown hooks, if any.Shutdown hooks are threads registered with the Runtime. Allshutdown hooks are run concurrently until they finish.

    2. The virtual machine calls all uninvoked finalizers, if appropriate.In this article, we are interested in the first phase, because it allows theprogrammer to ask the virtual machine to execute some clean-up codein the program. A shutdown hook is simply an instance of a subclass ofthe Thread class. Creating a shutdown hook is simple:

    1. Write a class extending the Thread class.2. Provide the implementation of your class' run method. This

    method is the code that needs to be run when the application isshut down, either normally or abruptly.

    3. In your application, instantiate your shutdown hook class.4. Register the shutdown hook with the current runtime'saddShutdownHook method.

    As you may have noticed, you don't start the shutdown hook as youwould other threads. The virtual machine will start and run yourshutdown hook when it runs its shutdown sequence.

    The code in Listing 1 provides a simple class called

  • 7/22/2019 java_intr_for_experts.pdf

    24/122

    ShutdownHookDemo and a subclass of Thread named ShutdownHook.Note that the run method of the ShutdownHook class simply prints thestring "Shutting down" to the console. Of course, you can insert anycode that needs to be run before the shutdown.

    After instantiation of the public class, its start method is called. Thestart method creates a shutdown hook and registers it with the currentruntime.

    ShutdownHook shutdownHook = new ShutdownHook();Runtime.getRuntime().addShutdownHook(shutdownHook);Then, the program waits for the user to press Enter.

    System.in.read();When the user does press Enter, the program exits. However, thevirtual machine will run the shutdown hook, printing the words

    "Shutting down."

    Listing 1: Using ShutdownHook

    package test;

    public class ShutdownHookDemo {public void start() {

    System.out.println("Demo");ShutdownHook shutdownHook = new ShutdownHook();

    Runtime.getRuntime().addShutdownHook(shutdownHook);}

    public static void main(String[] args) {ShutdownHookDemo demo = new ShutdownHookDemo();demo.start();try {

    System.in.read();}catch(Exception e) {}

    }}

    class ShutdownHook extends Thread {public void run() {

    System.out.println("Shutting down");}

    }

  • 7/22/2019 java_intr_for_experts.pdf

    25/122

    As another example, consider a simple Swing application whose classis called MySwingApp (see Figure 1). This application creates atemporary file when it is launched. When closed, the temporary filemust be deleted. The code for this class is given in Listing 2 on thefollowing page.

    Figure 1: A simple Swing application

    package test;

    import java.awt.*;import javax.swing.*;import java.awt.event.*;import java.io.File;import java.io.IOException;

    public class MySwingApp extends JFrame {JButton exitButton = new JButton();JTextArea jTextArea1 = new JTextArea();

    String dir = System.getProperty("user.dir");String filename = "temp.txt";

    public MySwingApp() {exitButton.setText("Exit");exitButton.setBounds(new Rectangle(304, 248, 76, 37));exitButton.addActionListener(new java.awt.event.ActionListener()

    {public void actionPerformed(ActionEvent e) {

    exitButton_actionPerformed(e);}

    });

    this.getContentPane().setLayout(null);jTextArea1.setText("Click the Exit button to quit");jTextArea1.setBounds(new Rectangle(9, 7, 371, 235));this.getContentPane().add(exitButton, null);this.getContentPane().add(jTextArea1, null);this.setDefaultCloseOperation(EXIT_ON_CLOSE);

    http://onjava.com/pub/a/onjava/2003/03/26/shutdownhook.html?page=2http://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/pub/a/onjava/2003/03/26/shutdownhook.html?page=2http://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3E
  • 7/22/2019 java_intr_for_experts.pdf

    26/122

  • 7/22/2019 java_intr_for_experts.pdf

    27/122

    System.out.println("Creating temporary file");file.createNewFile();

    }catch (IOException e) {

    System.out.println("Failed creating temporary file.");

    }}When the user closes the application, the application must delete thetemporary file. We hope that the user will always click the Exit button--by doing so, the shutdown method (which deletes the temporary file)will always be called. However, the temporary file will not be deleted ifthe user closes the application, by clicking the X button of the frame orby some other means.

    Listing 3 offers a solution to this. It modifies the code in Listing 2 byproviding a shutdown hook. The shutdown hook class is declared as an

    inner class so that it has access to all of the methods of the main class.In Listing 3, the shutdown hook's run method calls the shutdownmethod, guaranteeing that this method will be invoked when thevirtual machine shuts down.

    Listing 3: Using a shutdown hook in the Swing application

    package test;

    import java.awt.*;

    import javax.swing.*;import java.awt.event.*;import java.io.File;import java.io.IOException;

    public class MySwingAppWithShutdownHook extends JFrame {JButton exitButton = new JButton();JTextArea jTextArea1 = new JTextArea();

    String dir = System.getProperty("user.dir");String filename = "temp.txt";

    public MySwingAppWithShutdownHook() {exitButton.setText("Exit");exitButton.setBounds(new Rectangle(304, 248, 76, 37));exitButton.addActionListener(new java.awt.event.ActionListener()

    {public void actionPerformed(ActionEvent e) {

    exitButton_actionPerformed(e);

    http://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3Ehttp://onjava.com/onjava/2003/03/26/%3C!--CS_NEXT_REF--%3E
  • 7/22/2019 java_intr_for_experts.pdf

    28/122

    }});

    this.getContentPane().setLayout(null);jTextArea1.setText("Click the Exit button to quit");

    jTextArea1.setBounds(new Rectangle(9, 7, 371, 235));this.getContentPane().add(exitButton, null);this.getContentPane().add(jTextArea1, null);this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.setBounds(0,0, 400, 330);this.setVisible(true);initialize();

    }

    private void initialize() {// add shutdown hook

    MyShutdownHook shutdownHook = new MyShutdownHook();Runtime.getRuntime().addShutdownHook(shutdownHook);

    // create a temp fileFile file = new File(dir, filename);

    try {System.out.println("Creating temporary file");file.createNewFile();

    }catch (IOException e) {

    System.out.println("Failed creating temporary file.");}

    }

    private void shutdown() {// delete the temp fileFile file = new File(dir, filename);

    if (file.exists()) {System.out.println("Deleting temporary file.");file.delete();

    }}

    void exitButton_actionPerformed(ActionEvent e) {shutdown();System.exit(0);

    }

  • 7/22/2019 java_intr_for_experts.pdf

    29/122

    public static void main(String[] args) {MySwingAppWithShutdownHook mySwingApp = new

    MySwingAppWithShutdownHook();}

    private class MyShutdownHook extends Thread {public void run() {shutdown();

    }}

    }Pay special attention to the initialize method in the class shown inListing 3. The first thing it does is to create an instance of the innerclass MyShutdownHook, which extends a Thread:

    // add shutdown hook

    MyShutdownHook shutdownHook = new MyShutdownHook();Once you get an instance of the MyShutdownHook class, pass it to theaddShutDownHook method of the Runtime, as in the following line:

    Runtime.getRuntime().addShutdownHook(shutdownHook);The rest of the initialize method is similar to the initialize method in theclass given in Listing 2. It creates a temporary file and prints a string"Creating temporary file":

    // create a temp fileFile file = new File(dir, filename);

    try {System.out.println("Creating temporary file");file.createNewFile();

    }catch (IOException e) {

    System.out.println("Failed creating temporary file.");}Now, start the small application given in Listing 3. Check that thetemporary file is always deleted, even if you abruptly shut down theapplication.

    Summary

    Sometimes we want our application to run some clean-up code prior toshutting down. However, it is impossible to rely on the user to alwaysquit properly. The shutdown hook described in this article offers asolution that guarantees that the clean-up code is run, regardless of

  • 7/22/2019 java_intr_for_experts.pdf

    30/122

    how the user closes the application.

    Q: What is OOPS, object and class.

    A: OOPS provide the way of modularizing the program by creatingpartitioned memory area for both data and operations.OOPS allows describing the problem in terms of problem rather than interms of computer where the solution will run and follows bottom-upapproach in design.Objects are run time entities (physical entities) represent the realworld entities. That has both data and operations to manipulate data.We can make request to object asking it to perform its operations bysending messages (making a call to method of object). Each objectoccupies its own memory.Thats the way all object are communicate each other through sending

    message. Object is an entity, we can feel and touch. Objects are reallyexisted in real world.In theory the conceptual concept of problem is represented as object inproblem space.Class is user defined data type that represents the logical idea of realworld entity and describes the properties and behavior of real worldentity. Class is blue print or plan, we cant feel and touch. Classes arenot existed in real world.Q. What is inheritance?A. Is the process by which an object can acquires the properties ofanother object. Inheritance allows the creation of hierarchical

    classification. Which defines an interface is common for a set of relateditems. Which provides is-a relationship between classes. For example ATriangle is a Shape. A class is inherited is called superclass and a classdoes inheriting is called subclass. The main goal of inheritance is toprovide code reusability.a) All the messages send to object of superclass can also send tosubclass.b) We can add additional features to the existing type with outdisturbing it.c) We can change the behavior of new class. This is called overriding. Itmeans we are using same interface as existing type, but we are

    making it something different for new type.Q:

    What is the difference between an Interface and an Abstract class?

    A:An abstract class provides common interface for all its subclasses.And this common interface expressed differently in sub classes. Anabstract class is a class that is declared abstractit may or may notinclude abstract methods. When an abstract class is subclassed, thesubclass usually provides implementations for all of the abstract

  • 7/22/2019 java_intr_for_experts.pdf

    31/122

    methods in its parent class. However, if it does not, the subclassmust also be declared abstract. Abstract classes are similar tointerfaces, except that they provide a partial implementation, leavingit to subclasses to complete the implementation.An abstract class can have instance methods, instance variables

    that implement a default behavior. Abstract class may also containabstract methods which has no implementation. An abstract classmay have static fields and static methods. You can use these staticmembers with a class referencefor example,AbstractClass.staticMethod()as you would with any other class. Anabstract class can not be instantiated. And may refer the sub classsobjects.Any class with an abstract method is automatically abstract itself,

    and must be declared as such.A class may be declared abstract even if it has no abstract methods.This prevents it from being instantiated.

    An abstract class is a class which may have the usual flavors of classmembers (private, protected, etc.), but has some abstract methodswhich are not private.

    abstract class GraphicObject {int x, y;

    ...void moveTo(int newX, int newY) {

    ...}abstract void draw();abstract void resize();

    }class Circle extends GraphicObject {

    void draw() {...

    }

    void resize() {...

    }}class Rectangle extends GraphicObject {

    void draw() {...

    }

  • 7/22/2019 java_intr_for_experts.pdf

    32/122

  • 7/22/2019 java_intr_for_experts.pdf

    33/122

    the various objects are all of-a-kind, and share a common state andbehavior, then tend towards a common base class(abstract class). Ifall they share is a set of method signatures, then tend towards aninterface.When to choose

    Choosing interfaces and abstract classes is not an either/orproposition. If you need to change your design frequently, make it an

    interface. However, you may have abstract classes that provide

    some default behavior. Abstract classes are excellent candidates

    inside of application frameworks.

    Abstract classes let you define some behaviors; they force your

    subclasses to provide others. For example, if you have an application

    framework, an abstract class may provide default services such as

    event and message handling. Those services allow your application

    to plug in to your application framework.

    Q. Difference between Overloading and overriding

    A. Using the same name for operations on different types is calledoverloading. Method overloading allows several methods to share thesame name but with a different set of parameters (does not depend onreturn type).Each overloaded method performs a similar task. Overloaded methodsare normally used to perform similar operations that involve differentprogramming logic on different data types. Overloading occurs within aclass.Another common use of overloading is when defining constructors:public Time( ) //default constructorpublic Time( int hr, int min, int sec ) //general constructorpublic Time( Time time ) //copy constructorOverriding is similar to overloading, with the exception that it occursbetween classes and each method has the same signature. Aninstance method in a subclass with the same signature (name, plus the

    number and the type of its parameters) and return type as an instancemethod in the superclass overrides the superclass's method.A subclasscan override a superclass method by redefining that method. When themethod is mentioned by name in the subclass, then the subclassversion is automatically used.Overloading deals with multiple methods in the same class with thesame name but different signatures. Overriding deals with two

  • 7/22/2019 java_intr_for_experts.pdf

    34/122

    methods, one in a parent class and one in a child class that have thesame signature.Overloading lets you define a similar operation in different ways fordifferent data. Overriding lets you define a similar operation indifferent ways for different object types.

    Instance method cannot override the static methods and vice-versa.While overriding be care of weaker privileges (The method must havehigher access specifier than that of in super class).Q:

    What is the purpose of garbage collection in Java, and when is itused?

    A:The purpose of garbage collection is to identify and discard objectsthat are no longer needed by a program so that their resources canbe reclaimed and reused.A Java object is subject to garbage collection when it becomesunreachable to the program in which it is used. In java memory de-allocation is done automatically. When object has no reference is

    exists then it is treated to be no longer needed. Then the garbagecollector reclaims the memory occupied by that object. The finalize ()method on object is called just prior to object is going to be garbagecollected. Which is usually cleans up or releases the resources usedby that object. We can do garbage collection manually by a callSystem.gc();Example:class NoOfObjects{

    String nameOfObject;static int count=0;

    NoOfObjects(String name){

    nameOfObject=name;System.out.println("object "+nameOfObject+" is

    created");count++;

    }

    /*finalize method is called just before object is going to be garbagecollected.*/

    public void finalize()

    {count--;System.out.println(nameOfObject+" is garbage

    collected");}public static void main(String[] args){

    NoOfObjects a=new NoOfObjects("a");

  • 7/22/2019 java_intr_for_experts.pdf

    35/122

    NoOfObjects b=new NoOfObjects("b");new NoOfObjects("c");System.out.println("no of objects are

    "+NoOfObjects.count);b=null;

    System.gc();System.out.println("no of objects are"+NoOfObjects.count);

    }}

    Initializing the base class

    In super class, when we dont have any constructors or we haveimplemented default constructor and parameterized constructors,

    there is no need to call super class constructor from base classconstructor.If we have parameterized constructor and not having any implementeddefault constructor then we have to call super classs constructor frombase class constructor.Why because the default is lost when we have implemented anyconstructor.Initializing and loading of child classClass (.class file) is loaded at the point of used first. This is usuallywhen the object of that is class is constructed, but loading also occurswhen a static field or static method is accessed. When a class file is

    going to be loaded it checks extends keyword, if there is super classthen first super class is loaded then the child class. If the base classagain has another base class, that second class would then be loaded,and so on.Class A { }Class B extends A { }Class C extends B { }Class Demo{

    //C.staticMethod(); or new C();-----

    }A is first loaded, then B, finally C.1. All the static variables and static block are loaded in textual order(the order that you write down in class definition). And statics alsoinitialized only once.2. After all the initialization variables and initialization block are loadedin textual order (the order that you write down in class definition). Andthese are initialized as many as times as no of objects are created.

  • 7/22/2019 java_intr_for_experts.pdf

    36/122

    3. Finally constructor is executed.For exampleClass A { }Clsss B extends A {}Class Demo

    {Public static void main(String a[]){

    B ob1 =new B();B ob2=new B();

    }} //end DemoExecution flowB ob1=new B();

    1. Static variables and static block of class A in textual order. Theseare executed only once.

    2. Static variables and static block of class B in textual order.These are executed only once.

    3. Instance variables and initialization block of class A in textualorder and finally constructor.

    4. Instance variables and initialization block of class B in textualorder and finally constructor.

    B ob2=new B()5. Instance variables and initialization block of class A in textual

    order and finally constructor.6. Instance variables and initialization block of class B in textual

    order and finally constructor.

    What is final?Final means it is constant.A field is both static and final is single storage field that cannot bechanged.Final classes can not be inherited. We can change the fields in finalclass objects as well as final objects (it means fields in final class arenot final). All the methods in final class are implicitly final.Final primitives are can not be changed. Final referenced variables arecan not point to another objects. But the objects are modifiable. This isalso for arrays. Those array contents can be modified.Finals that are declared as final but not given an initialization values

    are called blank finals. Blank finals must be initialized in constructor.Final arguments cannot be changed (primitives cannot be changed,references can not point to other objects) within the method. But wecan read them.Final methods are not overridden. We can prevent the change of code.All the private methods in a class are implicitly final.final class B{

  • 7/22/2019 java_intr_for_experts.pdf

    37/122

    final int b;int c;B(){

    b=c;

    }void change(int i){

    //b=i; final variable b can not be changed}int a=40;

    }

    class A //extends B --A final class canot be inherited{

    A (){

    }A (B b,final int c,final B d){

    b=new B();//ok//d=new B();//cant change//c=20; cannot change

    }

    final private void bb(){

    }int y;

    }

    Public class FinalDemo{

    final int x=30;

    final A ob=new A();final int arr[]=new int[9];void fun1(){

    ob.y=20;arr[6]=90;//x=80; primitive finals can not be changed//ob=new A();

  • 7/22/2019 java_intr_for_experts.pdf

    38/122

    //arr=new int[90];int z;z=20;System.out.println(z);final A a;

    //System.out.println(a);//a.y=0; we cannot use local variable before //assinging iteven it is non-final

    B oa=new B();oa.a=70; //we can change final class objectsSystem.out.println("ok");

    }/*** @param args*/public static void main(String[] args)

    {FinalDemo i=new FinalDemo();i.fun1();i.ob.y=80;//x=90;// TODO Auto-generated method stub

    }

    }

    Q. What is singleton java class?

    A java class allows to create only one object for it is called singletonjava class.

    Creation:class SingleTon

    {private static SingleTon obj=null;

    private SingleTon(){

    }static SingleTon getObj(){

    obj=new SingleTon();return obj;

    }

    public clone()

  • 7/22/2019 java_intr_for_experts.pdf

    39/122

    {throw new CloneNotSupportedException();

    }}

    Q:

    Describe synchronization in respect to multithreading.

    A:With respect to multithreading, synchronization is the capability tocontrol the access of multiple threads to shared resources. Withoutsynchronization, it is possible for one thread to modify a sharedvariable while another thread is in the process of using or updatingsame shared variable. This usually leads to significant errors.Synchronization allows one thread can use the resource at a time. Injava every object has its own monitor implicitly so that it is entered

    automatically when a thread uses a objects synchronized method,no other threads can invoke any synchronized method on sameobject.

    Q:

    Explain different way of using thread?

    A:The thread could be implemented by using Runnable interface or byinheriting from the Thread class. The former is more advantageous,because when you are going for multiple inheritance., the onlyinterface can help.

    Q: What are pass by reference and passby value?A: Pass By Reference means the passing the address itself rather than

    passing the value. Passby Value means passing a copy of the valueto be passed.

    Q: What is HashMap and Map?A: Map is Interface and Hashmap is class that implements that. Maps

    store a key / value pairs. Keys are unique. Some Maps allows nullkey and null value others can not. HashMap uses hashing whenstoring the elements. When we are using HashMap, specify the

    object as key and value that linked to that object key. The key isthen hashed. The resulting hashcode is used as the index at whichthe value is stored in map. These hashcodes are used to look up thevalues. HashMap allows nulls as both keys and values. Hashing isused to get fast lookup.

    Q: Difference between HashMap and HashTable?

  • 7/22/2019 java_intr_for_experts.pdf

    40/122

    A: Hashtable is synchronized whereas HashMap not.The HashMap class is roughly equivalent to HashTable, except thatit is unsynchronized and permits nulls. (HashMap allows null valuesas key and value whereas Hashtable doesnt allow).HashMap does not guarantee that the order of the map will remain

    constant over time.In addition to methods defined by Map interface a Hastable addssome of legacy methods for better performance.

    Q: Difference between ArrayList and LinkedList?If you need to support random access (getting elements fromanywhere), without inserting or removing elements at/from anyplace other than the end, then ArrayList offers the optimalcollection. Randomly accessing elements in ArrayList is a constanttime operation. It takes same time regardless where from youaccessing element. In LinkedList it is expensive.

    Both are not synchronized.Both allow null values.If, however, you need to frequently add and remove elements fromthe middle of the list and only access the list elements sequentiallythen LinkedList offers the better implementation. In addition,LinkedList adds several methods for working with the elements atthe ends of the list (only the new methods are shown in thefollowing diagram):

    By using these new methods, you can easily treat the LinkedList asa stack, queue, or other end-oriented data structure.BasicsThe underlaying data structure for the ArrayList is the array, and for

    the LinkedList the linked list.This means for the ArrayList; fast random access but slowinsert/remove except adding elements at the end because the arrayindex gets you right to that element. But then adding and deletingat the start and middle of the arraylist would be slow, because allthe later elements have to copied forward or backward. (UsingSystem.arrayCopy()).when run an "add(Object o)" command a new array will be created

  • 7/22/2019 java_intr_for_experts.pdf

    41/122

    with n+1 dimension. All "older" elements will be copied to first nelements and last n+1 one will filled with the value which youprovide with add() method. To avoid that internal re-copying ofarrays you should use ensureCapacity(int requestCapacity) method -it will create an array only once.

    For example if you need to add new element to the end of anArrayList you have to look at the size of the collection and then addthat new element at n+1 place. In LinkedList you do it directly byaddLast(E e) method.And for the LinkedList; slow random access but fast insert/removeanywhere. LinkedList is made up of a chain of nodes. Each nodestores an element and the pointer to the next node. A singly linkedlist only has pointers to next. A doubly linked list has a pointer to thenext and the previous element. This makes walking the listbackward easier. Linked lists are fast for inserts and deletesanywhere in the list, since all you do is update a few next and

    previous pointers of a node.

    Q:

    Difference between Vector and ArrayList?

    The Vector is a historical collection which is replaced by ArrayList.The documentation for ArrayList states "This class isroughly equivalent to Vector, except that it isunsynchronized."An ArrayList could be a good choice if you need very flexible Arraytype of collection with limited functionality.

    Vectors are a lot slower, performance wise, than ArrayLists. So, useArraylists unless you need synchronised lists. Vector is historicalclass and was retrofitted to satisfy the List interface, but still retainthe "old" methods (like getElementAt()).Vector is synchronized whereas ArrayList is not. Vector has manylegacy methods that shows high performance and those are not partof collections.public synchronized void removeElementAt(int);protected void removeRange(int,int);public synchronized java.lang.Object firstElement();public synchronized java.lang.Object lastElement();

    public java.util.Enumeration elements();public synchronized java.util.List subList(int,int);we can use Collections wrapper to get synchronization listList myList=new ArrayList();myList = Collections.synchronizedList(myList)

  • 7/22/2019 java_intr_for_experts.pdf

    42/122

  • 7/22/2019 java_intr_for_experts.pdf

    43/122

    A:Static block is executed when a class is loaded into memory.Static means one per class, not one for each object no matter howmany instance of a class might exist. This means that you can usethem without creating an instance of a class.Static methods and variables can be used in non-static methods,

    reverse is not possible. Static methods can be overridden.you can't override a static method with a non-static method. In otherwords, you can't change a static method into an instance method ina subclass.

    Q:

    What is final?

    A:A final class can't be extended ie., final class may not be subclassed.A final method can't be overridden when its class is inherited. Youcan't change value of a final variable (is a constant).

    Q

    :

    What if the main method is declared as private?

    A:The program compiles properly but at runtime it will give "Mainmethod not public." message.[ ReceivedfromSandeshSadhale]

    Q: What if the static modifier is removed from the signature of the

    main method?A: Program compiles. But at runtime throws an error

    "NoSuchMethodError".[ Received fromSandeshSadhale]

    Q:

    What if I write static public void instead of public static void?

    A:Program compiles and runs properly.

    [ Received from Sandesh Sadhale]Q:

    What if I do not provide the String array as the argument to themethod?

    A:Program compiles but throws a runtime error "NoSuchMethodError".[ Received from Sandesh Sadhale]

    Q:

    What is the first argument of the String array in main method?

    A:The String array is empty. It does not have any element. This is

  • 7/22/2019 java_intr_for_experts.pdf

    44/122

  • 7/22/2019 java_intr_for_experts.pdf

    45/122

    Q:

    Can I import same package/class twice? Will the JVM load thepackage twice at runtime?

    A:One can import the same package or same class multiple times.Neither compiler nor JVM complains about it. And the JVM willinternally load the class only once no matter how many times you

    import the same class.Q: What are Checked and UnChecked Exception?A: A checked exception is some subclass of Exception (or

    Exception itself), excluding class RuntimeException and itssubclasses.Making an exception checked forces client programmers todeal with the possibility that the exception will be thrown. eg,IOException thrown by java.io.FileInputStream's read()methodUnchecked exceptions are RuntimeException and any of its

    subclasses. Class Error and its subclasses also areunchecked. With an unchecked exception, however, thecompiler doesn't force client programmers either to catch theexception or declare it in a throws clause. In fact, clientprogrammers may not even know that the exception could bethrown. eg, StringIndexOutOfBoundsException thrown byString's charAt() method Checked exceptions must becaught at compile time. Runtime exceptions do not need tobe. Errors often cannot be.

    Q: What are different types of inner classes?A: Nested top-level classes, Member classes, Local classes,

    Anonymous classes

    Nested top-level classes- If you declare a class within a classand specify the static modifier, the compiler treats the classjust like any other top-level class.Any class outside the declaring class accesses the nestedclass with the declaring class name acting similarly to apackage. eg, outer.inner. Top-level inner classes implicitlyhave access only to static variables.There can also be innerinterfaces. All of these are of the nested top-level variety.

    Member classes - Member inner classes are just like othermember methods and member variables and access to themember class is restricted, just like methods and variables.This means a public member class acts similarly to a nestedtop-level class. The primary difference between memberclasses and nested top-level classes is that member classeshave access to the specific instance of the enclosing class.

  • 7/22/2019 java_intr_for_experts.pdf

    46/122

    Local classes - Local classes are like local variables, specificto a block of code. Their visibility is only within the block oftheir declaration. In order for the class to be useful beyondthe declaration block, it would need to implement a

    more publicly available interface. Because local classes arenot members, the modifiers public, protected, private, andstatic are not usable.Anonymous classes - Anonymous inner classes extend localinner classes one level further. As anonymous classes haveno name, you cannot provide a constructor.

    Q:Are the imports checked for validity at compile time? e.g. will thecode containing an import such as java.lang.ABCD compile?

    A: Yes the imports are checked for the semantic validity at compiletime. The code containing above line of import will not compile. Itwill throw an error saying,can not resolve symbol

    symbol : class ABCDlocation: package ioimport java.io.ABCD;[ Received fromSandeshSadhale]

    Q:Does importing a package imports the subpackages as well? e.g.Does importing com.MyTest.* also import com.MyTest.UnitTests.*?

    A: No you will have to import the subpackages explicitly. Importingcom.MyTest.* will import classes in the package MyTest only. It will

    not import any class in any of it's subpackage.[ Received fromSandeshSadhale]

    Q:What is the difference between declaring a variable and defining avariable?

    A: In declaration we just mention the type of the variable and it's name.We do not initialize it. But defining means declaration + initialization.e.g String s; is just a declaration while String s = new String("abcd"); Or String s = "abcd"; are both definitions.

    [ Received fromSandeshSadhale]

    Q:What is the default value of an object reference declared as aninstance variable?

    A: null unless we define it explicitly.[ Receive

  • 7/22/2019 java_intr_for_experts.pdf

    47/122

  • 7/22/2019 java_intr_for_experts.pdf

    48/122

  • 7/22/2019 java_intr_for_experts.pdf

    49/122

  • 7/22/2019 java_intr_for_experts.pdf

    50/122

    [ Received fromSandesh Sadhale]

    Q:Why do we need wrapper classes?A: It is sometimes easier to deal with primitives as objects. Moreover

    most of the collection classes store objects and not primitive data

    types. And also the wrapper classes provide many utility methodsalso. Because of these resons we need wrapper classes. And sincewe create instances of these classes we can store them in any of thecollection classes and pass them around as a collection. Also we canpass them around as method parameters where a method expectsan object.[ Received fromSandesh Sadhale]

    Q:What are checked exceptions?A: Checked exceptions are those which the Java compiler forces you to

    catch. E.g. IOException are checked Exceptions.

    [ Received fromSandesh Sadhale]

    Q:What are runtime exceptions?A: Runtime exceptions are those exceptions that are thrown at runtime

    because of either wrong input data or because of wrong businesslogic etc. These are not checked by the compiler at compile time.[ Received fromSandesh Sadhale]

    Q:What is the difference between error and an exception?A: An error is an irrecoverable condition occurring at runtime. Such as

    OutOfMemory error. These JVM errors and you can not repair them at

    runtime. While exceptions are conditions that occur because of badinput etc. e.g. FileNotFoundException will be thrown if the specifiedfile does not exist. Or a NullPointerException will take place if you tryusing a null reference. In most of the cases it is possible to recoverfrom an exception (probably by giving user a feedback for enteringproper values etc.).[ Received fromSandesh Sadhale]

    Q:How to create custom exceptions?A: Your class should extend class Exception, or some more specific type

    thereof.

    [ Received fromSandesh Sadhale]

    Q:If I want an object of my class to be thrown as an exception object,what should I do?

    A:The class should extend from Exception class. Or you can extendyour class from some more precise exception type also.[ Received fromSandesh Sadhale]

  • 7/22/2019 java_intr_for_experts.pdf

    51/122

    Q:If my class already extends from some other class what should I do ifI want an instance of my class to be thrown as an exception object?

    A: One can not do anytihng in this scenarion. Because Java does notallow multiple inheritance and does not provide any exceptioninterface as well.

    [ Received from SandeshSadhale]Q:How does an exception permeate through the code?A: An unhandled exception moves up the method stack in search of a

    matching When an exception is thrown from a code which iswrapped in a try block followed by one or more catch blocks, asearch is made for matching catch block. If a matching type is foundthen that block will be invoked. If a matching type is not found thenthe exception moves up the method stack and reaches the callermethod. Same procedure is repeated if the caller method is includedin a try catch block. This process continues until a catch block

    handling the appropriate type of exception is found. If it does notfind such a block then finally the program terminates.[ Received from SandeshSadhale]

    Q:What are the different ways to handle exceptions?A: There are two ways to handle exceptions,

    1. By wrapping the desired code in a try block followed by a catchblock to catch the exceptions. and2. List the desired exceptions in the throws clause of the method andlet the caller of the method handle those exceptions.[ Received from Sandesh

    Sadhale]Q:What is the basic difference between the 2 approaches to exception

    handling?1> try catch block and2> specifying the candidate exceptions in the throws clause?When should you use which approach?

    A: In the first approach as a programmer of the method, you urself aredealing with the exception. This is fine if you are in a best position todecide should be done in case of an exception. Whereas if it is notthe responsibility of the method to deal with it's own exceptions,then do not use this approach. In this case use the second approach.

    In the second approach we are forcing the caller of the method tocatch the exceptions, that the method is likely to throw. This is oftenthe approach library creators use. They list the exception in thethrows clause and we must catch them. You will find the sameapproach throughout the java libraries we use.[ Received from SandeshSadhale]

    Q:Is it necessary that each try block must be followed by a catch

  • 7/22/2019 java_intr_for_experts.pdf

    52/122

    block?A: It is not necessary that each try block must be followed by a catch

    block. It should be followed by either a catch block OR a finally block.And whatever exceptions are likely to be thrown should be declaredin the throws clause of the method.

    [ Received from SandeshSadhale]Q:If I write return at the end of the try block, will the finally block still

    execute?A: Yes even if you write return as the last statement in the try block

    and no exception occurs, the finally block will execute. The finallyblock will execute and then the control return.[ Received from SandeshSadhale]

    Q:If I write System.exit (0); at the end of the try block, will the finallyblock still execute?

    A: No in this case the finally block will not execute because when yousay System. exit (0); the control immediately goes out of theprogram, and thus finally never executes.[ Received from SandeshSadhale]

    Q:How are Observer and Observable used?A:Objects that subclass the Observable class maintain a list of

    observers. When an Observable object is updated it invokes theupdate () method of each of its observers to notify the observers thatit has changed state. The Observer interface is implemented by

    objects that observe Observable objects.[Received from Venkateswara Manam]

    Q:What is synchronization and why is it important?A:With respect to multithreading, synchronization is the capability to

    controlthe access of multiple threads to shared resources. Withoutsynchronization, it is possible for one thread to modify a sharedobject while another thread is in the process of using or updatingthat object's value. This often leads to significant errors.[ Received from Venkateswara Manam]

    Q:How does Java handle integer overflows and underflows?

    A: It uses those low order bytes of the result that can fit into the size ofthe type allowed by the operation.[ Received from Venkateswara Manam]

    Q:Does garbage collection guarantee that a program will not run out ofmemory?

    A:Garbage collection does not guarantee that a program will not runout of memory. It is possible for programs to use up memoryresources faster than they are garbage collected. It is also possible

    mailto:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/22/2019 java_intr_for_experts.pdf

    53/122

    for programs to create objects that are not subject to garbagecollection.[ Received from Venkateswara Manam]

    Q:What is the difference between preemptive scheduling and time

    slicing?A:Under preemptive scheduling, the highest priority task executes untilit enters the waiting or dead states or a higher priority task comesinto existence. Under time slicing, a task executes for a predefinedslice of time and then reenters the pool of ready tasks. Thescheduler then determines which task should execute next, based onpriority and other factors.[ Received from Venkateswara Manam]

    Q:When a thread is created and started, what is its initial state?A:A thread is in the ready state after it has been created and started.

    [ Received from Venkateswara Manam]

    Q:What is the purpose of finalization?A:The purpose of finalization is to give an unreachable object the

    opportunity to perform any cleanup processing before the object isgarbage collected.[ Received from Venkateswara Manam]

    Q:What is the Locale class?A:The Locale class is used to tailor program output to the conventions

    of a particular geographic, political, or cultural region.[ Received from Venkateswara Manam]

    Q:What is the difference between a while statement and a dostatement?

    A:A while statement checks at the beginning of a loop to see whetherthe next loop iteration should occur. A do statement checks at theend of a loop to see whether the next iteration of a loop shouldoccur. The do statement will always execute the body of a loop atleast once.[ Received from Venkateswara Manam]

    Q:What is the difference between static and non-static variables?A:A static variable is associated with the class as a whole rather than

    with specific instances of a class. Non-static variables take on uniquevalues with each object instance.[ Received from Venkateswara Manam]

    Q:How are this() and super() used with constructors?A:This() is used to invoke a constructor of the same class. super() is

    used to invoke a superclass constructor.[ Received from Venkateswara Manam]

    Q:What are synchronized methods and synchronized statements?A:Synchronized methods are methods that are used to control access

    to an object. A thread only executes a synchronized method after ithas acquired the lock for the method's object or class. Synchronized

    mailto:[email protected]