Static keyword
1) static variables
2) static methods
3) static blocks of code.
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 JVMclass 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.
- 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:
- Inline functions follow all the protocols of type safety enforced on normal functions.
- Inline functions are specified using the same syntax as any other function except that they include the inline keyword in the function declaration.
- 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!!";
str += "Lost!!";
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
- 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.
- 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. - 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.
- 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;
- 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 *. - Global variables: Unlike C and C++, the Java language offers no way to declare global variables (or methods).
- The preprocessor: The Java platform does not have a preprocessor, nor does it have any preprocessor directives or macros.
- goto: Although the Java language reserves goto as a keyword, there is no goto statement like the one used in C.
- struct, union, typedef, enum: The Java language does not have the struct or union types, nor does it have the typedef or enum keywords.
- 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.
- Freely placed methods: C requires that function declarations appear before they are invoked, but Java methods can be invoked before they have been declared.
- 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. 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- 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
- 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
- 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
- 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.
- 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.
- 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.
- 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.
- 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
- 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.