Java is object oriented, platform independent,secure,robust,simple,etc
Platform independence means that we can write and compile the java code in one platform (eg Windows) and can execute the class in any other supported platform eg (Linux,Solaris,etc).
Byte code is a set of instructions generated by the compiler. JVM executes the byte code.
A Java source file on compilation produces an intermediary .class rather than a executable file. This .class file is interpreted by the JVM. Since JVM acts as an intermediary layer.
JVM is Java Virtual Machine which is a run time environment for the compiled java class files.
JVM's are not platform independent. JVM's are platform specific run time implementation provided by the vendor. A Windows JVM cannot be installed in Linux.
Any software vendor can provide a JVM but it should comply to the Java langauge specification.
JDK is Java Development Kit which is for development purpose and it includes execution environment also. But JVM is purely a run time environment and hence you will not be able to compile your source files using a JVM.
Pointer is a reference handle to a memory location. Improper handling of pointers leads to memory leaks and reliability issues hence Java doesn't support the usage of pointers.
Both object reference and pointer point to the memory location of the object. You can manipulate pointers but not object references.
Java doesn't support multiple inheritance.
When a class inherits from more than class, it will lead to the diamond problem - say A is the super class of B and C & D is a subclass of both B and C. D inherits properties of A from two different inheritance paths ie via both B & C. This leads to ambiguity and related problems, so multiple inheritance is not allowed in Java.
Java is a pure object oriented language. Except for the primitives everything else are objects in Java.
Path and Classpath are operating system level environment variales. Path is used define where the system can find the executables(.exe) files and classpath is used to specify the location .class files.
Operator overloading makes the code very difficult to read and maintain. To maintain code simplicity, Java doesn't support operator overloading.
Keywords cannot be used as identifiers.
Few of the words are reserved as keywords for future usage. Compiler forces the developer not to use a reserved keyword. const and
When a new keyword is used in a new version of the JDK, there is high chances that has been used by developers as identifiers. This make tougher for the code base to migrate to new version since it requires code change, recompilation,testing and release cycle.
Yes. enum keyword was used extensively as identifier in one of our project - we had to change the code in a lot of places to migrate it to newer v ersion.
Identifiers are names given to a variable, method, class and interface. Identifiers must conform to the following rules:
a. The identifiers can contain a to z, A to Z,0 to 9,_ and $.
b. Special characters other than _ and $ cannot be used in identifiers.
c. Identifiers cannot start with numbers.
d. keywords cannot be used as identifiers.
Naming conventions are part of coding standards which are prescribed for better readability and maintenance. The following are simple conventions followed in Java:
1. Instance and local Variables should start with a lowercase and subsequent word should start with a capital letter. Examples:
int quantity;
double unitPrice;
2. Class level variables ie constants should be in capital letters and _ is used word seprator
final static double PI = 3.14;
final static int MAX_PRIORITY = 10;
3. Method names should start with small case and subsequent word should be capital letter.
public double getAvailableBalance(String accountNo) throws InvalidAccountException{}
4. Classes and Interfaces should start with a capital letter and subsequent words should also be capital letters.
public class HelloWorld{}
No. These are standards. Each company or fot that matter each software unit might have its own coding standards. These are not enforced by the compiler.
The best and simple way is to do peer reviews and code walkthroughs. You can use external plugins to your IDE (integrated development environment) to enforce during coding itself.
Literals are source code representation of primitive data types.
boolean, byte, short, int, long, float, double and char.
Primitive data types are not objects.
Excpet boolean and char, others are number data types and they are all signed which means that they can hold both positive and negative values.
The boolean is the simplest data type which can hold true or false.
Values which are defaulted during object initialisation are called default values. Each data type has a default value.
For boolean data type, it is false. For byte,short,int and long, it is 0. For float and double, it is 0.0. For char, the default value is 'u000'.
Yes. Object references are defaulted to null.
If arrays is just declared but not initialised then the array reference will be defaulted to null. This is because arrays are objects in Java.
int arr[]; // Here the arr reference is defaulted to null.
If array values are not assigned, then will be defaulted to their respective default values.
double priceRange[] = new double[3]; // Here all the elements in the array will be defaulted to 0.0 - the default value of double.
String str[] = new String[3]; // Here all the elements will be defaulted to null - the default value for object references.
Consider the below statement:
int i = 10;
Here int is the keyword which has special meaning attached Java programming langauge ie whatever is declared is an integer value.
i is the identifier or the variable name.
10 is the literal or the actual value.
The following are the 3 different ways to represent an integer value:
int i = 123 // this is the usual decimal representation.
int i = 0123 // this is octal representation. Octal values start with a zero.
int i = 0XCAAD // this is hexadecimal representation. Hexadecimal values start with 0X.
Char value can be represented in 3 ways. They are as follows:
char ch = 'A'; // represented using single quotes.
char ch = 'u0041'; // represented using unicode representation.
char ch = 41; // represented using integer value.
char is internally represented as a unsigned 16 bit integer value ie it will accept integer values from 0 to 65536.
Yes. A fine example is switch statement will accept char value for multiway condition checking.
Yes possible. The below is an example.
char ch = 'A';
System.out.println(ch++);
The above statement will print B. ++ is a numeral operand and since char is internally represented as integer, ++ operand can be applied on char value.
A universal, 16-bit, standard coded character set for the representation of all human scripts.
It will be represented as a double value. Floating point literals are always double by default. If you want a float, you must append an F or f to the literal.
The statement will result in RuntimeException (DivideByZeroException). Integer values cannot be divided by zero.
This will compile and execute fine. The result will be Infinity
a variable is a facility for storing data. The current value of the variable is the data actually stored in the variable.
There are 3 types of variables in Java. They are :
1. Local variables.
2. Instance variables.
3. Class variables.
Local varaiables are those which are declared within a block of code like methods, loops, exception blocks, etc. Local variables should be initialised before accessing them. Local variables are stored on the stack, hence they are sometimes called stack variables. They are also called as method variables or block variables.
As soon as the block is completed the variables are eligible for GC. Block could be a condition, a loop, a exception block or a method
Consider the below class:
public class Test {
public static void main (String str[]){
String name = str[0];
for (int i=0; i<=10; i++){
System.out.println(name + i);
}
}
}
In the above the class, the variable i is eligible for garbage collection immediately after the completion of for loop.
name string variable and str[] argument are eligible for GC after the completion of main method.
Instance variables are those which are defined at the class level. As we know, object have identity and behaviour - the identity is provided by the instance variables. These are also called as object variables. Instance variables need not be initialized before using them. Instance variables will be initialized to their default values automatically when not initialized.
No. Arrays are not primitives - they are objects.
Object obj[]; // most frequently used form of array declaration.
Object []obj; // nothing wrong with this.
Object[] obj; // nothing wrong with this.
int i[][]; // most frequently form multi-dimensional array
int[] i[]; // nothing wrong with this.
int[] i[],j; // nothing wrong with this. Important : i is double dimensional whereas j is single dimensional.
declaration,initialization and assignment
int i[]; // array declaration.
i[] = new int[2]; // array initialization.
i[0] = 10; i[1] = 7; i[2] = 9; // element value assignment.
The below statement merges declaration,initialization and assignment into a single step:
int i [] = {10, 20, 30 40};
length is an instance variable of array object - here it is given a method.
length of an array should be given when it is initialized. Here it is given during declaration. It will result in compilation error.
It will print 6. Remember array indexes start with 0.
ArrayIndexOutOfBoundsException and NullPointerException.
No not required. main method should be defined only if the source class is a java application.
Main method doesn't return anything hence declared void.
main method is the entry point for a Java application and main method is called by the JVM even before the instantiation of the class hence it is declared as static. static methods can be called even before the creation of objects.
main method accepts an array of String objects as argument.
You should pass the argument as a command line argument. Command line arguments are seprated by a space. The following is an example:
java Hello Tom Jerry
In the above command line Hello is the class, Tom is the first argument and Jerry is the second argument.
If you dont access the argument, the main method will execute without any problem. If try to access the argument, NullPointerException will be thrown.
Yes. You can have any number of main methods with different method signature and implementation in the class.
Yes. Any inheriting class will not be able to have it's own default main method.
No it doesn't matter but void should always come before main().
Yes. A single source file can contain any number of Class declarations but only one of the class can be declared as public.
2 class files will be generated by the compiler.
Yes. Comments can appear anywhere in the code. It is just a "skip this line" instruction to the conpiler.
If the class in the source is not of public access, then the name can be anything but should confirm to identifier rules.
Inheritance is a concept where the properties and behaviour of a class is reused in another class. The class which is being reused or inherited is called the super class or the parent class. The class which is inheriting is called the subclass or the child class of the inherited class.
No. Java Supports only single inheritance.
When a class inherits from more than class, it will lead to inheritance path amibiguity (this is normally calledthe diamond problem). Say A is the super class of B and C & D is a subclass of both B and C. D inherits properties of A from two different inheritance paths ie via both B & C. This leads to ambiguity and related problems, so multiple inheritance is not allowed in Java.
extends keyword is used for inheritance.
No. If Vehicle is super class and Car is the subclass then the following reference would be wrong – Car c = new Vehicle();
Yes. The below is an example :
Vehicle v = new Car();
Yes. We can create a object reference for an interface. The object should have provided the implementation for the object.
Runnable r = new Test();
Test class should have implemented the runnable interface and overridded the run method.
Constructors are used to initialise an object. Constructors are invoked when the new operator on the class are called.
Constructor name should be the same as class name.Constructors doesn’t return anything – not even void.
Yes. Like methods constructors can also throw exceptions.
Yes. Constructors can be overloaded.
No. If you don’t define a constructor, the compiler will provide a default constructor.
Default constructor is a no argument constructor which initialises the instance variables to their default values. This will be provided by the compiler at the time of compilation. Default constructor will be provided only when you don’t have any constructor defined.
“this” is used to refer the currently executing object and it’s state. “this” is also used for chaining constructors and methods.
“super” is used to refer to the parent object of the currently running object. “super” is also to invoke super class methods and classes.
When you instantiate a subclass, the object will begin with an invocation of the constructor in the base class and initialize downwards through constructors in each subclass till it reaches the final subclass constructor.
Note: This top down imagery for class inheritance, rather than a upward tree-like approach, is standard in OOP but is sometimes confusing to newcomers.
The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class. Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon. Overloading and overriding are two types of polymorphism.
In a class, if two methods have the same name and a different signature,it is known as overloading in Object oriented concepts.
Overloading is a powerful feature, but you should use it only as needed. Use it when you actually do need multiple methods with different parameters, but the methods do the same thing. That is, don't use overloading if the multiple methods perform different tasks. This approach will only confuse other developers who get a peek at your code.
Overriding means, to give a specific definition by the derived class for a method implemented in the base class.
Package is a collection of related classes and interfaces. package declaration should be first statement in a java class.
java.lang package is imported by default even without a package declaration.
The classes will packaged into a no name default package. In practice, we always put classes into a meaningful package.
When a * is used in a import statement, it indicates that the classes used in the current source can be available in the imported package. Using slightly increases the compilation time but has no impact on the execution time.
A class can't be declared as private. It will result in compile time error.
A class can't be declared as protected. only methods can be declared as protected.
A protected method can be accessed by the classes within the same package or by the subclasses of the class in any package.
Nobody can instantiate the class from outside that class.
default access means the class,method,construtor or the variable can be accessed only within the package.
Yes. default is a keyword but is associated with switch statement not with access specifiers.
If you dont specify any access, then it means the class is of default access.
No its not possible. It will result in compile time error.
A final variable's value can't be changed. final variables should be initialized before using them.
No. Local variables cannot be declared as final.
A method declared as final can't be overridden. A sub-class doesn't have the independence to provide different implementation to the method.
You should declared your class as final. A class declared as final can't be inherited by any other class.
When a class is independent and completely concrete in nature, then the class has to be marked as final.
java.lang.String,java.lang.Math are final classes.
The variable should be declared as static and final. So only one copy of the variable exists for all instances of the class and the value can't be changed also.
static final int PI = 3.14; is an example for constant.
No a class cannot be defined as static. Only a method,a variable or a block of code can be declared as static.
When a method needs to be accessed even before the creation of the object of the class then we should declare the method as static.
Print the statement inside a static block of code. Static blocks get executed when the class gets loaded into the memory and even before the creation of an object. Hence it will be executed before the main method.
static code blocks could be used for one time initialisation activities.
Constructors are used for object level initialisation whereas the static block are used for class level initialisation ie to initialise constants.
No. It will be executed only once for each class ie at the time of loading a class.
A static method should not refer to instance variables without creating an instance.It cannot use "this" or "super". A static method can acces only static variables or static methods.
No. It should be static only.
static variables are class level variables where all objects of the class refer to the same variable. If one object changes the value then the change gets reflected in all the objects.
Static varaibles are class level variables and they can't be declared inside a method. If declared, the class will not compile.
A Class which doesn't provide complete implementation is defined as an abstract class. Abstract classes enforce abstraction.
Variables can't be declared as abstract. only classes and methods can be declared as abstract.
Not possible. An abstract class without being inherited is of no use and a final class cannot be inherited. So if a abstract class is declared as final, it will result in compile time error.
An abstract method is a method whose implementation is deferred to a subclass.
Yes it's possible. This is basically to avoid instance creation of the class.
Then the subclass also becomes abstract. This will be enforced by the compiler.
Its the same as the earlier answer. The class has to be marked as abstract. This will be enforced by the compiler.
Not possible. Abstract classes are not concrete and hence can't be instantiated. If you try instantiating, you will get compilation error.
Yes. You can create a reference for an abstract class only when the object being has provided the implementation for the abstract class - it means that the object should be of a concrete subclass of the abstract class. This applies to interfaces also. Below is an example for interface referencing an object:
java.sql.Connection con = java.sql.DriverManager.getConnection("");
No. Only methods can be marked as native.
When a java method accesses native library written in someother programming language then the method has to be marked as native.
By using native methods, the java program loses platform independence - the accessed platform might be tightly coupled with a operating system hence java program also loses OS independence.
Only variables can be marked as transient. Variables marked as transient will not be persisted during object persistence.
Only variables can be marked as volatile. Volatile variables might be modified asynchronously.
Interfaces say what a class must do but does not say how a class must do it. Interfaces are 100% abstract.
No not possible. Class C should provide implementation for all the methods in the Interface I. Since Class C didn't provide implementation for m1 method, it has to be declared as abstract. Abstract classes can't be instantiated.
No not possible. Doing so will result in compilation error. public and abstract are the only applicable modifiers for method declaration in an interface.
Intefaces doesn't provide implementation hence a interface cannot implement another interface.
Yes an Interface can inherit another Interface, for that matter an Interface can extend more than one Interface.
Not possible. A Class can extend only one class but can implement any number of Interfaces.
Basically Java doesn't allow multiple inheritance, so a Class is restricted to extend only one Class. But an Interface is a pure abstraction model and doesn't have inheritance hierarchy like classes(do remember that the base class of all classes is Object). So an Interface is allowed to extend more than one Interface.
Not possible. Doing so so will result in compilation error.
An Interface which doesn't have any declaration inside but still enforces a mechanism.
No. Always all variables declared inside a interface are of public access.
Only public and abstract modifiers are allowed for methods in interfaces.
An object reference can be cast to an interface reference when the object implements the referenced interface.
Inner classes are classes which are defined inside another class.
Static Inner classes are called sometimes referred as nested classes because these classes can exist without any relationship with the containing class.
Inner class is just a concept and can be applied to any class, hence there is no common super class for inner classes.
1. Inner classes are not reusable hence defeats one of the fundamental feature of Java.
2. Highly confusing and difficult syntax which leads poor code maintainability.
The following are the different types of Inner classes:
- Regular Inner Class
- Method Local Inner Class
- Static Inner Class
- Anonymous Inner Class
A Regular inner class is declared inside the curly braces of another class outside any method or other code block. This is the simplest form of inner classes.
Yes. Since inner classes are treated as a member of the outer class they can access private members of the outer class.
Outer out=new Outer();
Outer.Inner in=out.new Inner();
A method-local inner class is defined within a method of the enclosing class.
The following are the restrictions for Method Inner Classes:
- Method Local Inner classes cannot acccess local variables but can access final variables.
- Only abstract and final modifiers can be applied to Method Local Inner classes
- Method Local Inner classes can be instantiated only within the method in which it is contained that too after the class definition.
Anonymous Inner Classes have no name, and their type must be either a subclass of the named type or an implementer of the named interface. The following are the different forms of inner classes:
- Anonymous subclass(i.e. extends a class)
- Anonymous implementer (i.e. implements an interface)
- Argument-Defined Anonymous Inner Classes
One. Normal classes and other inner classes can implement more than one interface whereas anonymous inner classes can either implement a single interface or extend a single class.
Static Inner Classes are inner classes which marked with a static modifier. These classes need not have any relationship with the outer class. These can be instantiated even without the existence of the outer class object.
Yes. It can be instantiated as follows by referencing the Outer class.
Outer.Inner in = new Outer.Inner();
- It cannot access non-static members of the outer class.
- It cannot use this reference to the outer class.
Two class files will be produced as follows:
Outer.class
Outer$Inner.class