Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, March 02, 2016

Static

Static keyword

1) static variables
2) static methods
3) static blocks of code.

static variable

  • It is a variable which belongs to the class and not to object(instance)
  • Static variables are initialized only once , at the start of the execution . These variables will be initialized first, before the initialization of any instance variables
  • A single copy to be shared by all instances of the class
  • A static variable can be accessed directly by the class name and doesn’t need any object
  • Syntax : <class-name>.<variable-name>
class Book {
    public static String Title;
    public static String Author;
    int yearPublished;
}

public class StaticMain2 {
    public static void main(String[] args) { //no need an instance of class
                                             //otherwise Book b = new Book();
                                             // to access b.yearPublished
        Book.Title = "Psychology and Human Evolution";
        Book.Author = "Jeannot Lamm";
           
    }
}

         static method

  • It is a method which belongs to the class and not to the object(instance)
  • A static method can access only static data. It can not access non-static data (instance variables)
  • A static method can  call only  other static methods and can not call a non-static method from it.
  • A static method  can be accessed directly by the class name and doesn’t need any object
  • Syntax : <class-name>.<method-name>
  • A static method cannot refer to "this" or "super"  keywords in anyway

          static block

           The static block, is a block of statement inside a Java class that will be executed when a class is first loaded in to the JVM

          class Test{
           static {
           //Code goes here
          }
           }
 
public static void main(String[] args){
  Thread t1 = new Thread(new Runnable() {
...
private static void producer(){  //static function in a class since no object (new) defined static
  Random random = new Random();
  while(true){
   try {
//    Integer val = random.nextInt(100);
    queue.put(random.nextInt(100)); //range 0 - 99
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
Static initialize block is executed even before JVM calls main method. They are executed when a Class is loaded into Memory by JVM.

In C/C++:
- A static variable, declared globally, will only be visible in that source file. Static functions are functions that are only visible to other functions in the same file. Global all files can access it using C keyword extern.

 static int varl //can't be seen from outside files, limit the scope.
 int var;          //Variables that are defined outside functions - global variables. Can see from outside
- The variable is permanent. The variable can only be initialized once and only one copy of the variable exists.(initialized at compilation time), retains it value between calls.
-Only one copy if the variable exits. All instances of the object use the same variables
-Static Function can only access static members/fields of the class but non-static member function can access static member function or data(see example below) and it can call only other static member functions. Normally, the address of the current object(this) is passed in when any member function is called, but a static member has no "this" which is the reason it cannot access ordinary members a bit faster since doesn't have (this). At the same time you get the benefits of having the function inside the class (p.473 of Thinking of C++ Bruce Eckel.). Static members have the same properties as global variables but enjoying class scope. It is a global variables, the only difference is its name outside the class. Static data members of a class are also known as "class variables" is a variable defined in a class of which a single copy exists, regardless of how many instances of the class exist. It does not depend on any object. There is only one unique value for all the objects of that same class. For the above reasons main in Java has a static keyword.
          public static void main(String args[])
The keyword static allows main() to be called without having to instantiate a particular instance of the class. This is necessary since main() is called by the Java interpreter before any objects are made. Before the main method is called, no objects are instantiated. Having the static keyword means the method can be called without creating any objects first. The main() method in C++, C# and Java are static because they can then be invoked by the runtime engine without having to instantiate an instance of the parent class. Now main without keyword static.
          public void main(String args[])
Exception in thread "main" java.lang.NoSuchMethodError: main (cannot find main because no object is initiated for main)
Since main method is static Java virtual Machine can call it without creating any instance of class which contains main method. Otherwise JVM has to create instance of main Class and since constructor main() can be overloaded and can have arguments there would not be any certain and consistent way for JVM to find main method in Java. All objects of non-primitive types can be created only via "new" in Java. There is no equivalent to creating non-primitive objects on the stack as in C++. Anything which is declared in class in Java comes under reference type and requires object to be created before using them but static method and static data are loaded into separate memory inside JVM called context which is created when a class is loaded. If main method is static than it will be loaded in JVM context and are available to execution.
-Static will remain reserved for the duration of the execution program. Consider this bit of code.
 char *func(void);

        main()
        {
            char *Text1;
            Text1 = func();
        }

        char *func(void)
        {
            char Text2[10]="martin";
            return(Text2);
        }

 Now, 'func' returns a pointer to the memory location where 'text2' starts BUT text2 has a storage class of 'auto' and will disappear when we exit the function and could be overwritten but something else. The answer is to specify
        static char Text[10]="martin";


class Student {
        int a; //initialized to zero
        static int b; //initialized to zero only when class is loaded not for each object created.

          Student(){
           //Constructor incrementing static variable b
           b++;
          }


           public void showData(){
              System.out.println("Value of a = "+a);
              System.out.println("Value of b = "+b);
           }
        //public static void increment(){
        //a++;
        //}

        }

        class Demo{
           public static void main(String args[]){
             Student s1 = new Student();
             s1.showData();
             Student s2 = new Student();
             s2.showData();
        //     Student.a++;  //cannot access instance variable "a" from static method "increment"
        //     s1.showData();
          }
        }
//: C10:StaticMemberFunctions.cpp
class X {
int i;
static int j;
public:
 X(int ii = 0) : i(ii) {
 // Non-static member function can access
 // static member function or data:
 j = i;
 }
 int val() const { return i; }
 static int incr() {
 //! i++; // Error: static member function
 // cannot access non-static member data
 return ++j;
 }
 static int f() {
 //! val(); // Error: static member function
 // cannot access non-static member function
 return incr(); // OK -- calls static
 int v;
 }
};
int X::j = 0;  // a static for all objects it works
//int X::i = 1;  // error: ‘int X::i’ is not a static member of ‘class X’

int main() {
 X x;
 X* xp = &x;
 x.f();
 xp->f();
 X::f(); // with static Only works with static members. error: cannot call member function ‘int X::f()’ without object
 x.f();  // without static need an object
// int X::j = 0;
} ///:~

C++ Static Class: C++ doesn't directly support a static class only Static data members and Static member functions. There is no "static class" in C++. The nearest concept would be a class with only static methods


See http://stackoverflow.com/questions/1303947/c-compiler-warning-returning-local-variable/35777878#35777878
class Three
{
    string *m_ob;
    int m_x, m_y, m_z;
public:
    Three(){}
    Three(string ob, int x, int y, int z): m_ob(new string(ob)), m_x(x), m_y(y), m_z(z) {}
    Three &operator+(Three &t)
    {
        static Three th;  //static here otherwise return this object is gone!
        th.m_ob = new string("Sum object");
        cout << "---------" << this->m_x << " " << t.m_x << endl;
        th.m_x = this->m_x + t.m_x;
        th.m_y = this->m_y + t.m_y;
        th.m_z = this->m_z + t.m_z;
        return th; //create in stack gone when return
    }

    friend ostream &operator<< (ostream &stream, Three t)
    {
        stream << *t.m_ob <<": ",
        stream << t.m_x << ",";
        stream << t.m_y << ",";
        stream << t.m_z << "\n";
        return stream;
    }
};

int main()
{
    Three ob1("ob1", 1, 2, 3), ob2("ob2", 4, 5, 6), ob3("ob3", 7, 8, 9);
    cout << ob1 << ob2 << ob3 << endl;
    Three ob = ob1 + ob2 + ob3;
    cout << ob << endl;
}
//Without static Three th will error: warning: reference to local variable ‘th’ returned [-Wreturn-local-addr]
//object create in stack it is gone when return. In c_cpp_reference when return value need static.

Inline functions versus Macros

 Although inline functions are similar to macros (because the function code is expanded at the point of the call at compile time), inline functions are parsed by the compiler, whereas macros are expanded by the preprocessor. As a result, there are several important differences:
  1.  Inline functions follow all the protocols of type safety enforced on normal functions.
  2.  Inline functions are specified using the same syntax as any other function except that they include the inline keyword in the function declaration.
  3.  Expressions passed as arguments to inline functions are evaluated once. In some cases, expressions passed as arguments to macros can be evaluated more than once.

    // inline_functions_macro.c
    
        #include <stdio.h>
        #include <conio.h>
    
        #define toupper(a) ((a) >= 'a' && ((a) <= 'z') ? ((a)-('a'-'A')):(a))
    
        int main() {
           char ch;
           printf_s("Enter a character: ");
           ch = toupper( getc(stdin) );
           printf_s( "%c", ch );
        }
    
        Input
    
        xyz
    
        Inline functions remedy the problem previously described.
    
        // inline_functions_inline.cpp
        #include <stdio.h>
        #include <conio.h>
    
        inline char toupper( char a ) {
           return ((a >= 'a' && a <= 'z') ? a-('a'-'A') : a );
        }
    
        int main() {
           printf_s("Enter a character: ");
           char ch = toupper( getc(stdin) );
           printf_s( "%c", ch );
        }
    
        Input
    
        a
    
        Output
    
        Enter a character: A

String, StringBuffer and StringBuilder in Java


Differences between String and StringBuffer in Java
Main difference between String and StringBuffer is String is immutable while StringBuffer is mutable means you can modify a StringBuffer object once you created it without creating any new object. This mutable property makes StringBuffer an ideal choice for dealing with Strings in Java. You can convert a StringBuffer into String by its toString() method. String vs StringBuffer or what is difference between StringBuffer and String is one of the popular interview questions for either phone interview or first round. Now days they also include StringBuilder and ask String vs StringBuffer vs StringBuilder. So be preparing for that. In the next section we will see difference between StringBuffer and StringBuilder in Java.
Difference between StringBuilder and StringBuffer in Java
StringBuffer is very good with mutable String but it has one disadvantage all its public methods are synchronized which makes it thread-safe but same time slow. In JDK 5 they provided similar class called StringBuilder in Java which is a copy of StringBuffer but without synchronization. Try to use StringBuilder whenever possible it performs better in most of cases than StringBuffer class. You can also use "+" for concatenating two string because "+" operation is internal implemented using either StringBuffer or StringBuilder in Java. If you see StringBuilder vs StringBuffer you will find that they are exactly similar and all API methods applicable to StringBuffer are also applicable to StringBuilder in Java. On the other hand String vs StringBuffer is completely different and there API is also completely different, same is true for StringBuilders vs String.


Java provides the StringBuffer and String classes, and the String class is used to manipulate character strings that cannot be changed. Simply stated, objects of type String are read only and immutable. The StringBuffer class is used to represent characters that can be modified.

The significant performance difference between these two classes is that StringBuffer is faster than String when performing simple concatenations. In String manipulation code, character strings are routinely concatenated. Using the String class, concatenations are typically performed as follows:
String str = new String ("Stanford ");
str += "Lost!!";
If you were to use StringBuffer to perform the same concatenation, you would need code that looks like this:
StringBuffer str = new StringBuffer ("Stanford ");
str.append("Lost!!"
More...
String s = "a" + "b" + "c";
It is rather pointless to use StringBuffer.
String s = new StringBuffer().append("a").append("b").append("c").toString();
String s = "";
for (int i = 0; i < 10; i++) {
s = s + Integer.toString(i);
}


Using string in this loop will generate 10 intermediate string objects in memory: "0", "01", "012" and so on. While writing the same using StringBuffer you simply update some internal buffer of StringBuffer and you do not create those intermediate string objects that you do not need:


StringBuffer sb = new StringBuffer();
for (int i = 0; i < 10; i++) {
sb.append(i);
}
Actually for the example above you should use StringBuilder (introduced in Java 1.5) instead of StringBuffer - StringBuffer is little heavier as all its methods are synchronized.

Summary:

In Java, String concatenation operator (+) is internally implemented using StringBuffer.
String str = "Hello" + "World";
Would be executed as,
Concatenation operator "+" is internal implemented using either StringBuffer or StringBuilder.
String str = new StringBuffer().append("Hello").append("World").toString();
First an empty StringBuffer will be created and then operands of the + operator would be appended using append method of the StringBuffer.
Finally toString() method of the StringBuffer would be called to convert it to string object and the same will be returned.
String concatenation using this approach is very expensive in nature, because it involves creation of temporary StringBuffer object. Then that temporary object’s append method gets called and the resulting StringBuffer should be converted to back String representation using toString() method.
When to use String and when StringBuffer?
If there is a need to change the contents frequently, StringBuffer should be used instead of String because StringBuffer concatenation is significantly faster than String concatenation
String is immutable while StringBuffer and StringBuilder is mutable object
When to use StringBuffer and when StringBuilder
StringBuffer is synchronized while StringBuilder is not which makes StringBuilder faster than StringBuffer.
Use String if you require immutability, use Stringbuffer in java if you need mutable + threadsafety and use StringBuilder in Java if you require mutable + without thread-safety
Ref:
http://javarevisited.blogspot.ca/2011/07/string-vs-stringbuffer-vs-stringbuilder.html http://www.javaworld.com/javaworld/jw-03-2000/jw-0324-javaperf.html

Const vs. Final

In Java const is just a reserve keyword, there is no const in Java. But it can be done similar to const in C++. You can create a constant variable in a class. To create a constant variable, type the final keyword to the left of the variable. Once again, when declaring a constant, you must initialize it with an appropriate constant value. static final in MAX_UNITS = 25; in C++ const MAX_UNITS = 25; A final variable in Java can be assigned to only once, but if the variable is a reference-type, you can still change what it refers to. A const variable in C++ can be assigned to only once, where it’s declared, and nothing is allowed to change about the value, whether it’s an object or not.

this Instance

If a class contains member variables and methods, the (non-static) member variables are automatically available to the method(s) of the class, even member variables that are private. When accessing a member variable or a method from another method of the class, to indicate that the member you are accessing belongs to the same class, you can precede it with the this member and the period operator.

C++ vs. Java

  1. C less rules than C++, C++ is less rules than Java. Java many things you don't have to worry but many rules have to follow.
  2. By default, all members of a class are private and all the members of structure are public in C++ and by default, all the members of a Java class are public. This means that if you do not use the public or the private keyword, a field is automatically made by default scope. (access specifiers to use specify the scope of members of the class and the class itself). If the class has no specifier by default then such a class will be accessible from inside the same package. The class can either public or no specifier.
    public or no modifier - the same way as used in the class level
    private - members can only access
    protected -can be accessed from the same package and a subclass existing in any package can access.
  3. Java has char type uses the international 16-bit Unicode, C++ has char type 1 byte for 32-bit system and 2 bytes for 64-bit system.
  4. C-language did not contain any data types to represent a Boolean value. Both the C++ and Java languages have Boolean types.
    C++
    bool foo;
    Java
    boolean foo;
     
    
    
  5. Pointers
    The Java language does not include pointers. The reason for this is simple: pointers tend to cause confusion in the code, and they are a common source of bugs. Java references are pointers to Java objects, but you can't use Java references in the same way that you can use C pointers. Java references cannot be incremented or decremented, you can't convert references to or from primitive types, and there are no address of operators, such as &, or dereferencing operators, such as -> or *.
  6. Global variables: Unlike C and C++, the Java language offers no way to declare global variables (or methods).
  7. The preprocessor: The Java platform does not have a preprocessor, nor does it have any preprocessor directives or macros.
  8. goto: Although the Java language reserves goto as a keyword, there is no goto statement like the one used in C.
  9. struct, union, typedef, enum: The Java language does not have the struct or union types, nor does it have the typedef or enum keywords.
  10.  Freely placed variables: Java variables can be declared anywhere, as they are needed. Variables do not need to be grouped together at the top of a block, as they do in C.
  11. Freely placed methods: C requires that function declarations appear before they are invoked, but Java methods can be invoked before they have been declared.
  12. Garbage collection: The Java platform uses a garbage collector to
    automatically reclaim memory by recycling objects when they are no
    longer referenced. The malloc() and free() functions used by C
    aren't necessary in Java programming, and no similar methods exist for
    the Java language.
  13. No difference between Access Modifiers and Access Specifiers. Different names for the same.
    Access modifiers: abstract, final and strictfp . Access specifier: public,private, protected or default. 
    Java access Specifier are used to specify how the member variable ,methods or class to other classes.
    They are public ,private and protected.
    
    Access Modifier:
       1.Access
       2.Non Access
    
    Access:
        public ,private,protected and default.
    Non Access:
     abstract,final,native,static,synchronized,transient,volatile
     and strictfp
     
  14. What's the difference between an interface and an abstract class?
    • An abstract class is a class that is only partially implemented by the programmer. It may contain one or more abstract methods. An abstract method is simply a function definition that serves to tell the programmer that the method must be implemented in a child class.
    • An interface is similar to an abstract class; indeed interfaces occupy the same namespace as classes and abstract classes. For that reason, you cannot define an interface with the same name as a class. An interface is a fully abstract class; none of its methods are implemented and instead of a class sub-classing from it, it is said to implement that interface.
    • Abstract classes can have constants, members, method stubs and defined methods, whereas interfaces can only have constants and methods stubs.
    • Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public.
    • When inheriting an abstract class, the child class must define the abstract methods, whereas an interface can extend another interface and methods don't have to be defined.
    • A child class can only extend a single abstract (or any other) class, whereas an interface can extend or a class can implement multiple other interfaces.
    • A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility 
  15. When to use abstract class or interface?
    • Interface is used when you only want to declare which methods and members a class MUST have. Anyone implementing the interfaca will have to declare and implement the methods listed by the interface.
    • If you also want to have a default implementation, use abstract class. Any class extending the abstract class will have to implement only its abstract methods and members, and will have some default implementation of the other methods of the abstract class, which you may override or not.
    • Finally, you can implement as many interfaces as you want, but only extend one class (being it abstract or not). Keep that on mind before choosing.
    • public class C implements A, B{... }
    • public class C extends A{...}
    • Abstract class is an incomplete implementation of some concept. This incomplete implementation may be different in different context. Derived class implements the abstract class in its context.
    • Interface defines contract or standard. Implementation of the interface has to follow the contract or standard. Interfaces are more used to set these types of standards or contract
  16.  What does the Serializable interface do ?
    • The Serializable interface is just a marker. It means that objects can be serialized, i.e. they can be represented as a bit string and restored from that bit string. For example, both of your classes are serializable because they can be represented as a bit string (or regular string). On the other hand, a class that represents a file handle given out by the operating system can not be serialized: As soon as the program is finished, that handle is gone, and there is no way to get it back. Reopening the file by file name is not guaranteed to work, since it may have been deleted/moved/changed permissions in the meantime.
    • Serializing objects that don't implement the Serializable interface will result in a NotSerializableException being thrown
  17. How you can force the garbage collection ?
    • Garbage collection automatic process and can't be forced. You could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.
    • Garbage collection is one of the most important feature of Java, Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program can't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program.
    •  Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.
  18. What is Synchronization in Java?
    • Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time.
    •  In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value.
  19. What is memory leak?
    • A memory leak is where an unreferenced object that will never be used again still hangs around in memory and doesnt get garbage collected.
  20.  What is the difference between checked and unchecked exceptions?
    • In general, unchecked exceptions represent defects in the program (bugs), which are normally Runtime exceptions.
    •  Furthermore, checked exceptions represent invalid conditions in areas outside the immediate control of the program.
  21.  How does Java allocate stack and heap memory?
    •  Each time an object is created in Java it goes into the area of memory known as heap. The primitive variables like int and double are allocated in the stack, if they are local method variables and in the heap if they are member variables (i.e. fields of a class).
    • In Java methods local variables are pushed into stack when a method is invoked and stack pointer is decremented when a method call is completed.
    •  In a multi-threaded application each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space.
    •  The stack is threadsafe (each thread will have its own stack) but the heap is not threadsafe unless guarded with synchronisation through your code
  22. What is Java Reflection?
    • Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine.

    Friday, July 13, 2012

    LinkedList

    In C++
    /*
     * part1.h
     *
     */
    
    #ifndef PART1_H_
    #define PART1_H_
    
    #pragma once
    
    //---------------------------------------------------------------------------
    struct CarPart
    {
     long     PartNumber;
     char     PartName[40];
     double   UnitPrice;
     CarPart* Next;
    
    };
    
    //---------------------------------------------------------------------------
    class ListOfParts
    {
     int size;
    
    public:
     ListOfParts();
     int Count();
     CarPart* Head;
    
     int Add(CarPart* Item);
     CarPart *Retrieve(int pos);
     bool Delete();
    };
    
    #endif /* PART1_H_ */
    
    #include <iostream>
    #include "parts1.h"
    using namespace std;         //otherwise std::cout
    
    
    //---------------------------------------------------------------------------
    ListOfParts::ListOfParts()  //constructor
    // : size(0), Head(NULL)
    {
     size = 0;
     Head = NULL;  // either way : size(0), Head(BULL)
    }
    //---------------------------------------------------------------------------
    int ListOfParts::Count()
    {
     return size;
    }
    //---------------------------------------------------------------------------
    
    int ListOfParts::Add(CarPart *NewItem)
    {
     CarPart *Node = new CarPart;  //add struct CarPart into the class
    
     Node          = NewItem;
     Node->Next    = Head;   //of the struct pointer Next
     Head          = Node;   // of class pointer Head
     return size++;
    }
    //---------------------------------------------------------------------------
    CarPart *ListOfParts::Retrieve(int Position)
    {
     CarPart *Current = Head;
     for(int i = 0; i < Position && Current != NULL; i++)
     {
      Current = Current->Next;
     }
     return Current;
    }
    //---------------------------------------------------------------------------
    bool ListOfParts::Delete()
    {
     if( Head == NULL )
     {
      cout << "The list is empty\n";
      return false;
     }
     else
     {
      CarPart *Current;
    
      Current = Head->Next;
      Head->Next = Current->Next;
      size--;
      return true;
     }
    }
    
    #include <iostream>
    #include <string.h>
    #include <stdio.h>
    
    #include "parts1.h"
    
    
    using namespace std;
    
    //---------------------------------------------------------------------------
    int main()
    {
     ListOfParts *Parts = new ListOfParts();     //class
     CarPart     *Part;       //struct
    
     // Visual C++ 6 can't "scope" a variable in a for loop
     int i;
    
     Part  = new CarPart;
     Part->PartNumber = 9743;
     strcpy(Part->PartName, "Air Filter");
     Part->UnitPrice  = 8.75;
     Parts->Add(Part);
    
     Part  = new CarPart;
     Part->PartNumber = 27487;
     strcpy(Part->PartName, "Clutch Disk");
     Part->UnitPrice  = 47.15;
     Parts->Add(Part);
    
     Part  = new CarPart;
     Part->PartNumber = 87873;
     strcpy(Part->PartName, "Brake Disk");
     Part->UnitPrice  = 35.15;
     Parts->Add(Part);
    
     Part  = new CarPart;
     Part->PartNumber = 27644;
     strcpy(Part->PartName, "A/C Filter Drier");
     Part->UnitPrice  = 55.55;
     Parts->Add(Part);
    
     cout << "Number of Parts: " << Parts->Count() << endl;
    
     cout << "\n-=- List of Parts -=-";
     for(i = 0; i < Parts->Count(); i++)
     {
      CarPart* One = Parts->Retrieve(i);
    
      cout << "\nCar Part Information";
      cout << "\nPart #:      " << One->PartNumber;
      cout << "\nDescription: " << One->PartName;
      cout << "\nUnit Price: $" << One->UnitPrice << endl;
     }
    
     Parts->Delete();
    
     cout << "\nNumber of Parts: " << Parts->Count() << endl;
    
     cout << "\n-=- List of Parts -=-";
     for(i = 0; i < Parts->Count(); i++)
     {
      CarPart* One = Parts->Retrieve(i);
    
      cout << "\nCar Part Information";
      cout << "\nPart #:      " << One->PartNumber;
      cout << "\nDescription: " << One->PartName;
      cout << "\nUnit Price: $" << One->UnitPrice << endl;
     }
    
     return 0;
    }
    Output:
    Number of Parts: 4
    
    -=- List of Parts -=-
    Car Part Information
    Part #:      27644
    Description: A/C Filter Drier
    Unit Price: $55.55
    
    Car Part Information
    Part #:      87873
    Description: Brake Disk
    Unit Price: $35.15
    
    Car Part Information
    Part #:      27487
    Description: Clutch Disk
    Unit Price: $47.15
    
    Car Part Information
    Part #:      9743
    Description: Air Filter
    Unit Price: $8.75
    
    Number of Parts: 3
    
    -=- List of Parts -=-
    Car Part Information
    Part #:      27644
    Description: A/C Filter Drier
    Unit Price: $55.55
    
    Car Part Information
    Part #:      27487
    Description: Clutch Disk
    Unit Price: $47.15
    
    Car Part Information
    Part #:      9743
    Description: Air Filter
    Unit Price: $8.75
    
    In Java, it is much simple with a lot of less lines. Java has so many rules but it can be easy when you are master of the rules. I try to output the same format as C++. But it does more for example removeLast/removeFirst/getFirst/getLast item of the list and so on....LinkedList is a part of java.util.* so it is much easy.
    //http://www.javatutorialhub.com/java-arrays.html
    import java.util.*;
    
    class CarPart{
     long     PartNumber;
     String   PartName;
     double    UnitPrice;
     CarPart(int i, String s, double j){
       PartNumber = i;
       PartName = s;
       UnitPrice = j;
     }
       public String toString() {
            
            System.out.println("Car Part Information");
         return "Part #:  "+ PartNumber + "\n" +"Description: "+ PartName + "\n" + "Unit Price " + UnitPrice;
        }
     
    }
    
    class LinkedListPart{
       public static void main(String args[]){
         LinkedList<CarPart> parts = new LinkedList<CarPart>();
         parts.add(new CarPart(9743,"Air Filter",8.75));
         parts.add(new CarPart(27487,"Clutch Disk",47.15));
         parts.add(new CarPart(87873,"Brake Disk",35.15));
         parts.add(new CarPart(27644,"A/C Filter Drier",55.55));
         System.out.println("Number of Parts " + parts.size());
         for (CarPart element : parts) 
           System.out.println(element + "\n");
         parts.remove(0); 
         System.out.println("--After remove first part from LinkedList---"); 
         for (CarPart element : parts) 
           System.out.println(element + "\n");
         parts.removeLast();
         System.out.println("---After remove last part from LinkedList---"); 
          for (CarPart element : parts) 
           System.out.println(element + "\n");
      }
    }
    
    Output:
    Number of Parts 4
    Car Part Information
    Part #:  9743
    Description: Air Filter
    Unit Price 8.75
    
    Car Part Information
    Part #:  27487
    Description: Clutch Disk
    Unit Price 47.15
    
    Car Part Information
    Part #:  87873
    Description: Brake Disk
    Unit Price 35.15
    
    Car Part Information
    Part #:  27644
    Description: A/C Filter Drier
    Unit Price 55.55
    
    --After remove first part from LinkedList---
    Car Part Information
    Part #:  27487
    Description: Clutch Disk
    Unit Price 47.15
    
    Car Part Information
    Part #:  87873
    Description: Brake Disk
    Unit Price 35.15
    
    Car Part Information
    Part #:  27644
    Description: A/C Filter Drier
    Unit Price 55.55
    
    ---After remove last part from LinkedList---
    Car Part Information
    Part #:  27487
    Description: Clutch Disk
    Unit Price 47.15
    
    Car Part Information
    Part #:  87873
    Description: Brake Disk
    Unit Price 35.15
    

    Tuesday, July 03, 2012

    Why default constructor is required(explicitly) in a parent class if it has an argumented constructor

    class A {    
      A(int i){    
      }
    }
    class B extends A {
    }
    class Main {    
      public static void main(String a[]){
        B b_obj = new B();
      }
    }
    
    This will be an error: cannot find symbol constructor in B If we don't have argument constructor the compiler will insert super() the first line in derived class constructor. Since the parent has parameter(arguments) constructor, it supersedes the default constructor in A, the compiler could not find the default constructor per error showing therefore so we need to insert the default constructor.
    So class A will have 2 constructors: default A(){} and A(int i){}.
    2 ways to fix it
    - has a default constructor in parent class A
    - has a super(int) in B constructor
    class A {    
      A(int i){    
      }
    
      A(){}     //insert the default constructor in the base class, derived class unchanged 
    }
    class B extends A {
    }
    class Main {    
      public static void main(String a[]){
        B b_obj = new B();
      }
    }
     
    
    class A {    
      A(int i){    
      } 
    }
    class B extends A {
    
      B(int i) {    // add constructor for B with super(i) in the 1st line
    
      super(i); 
    
      }
    }
    class Main {    
      public static void main(String a[]){
        B b_obj = new B(2); //constructor has a value
      }
    }
    
    Same thing in C++ you need to create a default constructor for base class if the base class has arguments constructor as long as this argument/parameter constructor is exist the compile will not create default constructor. In Java you can use "super" keyword to call parameter constructor is must be the first line of derived/child constructor. To be compatible for both C++ and Java it is always good to have the parent default constructor.
    class A { 
     int i;
      public:  
      A(){}  
      A(int i){}   //A(int i) no default constructor you have to create one above A(){} like Java
    };
    class B : public A {
      public:
    };
    
    int  main(){
       B *b_obj = new B;  // for B compiler will use default constructor B(){} requires A(){}
    }
    
    See this for the full behaviors of C++ WRT constructors: http://en.wikipedia.org/wiki/Default_constructor
    if you specify a constructor, the compiler will not create a default one for you. The compiler will define a default ctor if and only if you don't explicitly declare any ctors. It is confusing when there is a parent and child class (derived class). In the above examples, we think that the compiler will generate the default constructor for the child class since there is no constructor is defined so it creates a default constructor for the child but when the object is created in the child class, the parent constructor is called first then the child constructor, this is where the error happens because it could not find the default constructor in the parent class.
    This rule applies to Java and C++ as well.
    Another way to do is let the child class initializes the base class ctor then no default ctor at base class as long as the compiler know there is one ctor is defined so it does not look for a default ctor. This is the case there is no source code for base class just a library to link and it can be set in the derived class (child class)
    #include <iostream>
    using namespace std;
    
    class A { 
     int i;
      public:  
      //A(){}  
      A(int i){}   //A(int i) no default constructor you have to create one above A(){} like Java
    };
    class B : public A {
     public:
     int j;
     B():A(j){}   // derived class initialize the base class constructor
    };
    
    int  main(){
       B *b_obj = new B;
    }
    

    Thursday, June 07, 2012

    Java Threads for Hello World

    //Extends Threads class DispThread extends Thread {
    String msg;

        public void run() {
        try {
        for(int i = 2; i > 0; i--) {  //delay
        System.out.println("Child Thread: " + i);
        Thread.sleep(10000);
        }
        } catch (InterruptedException e) {
            System.out.println("Child interrupted.");
        }
          
            System.out.println("Exiting child thread." + msg);
        }
        public DispThread(String m){
            msg = m;
        }
    }
    class ThreadTest {
        public static void main(String args[]) {
       
          DispThread dt1 = new DispThread("Hello");
          DispThread dt2 = new DispThread("World");
          dt1.start();  // call user thread from main thread
          dt2.start();
       
        }
    }
    With the delay the output
    Running tool: javac

    javac ThreadTest.java
    java ThreadTest
    Child Thread: 2
    Child Thread: 2
    Child Thread: 1
    Child Thread: 1
    Exiting child thread.Hello
    Exiting child thread.World

    Done.

    //Implements Runnable
    class DispThread implements Runnable {
    String msg;

        public void run() {
        try {
       for(int i = 5; i > 0; i--) {  //delay or sleep
        System.out.println("Child Thread: " + i);
        Thread.sleep(500);
         }
        } catch (InterruptedException e) {
           System.out.println("Child interrupted.");
          }
            System.out.println("Exiting child thread." + msg);
        }
        public DispThread(String m){
            msg = m;
        }
    }

    class ThreadTest1 {
        public static void main(String args[]) {
       
          DispThread dt1 = new DispThread("Hello");
          DispThread dt2 = new DispThread("World");
          Thread t1 = new Thread(dt1);   //because implements need to create an object
          Thread t2 = new Thread(dt2);
          t1.start();
          t2.start();
       
        }
    }
    //Without delay the output
    Running tool: javac

    javac ThreadTest1.java
    java ThreadTest1
    Exiting child thread.World
    Exiting child thread.Hello

    Done.

    //No Thread just println
    public class Hi {
    public static void main(String argv[]){
       System.out.println("Hello World");
       }
    }
    javac Hi
    Hello World

    Done.

    Interface (virtual function in C++) - Polymorphism

    interface Animal
    {

        String getName();   //Abstract String getName() is ok too??
        String talk();
    }


    class Cat implements Animal
    {
        public String name;
        public Cat(String name)   //constructor
        {       
            this.name = name;
            //System.out.println(name);
        }

        public String talk()
        {
            return "Meowww!";
        }

        @Override
        public String getName() {
            // TODO Auto-generated method stub
            System.out.println("GetnameCat = " + name);
            return name;
        }
    }

    class Dog implements Animal
    {
        public String name;
        public Dog(String name)
        {
            this.name = name;
        }

        public String talk()
        {
            return "Arf! Arf! Arf!";
        }

        @Override
        public String getName() {
            // TODO Auto-generated method stub
            System.out.println("GetnameDog = " + name);
            return name;
        }
    }

    class TestAnimals     //name has to be in this case with or without public is ok 
    {
        // prints the following:
        //
        // Missy: Meowww!
        // Mr. Mistoffelees: Meowww!
        // Lassie: Arf! Arf!
        //
        public static void main(String[] args)
        {

                  
               Animal[] animals =
            {
                new Cat("Missy"),
                new Cat("Mr. Mistoffelees"),
                new Dog("Lassie")
            };
         
    //java for each Loops without index otherwise (int i; i < animals.length; i++)
                  for (Animal a: animals)
                {
                System.out.println(a.getName() + ": " + a.talk());
                }
        }
    //--C++ virtual function
    #include <iostream>
    #include <string>

    using namespace std;

    class Animal
    {
            public:
            Animal(const string& name) : name(name) {};
            virtual string talk() = 0;  //Need pure virtual function here
            //virtual string talk();
            const string name;
    };

    class Cat : public Animal
    {
            public:
            Cat(const string& name) : Animal(name) {};
            virtual string talk() { return "Meow!"; }
    };

    class Dog : public Animal
    {
            public:
            Dog(const string& name) : Animal(name) {};
            virtual string talk() { return "Arf! Arf!"; }
    };

    // prints the following:
    //
    // Missy: Meow!
    // Mr. Mistoffelees: Meow!
    // Lassie: Arf! Arf!
    //
    int main()
    {
            Animal* animals[] =
            {
                    new Cat("Missy"),
                    new Cat("Mr. Mistoffelees"),
                    new Dog("Lassie")
            };

            for(int i = 0; i < 3; i++)
            {
                    cout << animals[i]->name << ": " << animals[i]->talk() << endl;
                    delete animals[i];
            }
            return 0;
    }
    UML: Generated by Umbrello: Import the code to generate the diagram or diagram to code generating it can be used to understand OOP or see how it translates between Java and C++ with very limited. It is great to study it is easy to use but not that good as Rational Rose. It is running under linux.

    Friday, January 25, 2008

    mm-applet

    It popups 2 windows:
    This has nothing to do with root privileges, you are prompted this message because nm-applet wants to use the wifi key (WEP i guess) stored in the keyring. What is the gnome-keyring?

    mm-applet
    Passphrase required by wireless network – A passphrase or encryption key is requred to access wireless network linksys

    to disable by delete /home/YOUR NAME/.gnome2/keyrings/default.keyring

    if connect to other AP then mm-applet and Passphrase may appear again then you can do from terminal

    you could ignore it and enter

    iwconfig wlan0 ESSID " " mode Managed key .... and it's still working

    in case the icon for wireless disappear can bring it back by Computer > Filesystem > usr > bin"
    then double click to run "nm-applet

    http://www.linuxquestions.org/questions/linux-general-1/keyring-problem-415928/
    http://ubuntuforums.org/showthread.php?t=622066

    Tuesday, May 16, 2006

    ActiveX vs. Java Applet

    ActiveX is a technology developed by Microsoft. With an ActiveX-enabled browser (ie Internet Explorer only) ActiveX controls can be downloaded as part of a Web document to add functionality to the browser (similar to Java applets). In particular ActiveX enables seamless viewing of Windows files of all types, eg spreadsheets, and in combination with other technologies such as Java and scripting languages, makes possible the development of complex Web applications. ...

    Does Active X works with Linux, I guess it is not because it is not windows, I tried Java applets for dialing to Netzero (ISP), it is all works for both linux and windows. Linux needs jre-1_5_0-linux-i586.bin and windows need C:\Program Files\Java\jre1.5.0_01\bin\npjpi150_01.dll

    Linux:
    download netzero.deb
    cp netzero.deb /
    cd /
    ar -xv netzero.deb
    gunzip data.tar.gz
    tar xvf data.tar
    Install java jre
    cd /opt/nzclient
    ./runclient.sh

    Create a file to get on desktop of cd ~/gnome-desktop links/associated to /java/jre-1_5_0/opt/runclient.sh
    Click to dial from desktop of gnome.

    Thread vs. process

    One difference: Threads within a process share a single address space, and can, with care (synchronization), access one another's variables. Processes run in different address spaces, and must use inter-process communications mechanisms to exchange information.
    Processes Versus Threads


    Other Terms:

    Heavyweight Process = Process
    Lightweight Process = Thread


    Advantages (Thread vs. Process):

    Much quicker to create a thread than a process.
    Much quicker to switch between threads than to switch between processes.
    Threads share data easily


    Disadvantages (Thread vs. Process):

    No security between threads: One thread can stomp on another thread's data.
    For threads which are supported by user thread package instead of the kernel:
    If one thread blocks, all threads in task block

    Thread States (Example Java):

    New = New: Placed on the ready list.
    Blocked = Wait for an event
    Runnable = Ready or Running
    Dead = Exit


    Thread functions: POSIX (Standard UNIX C/C++):

    pthread_create(): creates a thread
    pthread_exit(): kills itself
    pthread_kill(): sends a signal to a specified thread
    pthread_join(): waits for a thread to exit.
    pthread_self(): returns thread id
    synchronization functions


    Java Implementation
    http://objectlayer.blogspot.ca/2012/06/java-threads-for-hello-world.html
    Define a class to contain a thread, by defining:
    class Worker1 extends Thread OR
    class Worker2 implements Runnable (Recommended)
    The parent thread creates the object and invokes its start() function.
    The start function creates the child thread and calls the object’s run() function.
    Thread terminates when thread returns from run(), or stop() is called.

    Types of Thread Implementations


    User Thread Package

    A package outside the OS creates and schedules threads.
    Model: Many-to-one: Many user threads associated with one process.
    Thread creation/management is faster than Kernel Thread support
    However if one thread blocks, then entire process blocks. Thus all threads block.


    Kernel Thread Support

    The OS creates and schedules threads.
    Model: One-to-one: Each user thread is associated with one kernel thread.
    If one thread blocks, the kernel can schedule other threads.
    If multiprocessor configuration, kernel can allocate threads of same process on different processors.
    Example: Windows NT, Solaris, Digital UNIX

    Many-to-Many Model: Combination of above

    N user threads share M kernel threads (where N > M)
    There may be a flexible and changing assignment of user threads to kernel threads.
    Bound: User-thread is assigned permanently to kernel thread
    Unbound: User threads share available kernel threads
    Example: Solaris
    ----------------------deadlock vs. race condition
    DeadlocksA deadlock occurs when one or more threads are permanently blocked from executing because each thread waits on a resource held by another thread in the deadlock. A thread can also deadlock on itself. The simplest case of deadlock occurs when process p1 gains access to data structure a and process p2 gains access to b, but p1 then waits for b and p2 waits for a.
    A deadlock
    occurs when one or more threads are stuck waiting for something that never will
    occur.(advanced linux program p.82)
    Race Conditions
    A race condition occurs when two or more threads perform an operation, and the result of the operation depends on unpredictable timing factors; specifically, when each thread executes and waits and when each thread completes the operation.
    The result is trouble. Because both processes see the same scull device, each will
    store its new memory in the same place in the quantum set. If A stores its pointer
    first, B will overwrite that pointer when it does its store. Thus the memory allocated by A, and the data written therein, will be lost.

    Saturday, January 21, 2006

    C++ vs. Java

    - Java does not have pointer but instead has non primative variables that references
    - Java avoids much of the direct programmer management of memory that causes so many bugs in C and C++
    - Java does not have arrays which are references
    - Java does not have functions that are outside the scope of a class
    - Java's term for function is method
    - Multiple inheritance and concept of virtual inheritance in C++. No multiple inheritance in Java. Can get around by user interface
    - By default member of class are privates where Java a default member function/variables are visibility
    - Platform independence in Java which is not in C++
    - All member function in Java class are virtual by default, where C++ need specified
    - Constructor can be called from other constructors using this() in Java, this is not in C++

    Thursday, January 19, 2006

    What is Polymorphism ?

    Polymorphism is the capability to bind a specific derived class object to base class pointer at run-time.

    What is Class ?

    A class is a blue-print or prototype defines the variables, functions/methods for an object.
    class class_name {
    permission_label_1:
    member1;
    permission_label_2:
    member2;
    ...
    } object_name;

    What is object ?

    An object is a software bundle of related variables and methods. Software objects are often used to model real world objects that we found in everyday life.
    A class is the blueprint from which individual objects are created.
    An object is an individual instance of a class.