Basic Thinks

download Basic Thinks

of 22

Transcript of Basic Thinks

  • 8/4/2019 Basic Thinks

    1/22

    1. COMPARISON WITH C AND C++

    C C++

    MajorImplementations:

    GCC, MSVC, Borland C,Watcom C

    GNU Compiler

    Collection, MicrosoftVisual C++, Borland C+

    + BuilderProgramming-input

    /output:

    scanf for input;printf

    for output

    cin for input;cout for

    output

    Speed:

    C applications are

    faster to compile and

    execute than C++applications

    C++ applicationsare generallyslower at

    runtime, and are much

    slower to compilethan C programs

    OOP(ObjectOriented

    Programming):

    NoYes-polymorphism and

    inheritance

    Appeared in: 1972 1985

    Designed by: Dennis Ritchie Bjarne Stroustrup

    Developed by:Dennis Ritchie & BellLabs

    Bjarne Stroustrup

    Typing Discipline: Static, WeakStatic, Unsafe,Nominative

    Programming-

    include:use #include

    use #include

    Programming-

    String type:

    Cannot use string type

    but declare it as anarray

    Can use string type

    http://www.diffen.com/difference/Special:Information/Chttp://www.diffen.com/difference/Special:Information/C%2B%2Bhttp://www.diffen.com/difference/Special:Information/C%2B%2Bhttp://www.diffen.com/difference/extensions/Rating/db.php?j=1&q=136&t=213.120.111.192&c=5http://www.diffen.com/difference/extensions/Rating/db.php?j=2&q=136&t=213.120.111.192&c=5http://www.diffen.com/difference/extensions/Rating/db.php?j=3&q=136&t=213.120.111.192&c=5http://www.diffen.com/difference/extensions/Rating/db.php?j=4&q=136&t=213.120.111.192&c=5http://www.diffen.com/difference/extensions/Rating/db.php?j=5&q=136&t=213.120.111.192&c=5http://www.diffen.com/difference/Special:Information/C
  • 8/4/2019 Basic Thinks

    2/22

    C++, as the name suggests is a superset of C. As a matter of fact, C++ can

    run most of C code while C cannot run C++ code. Here are the 10 major

    differences between C++ & C

    1. C follows the procedural programming paradigm while C++ is a multi-

    paradigm language(procedural as well as object oriented)

    In case of C, importance is given to the steps or procedure of the program

    while C++ focuses on the data rather than the process.

    Also, it is easier to implement/edit the code in case of C++ for the same

    reason.

    2. In case of C, the data is not secured while the data is secured(hidden) in

    C++

    This difference is due to specific OOP features like Data Hiding which are not

    present in C.

    3. C is a low-level language while C++ is a middle-level language

    C is regarded as a low-level language(difficult interpretation & less user

    friendly) while C++ has features of both low-level(concentration on whats

    going on in the machine hardware) & high-level languages(concentration on

    the program itself) & hence is regarded as a middle-level language.

    4. C uses the top-down approach while C++ uses the bottom-up approach

    In case of C, the program is formulated step by step, each step is processed

    into detail while in C++, the base elements are first formulated which then

    are linked together to give rise to larger systems.

    5. C is function-driven while C++ is object-driven

    http://zarrata.com/durofy/programming/c-as-a-multi-paradigm-programming-language/http://zarrata.com/durofy/programming/c-as-a-multi-paradigm-programming-language/http://zarrata.com/durofy/programming/the-basics-of-object-oriented-programming/http://zarrata.com/durofy/programming/c-as-a-multi-paradigm-programming-language/http://zarrata.com/durofy/programming/c-as-a-multi-paradigm-programming-language/http://zarrata.com/durofy/programming/the-basics-of-object-oriented-programming/
  • 8/4/2019 Basic Thinks

    3/22

    Functions are the building blocks of a C program while objects are building

    blocks of a C++ program.

    6. C++ supports function overloading while C does not

    Overloading means two functions having the same name in the same

    program. This can be done only in C++ with the help ofPolymorphism(an

    OOP feature)

    7. We can use functions inside structures in C++ but not in C.

    In case of C++, functions can be used inside a structure while structures

    cannot contain functions in C.

    8. The NAMESPACE feature in C++ is absent in case of C

    C++ uses NAMESPACE which avoid name collisions. For instance, two

    students enrolled in the same university cannot have the same roll number

    while two students in different universities might have the same roll number.

    The universities are two different namespace & hence contain the same roll

    number(identifier) but the same university(one namespace) cannot have twostudents with the same roll number(identifier)

    9. The standard input & output functions differ in the two languages

    C uses scanf & printf while C++ uses cin>> & cout

  • 8/4/2019 Basic Thinks

    4/22

    Java Developer Kit contains tools needed to develop the Java programs,andJREto run the programs. The tools include compiler (javac.exe),

    Java application launcher (java.exe), Applet viewer, etc

    Compiler converts java code into byte code. Java application launcher opens

    aJRE, loads the class, and invokes its main method.

    You needJDK, if at all you want to write your own programs, and to compile

    the m. For running java programs, JRE is sufficient.

    JRE is targeted for execution of Java files

    i.e. JRE = JVM + Java Packages Classes(like util, math, Lang, awt,swing

    etc)+runtime libraries.

    JDKis mainly targeted for java development. I.e. You can create a Java file

    (with the help of Java packages), compile a Java file and run a java file

    JRE (Java Runtime Environment)

    Java Runtime Environment contains JVM, class libraries, and othersupporting files. It does not contain any development tools such as compiler,

    debugger, etc. Actually JVM runs the program, and it uses the class libraries,and other supporting files provided in JRE. If you want to run any java

    program, you need to have JRE installed in the system

    The Java Virtual Machineprovides a platform-independent way ofexecuting code; programmers can concentrate on writing software, without

    having to be concerned with how or where it will run.

    If u just want to run applets (ex: Online Yahoo games or puzzles),JREneedsto be installed on the machine.

    JVM (Java Virtual Machine)

    As we all aware when we compile aJava file, output is not an 'exe' but it's a'.class' file. '.class' file consists of Java byte codeswhich are

    understandable by JVM. Java Virtual Machine interprets the byte code intothe machine code depending upon the underlying operating system and

    hardware combination. It is responsible for all the things like garbage

    collection, array bounds checking, etc JVM is platform dependent.

    TheJVMis called "virtual" because it provides a machine interface that does

    not depend on the underlying operating system and machine hardware

  • 8/4/2019 Basic Thinks

    5/22

  • 8/4/2019 Basic Thinks

    6/22

    other. OOP offers greater flexibility and compatibility and is popular in

    developing larger application. Another important work in OOP is to classify

    objects into different types according to their properties and behavior. So

    OOP based software application development includes the analysis of the

    problem, preparing a solution, coding and finally its maintenance.

    Java is a object oriented programming and to understand the functionality of

    OOP in Java, we first need to understand several fundamentals related to

    objects. These include class, method, inheritance, encapsulation,

    abstraction, polymorphism etc.

    Class - It is the central point of OOP and that contains data and codes with

    behavior. In Java everything happens within class and it describes a set of

    objects with common behavior. The class definition describes all the

    properties, behavior, and identity of objects present within that class. As far

    as types of classes are concerned, there are predefined classes in languages

    like C++ and Pascal. But in Java one can define his/her own types with data

    and code.

    Object - Objects are the basic unit of object orientation with behavior,

    identity. As we mentioned above, these are part of a class but are not the

    same. An object is expressed by the variable and methods within the

    objects. Again these variables and methods are distinguished from each

    other as instant variables, instant methods and class variable and class

    methods.

  • 8/4/2019 Basic Thinks

    7/22

    Methods - We know that a class can define both attributes and behaviors.

    Again attributes are defined by variables and behaviors are represented by

    methods. In other words, methods define the abilities of an object.

    Inheritance - This is the mechanism of organizing and structuring software

    program. Though objects are distinguished from each other by some

    additional features but there are objects that share certain things common.

    In object oriented programming classes can inherit some common behavior

    and state from others. Inheritance in OOP allows to define a general class

    and later to organize some other classes simply adding some details with the

    old class definition. This saves work as the special class inherits all the

    properties of the old general class and as a programmer you only require the

    new features. This helps in a better data analysis, accurate coding and

    reduces development time.

    Abstraction - The process of abstraction in Java is used to hide certain

    details and only show the essential features of the object. In other words, it

    deals with the outside view of an object (interface).

    Encapsulation - This is an important programming concept that assists in

    separating an object's state from its behavior. This helps in hiding an

    object's data describing its state from any further modification by external

    component. In Java there are four different terms used for hiding data

    constructs and these are public, private, protected and package. As we know

    an object can associated with data with predefined classes and in any

    application an object can know about the data it needs to know about. So

  • 8/4/2019 Basic Thinks

    8/22

    any unnecessary data are not required by an object can be hidden by this

    process. It can also be termed as information hiding that prohibits outsiders

    in seeing the inside of an object in which abstraction is implemented.

    Polymorphism - It describes the ability of the object in belonging to

    different types with specific behavior of each type. So by using this, one

    object can be treated like another and in this way it can create and define

    multiple level of interface. Here the programmers need not have to know the

    exact type of object in advance and this is being implemented at runtime.

    In Java, some of the differences between other methods and constructorsare:

    Constructors never have an explicit return type.

    Constructors cannot be directly invoked (the keyword new must beused).

    Constructors cannot be synchronized, final, abstract, native, or static.

    Constructors are always executed by the same thread.

    This Keyword

    You cannot use this inside a static block because this relates to an instance

    of a class ("this instance"), while static blocks belong to the class itself. So,

    which one is the this instance when you're inside a block that does not

    belong specifically to any instance? In the case of your program, the static

    block is executed when the class is loaded, that's why the first output you

    see is "Static block started". Then, instance data is initialized. Is that clear?

    http://en.wikipedia.org/wiki/Java_(programming_language)http://en.wikipedia.org/wiki/Java_(programming_language)
  • 8/4/2019 Basic Thinks

    9/22

    The keyword this is useful when you need to refer to instance of the class

    from its method. The keyword helps us to avoid name conflicts. As we can

    see in the program that we have declare the name of instance variable and

    local variables same. Now to avoid the confliction between them we

    use this keyword.

    Super keyword

    This super key word is used to call a method in protected access modifier

    as we know the protected modifiers cannot accessible from any other

    package or classes without having inheritance by using the super keyword,

    compiler identifies the protected method of another class is available in

    current class as the method has being inherited in current class also the

    compiler will not allow to reference an object from another class which has

    Protected access. Use same class reference and call method () it is possible

    as the Obj class is inherited. *

    Super keyword

    http://www.aspose.com/adtracker/?code=160846100719http://www.aspose.com/adtracker/?code=160846100719
  • 8/4/2019 Basic Thinks

    10/22

    The super is java keyword. As the name suggest super is used to access the

    members of the super class. It is used for two purposes in java.

    The first use of keyword super is to access the hidden data variables of the

    super class hidden by the sub class.

    E.g. Suppose class A is the super class that has two instance variables as

    int a and float b. class B is the subclass that also contains its own data

    members named a and b. then we can access the super class (class A)

    variables a and b inside the subclass class B just by calling the following

    command.

    Super. Member;

    Here member can either be an instance variable or a method. This form of

    super most useful to handle situations where the local members of a

    subclass hide the members of a super class having the same name.

    class A{

    int a;

    float b;

    voidShow(){

    System.out.println("b in super class: " + b);

    }

    }

    class B extends A{

    int a;

    float b;

  • 8/4/2019 Basic Thinks

    11/22

    B( int p, float q){

    a = p;

    super.b = q;

    }

    voidShow(){

    super.Show();

    System.out.println("b in super class: " + super.b);

    System.out.println("a in sub class: " + a);

    }

    public static voidmain(String[] args){

    B subobj = new B(1, 5);

    subobj.Show();

    }

    }

    class A{

    int a;

    int b;

    int c;

    A(int p, int q, int r){

    a=p;

    b=q; c=r;

    }

    }

    class B extends A{

    int d;

    B(int l, int m, int n, int o){

    super(l,m,n);

    d=o;

    }voidShow(){

    System.out.println("a = " + a);

    System.out.println("b = " + b);

    System.out.println("c = " + c);

    System.out.println("d = " + d);

    }

  • 8/4/2019 Basic Thinks

    12/22

    public static voidmain(String args[]){

    B b = new B(4,3,8,7);

    b.Show();

    }

    }

    11.1 The Causes of Exceptions

    An exception is thrown for one of three reasons:

    An exception is an event that occurs during the execution of a program thatdisrupts the normal flow of instructions.

    An abnormal execution condition was synchronously detected by theJava virtual machine. Such conditions arise because:

    o evaluation of an expression violates the normal semantics of the

    language, such as an integer divide by zero, as summarizedin 15.6

    o an error occurs in loading or linking part of the program

    (12.2, 12.3)

    o some limitation on a resource is exceeded, such as using too

    much memory

    These exceptions are not thrown at an arbitrary point in the program,

    but rather at a point where they are specified as a possible result of anexpression evaluation or statement execution.

    A throw statement (14.17) was executed.

    An asynchronous exception occurred either because:o the method stop of class Thread was invoked

    o an internal error has occurred in the virtual machine (11.5.2)

    Exceptions are represented by instances of the class Throwable and

    instances of its subclasses. These classes are, collectively, the exceptionclasses.

    Subclass of runtime Exception is unchecked exception, remaining things are

    checked exception

    http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#79448http://java.sun.com/docs/books/jls/second_edition/html/execution.doc.html#44459http://java.sun.com/docs/books/jls/second_edition/html/execution.doc.html#44487http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#237350http://java.sun.com/docs/books/jls/second_edition/html/exceptions.doc.html#44395http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#79448http://java.sun.com/docs/books/jls/second_edition/html/execution.doc.html#44459http://java.sun.com/docs/books/jls/second_edition/html/execution.doc.html#44487http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#237350http://java.sun.com/docs/books/jls/second_edition/html/exceptions.doc.html#44395
  • 8/4/2019 Basic Thinks

    13/22

    Checked vs. Unchecked Exceptions

    Type of exceptions in java is checked exceptions and unchecked exceptions.

    This classification is based on compile-time checking of exceptions. There is

    also a classification based on runtime in java. It is not widely known! That is

    synchronous and asynchronous exceptions. First let us see the java checked

    exceptions and unchecked exceptions.

    Checked Exceptions Vs Unchecked Exceptions in Java

    At compile time, the java compiler checks that a program contains handlers

    for checked exceptions. Java compiler analyzes by which checked exceptions

    can result from execution of a method or constructor. For each checked

  • 8/4/2019 Basic Thinks

    14/22

    exception which is a possible result, the throws clause for the method or

    constructor must mention the class or its super classes of that exception.

    The class Runtime Exception and its subclasses, and the class Error and itssubclasses are unchecked exceptions classes. Because the compiler doesnt

    forces them to be declared in the throws clause. All the other exception

    classes that are part of Throw able hierarchy are checked exceptions.

    Now let us see a see small discussion on why exceptions are classified as

    checked exceptions and unchecked exceptions.

    Those unchecked exception classes which are the error classes (Error and its

    subclasses) are exempted from compile-time checking in java because they

    can occur at many points in the program and recovery from them is difficult

    or impossible.

    Example: OutOfMemoryError

    Thrown when the Java Virtual Machine cannot allocate an object because it

    is out of memory, and no more memory could be made available by the

    garbage collector.

    The runtime exception classes (Runtime Exception and its subclasses) are

    exempted from compile-time checking because, in the judgment of the

    designers of the Java, having to declare such exceptions would not aid

    significantly in establishing the correctness of programs.

    Example: NullPointerException

    Thrown when an application attempts to use null in a case where an object is

    required.

  • 8/4/2019 Basic Thinks

    15/22

  • 8/4/2019 Basic Thinks

    16/22

    IllegalArgumentException

    Illegal argument

    when calling a

    method

    - YES

    Interrupted ExceptionOne thread has beeninterrupted by

    another thread

    YES -

    NoSuchMethodException Nonexistent method YES -

    NullPointerExceptionInvalid use of null

    reference- YES

    NumberFormatExceptionInvalid string for

    conversion to number- YES

  • 8/4/2019 Basic Thinks

    17/22

    String class objects work with complete strings instead of treating them ascharacter arrays as some languages do. Note: Convert variables of

    type charto string objects by usinggStr = Character.toString(c);.

    Accessor methods: length(), charAt(i), getBytes(),

    getChars(istart,iend,gtarget[],itargstart), split(string,delim), toCharArray(),valueOf(g,iradix), substring(iStart [,iEndIndex)]) [returns up to but notincluding iEndIndex]

    Modifier methods: concat(g), replace(cWhich, cReplacement),

    toLowerCase(), toUpperCase(), trim().Note: The method format(gSyn,g) uses c-like printf syntax for fixed fields

    if required in reports.

    Boolean test methods: contentEquals(g), endsWith(g), equals(g),equalsIgnoreCase(g), matches(g), regionMatches(i1,g2,i3,i4),

    regionMatches(bIgnoreCase,i1,g2,i3,i4), startsWith(g)

    Integer test methods: compareTo(g) [returns 0 if object equalsparameter, -1 if object is before parameter in sort order, +1 if otherwise],

    indexOf(g) [returns position of first occurrence of substring g in the string,-1 if not found], lastIndexOf(g) [returns position of last occurrence of

    substring g in the string, -1 if not found], length().

    String class objects are immutable (ie. read only). When a change is madeto a string, a new object is created and the old one is disused. This causes

    extraneous garbage collection if string modifier methods are used too often.TheStringBuffer or StringBuilder class should be used instead of Stringobjects in these cases.

    StringBufferclass objects allow manipulation of strings without creating anew object each time a manipulation occurs

    ccessor methods: capacity(), charAt(i), length(), substring(iStart

    [,iEndIndex)])

    Modifier methods: append(g), delete(i1, i2), deleteCharAt(i),

    ensureCapacity(), getChars(srcBeg, srcEnd, target[], targetBeg),

    insert(iPosn, g), replace(i1,i2,gvalue), reverse(), setCharAt(iposn, c),setLength(),toString(g)

    http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.htmlhttp://home.cogeco.ca/~ve3ll/jatutor7.htm#sbhttp://home.cogeco.ca/~ve3ll/jatutor7.htm#sbuhttp://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.htmlhttp://home.cogeco.ca/~ve3ll/jatutor7.htm#sbhttp://home.cogeco.ca/~ve3ll/jatutor7.htm#sbu
  • 8/4/2019 Basic Thinks

    18/22

    StringBuilderclass methods are similar to StringBuffer ones but theyare unsynchronized(ie. not for multithreaded applications). They are also

    much faster. Examples of setting up a string buffer variable are:

    Accessor methods: capacity(), length(), charAt(i), indexOf(g),

    lastIndexOf(g)

    Modifier methods: append(g), delete(i1, i2), insert(iPosn, g), getChars(i),setCharAt(iposn, c), substring(), replace(i1,i2,gvalue), reverse(),

    trimToSize(g ), toString(g)

    Many text manipulation utilities require a tokenizer function whichparses or

    breaks up the text into subunits calledtokens based onspecific delimiters or break characters. The most common delimiteris whitespace which yields words as the tokens. The String.split(string,

    reg_exp) method allows regular expressions to be used to define thedelimiters. Java also provides several tokenizer classes

    including StringTokenizerfor strings, StreamTokenizer for files,

    and Scanner class for files using regular expression delimiters.

    StringTokenizerclass objects may be created by one of three constructor

    methods depending on the parameters used. The first parameter string is

    the source text to be broken at the default set ofwhitespace delimiters(space, tab, newline, cr, formfeed). If a second parameter is passed, that

    string is assumed to be the set of delimiting characters. Use the escaper \character when representing the string quote character "or any non-

    typeable delimiters such as tab (\t). If a true flag is added as a third

    parameter, any delimiters found are also returned as string tokens. TheStringTokenizer methods are: int countTokens(),

    boolean hasMoreTokens() and String nextToken().

    http://home.cogeco.ca/~ve3ll/jatutor7.htm#rehttp://home.cogeco.ca/~ve3ll/jatutor9.htm#tohttp://home.cogeco.ca/~ve3ll/jatutor9.htm#tohttp://home.cogeco.ca/~ve3ll/jatutor7.htm#rehttp://home.cogeco.ca/~ve3ll/jatutor9.htm#tohttp://home.cogeco.ca/~ve3ll/jatutor9.htm#to
  • 8/4/2019 Basic Thinks

    19/22

    THREAD

    Thread is the feature of mostly languages including Java. Threads allow the

    program to perform multiple tasks simultaneously. Process speed can beincreased by using threads because the thread can stop or suspend a

    specific running process and start or resume the suspended processes.Multitasking or multiprogramming is delivered through the running of

    multiple threads concurrently. If your computer does not have multi-

    processors then the multi-threads really do not run concurrently.

    In java we have two types of Threads: Daemon Thread and User

    Threads. Generally all threads created by programmer are user thread(unless you specify it to be daemon or your parent thread is a daemon

    thread). User thread is generally meant to run our program code. JVM

    doesn't terminate unless all the user thread terminate.

    On the other hand we have Daemon threads. Typically these threads

    are service provider threads. They should not be used to run your

    program code but some system code. These threads run parallel to yourcode but survive on the mercy of the JVM. When JVM finds no user threads it

    stops and all daemon thread terminate instantly. Thus one should never relyon daemon code to perform any program code.

    For better understanding consider a well known example of Daemon

    thread: Java garbage collector. Garbage collector runs as a daemonthread to reclaim any unused memory. When all user threads terminates,

    JVM may stop and garbage collector also terminates instantly.

    The static synchronized methods of the same class always block each

    other as only one lock per class exists. So no two static synchronized

    methods can execute at the same time.

    When a synchronized non static method is called a lock is obtained on

    the object. When a synchronized static method is called a lock is obtainedon the class and not on the object.

  • 8/4/2019 Basic Thinks

    20/22

    every instance of class Object and its subclass's has a lock

    primitive data type fields (Scalar fields) can only be locked via their

    enclosing class

    fields cannot be marked as synchronized however they can be

    declared volatile which orders the way they can be used or you can write

    synchronized access or methods array objects can be synchronized BUT their elements cannot, nor

    can their elements be declared volatile

    Class instances are Objects and can be synchronized via static

    synchronized methods

    Synchronized blocks

    allow you to execute synchronized code that locks an object without

    requiring you to invoke a synchronized methodSynchronized ( expr ) {

    // 'expr' must evaluate to an Object

    }Synchronized methods

    declaring a method as synchronized ie synchronized void f() isequivalent to

    void f() { synchronized(this) {// body of method

    }

    }

    the synchronized keyword is NOT considered part of a method's

    signature. IT IS NOT AUTOMATICALLY INHERITED when subclassesoverride superclass methods

    methods in Interfaces CANNOT be declared synchronized constructors CANNOT be declared synchronized however they cancontain synchronized blocks

    synchronized methods in subclasses use the same locks as theirsuperclasses

    synchronization of an Inner Class is independent on it's outer class

    a non-static inner class method can lock it's containing class by usinga synchronized block

    synchronized(OuterClass.this) {// body

    }Locking

    locking follows a built-in acquire-release protocol controlled by

    the synchronized keyword

    a lock is acquired on entry to a synchronized method or block and

    released on exit, even if the exit is the result of an exception

    you cannot forget to release a lock

    locks operate on a per thread basis, not on a per-invocation basis

  • 8/4/2019 Basic Thinks

    21/22

    Java uses re-entrant locks ie a thread cannot lock on itselfclass Reentrant {

    public synchronized void a() {

    b();

    System.out.println("here I am, in a()");}

    public synchronized void b() {System.out.println("here I am, in b()");

    }

    }

    in the above code, the synchronized method a(), when executed,

    obtains a lock on its own object. It then calls synchronizedmethod b() which also needs to acquire a lock on its own object

    if Java did not allow a thread to reacquire its own lock method b()

    would be unable to proceed until method a() completed and released thelock; and method a() would be unable to complete until method b()

    completed. Result: deadlock

    as Java does allow reentrant locks, the code compiles and runs

    without a problem

    the locking protocol is only followed for synchronized methods, it

    DOES NOT prevent unsynchronized methods from accessing the object

    once a thread releases a lock, another thread may acquire it BUTthere is no guarantee as to WHICH thread will acquire the lock next

    Class fields and methods

    locking an object does not automatically protect access

    to static fields protecting static fields requires a synchronized static block ormethod

    static synchronized statements obtain a lock on the Class vs aninstance of the class

    a synchronized instance method can obtain a lock on the class

    Synchronized (Class Name. class) {// body

    }

    the static lock on a class is not related to any other class including its

    super classes a lock on a static method has no effect on any instances of thatclass (JPL pg 185)

    you cannot effectively protect static fields in a super class by addinga new static synchronized method in a subclass; an explicit block

    synchronization is the preferred way

  • 8/4/2019 Basic Thinks

    22/22

    nor should you use synchronized(get Class()); this locks the actualClass which might be different from the class in which the static fields are

    declared