Selection statements
A java Program can contain any no. Of classes but at most one class can be declared as public. "If there is a public class the name of the Program and name of the public class must be matched otherwise we will get compile time error".
If there is no public class then any name we gives for java source file.
Case 1:
- If there is no public class then we can use any name for java source file there are no restrictions.
Example:
A.java
B.java
C.java
Ashok.java
Case 2:
- If class B declared as public then the name of the Program should be B.java otherwise we will get compile time error saying "class B is public, should be declared in a file named B.java".
Case 3:
- If both B and C classes are declared as public and name of the file is B.java then we will get compile time error saying "class C is public, should be declared in a file named C.java".
- It is highly recommended to take only one class for source file and name of the Program (file) must be same as class name. This approach improves readability and understandability of the code.
Example:
class B {public static void main(String args[]){System.out.println("B class main method);}}class C {public static void main(String args[]){System.out.println("C class main method);}}class D {}class A {public static void main(String args[]){System.out.println("A class main method);}}
Output:
D:\Java>java A
A class main method is executed
D:\Java>java B
B class main method is executed
D:\Java>java C
C class main method is executed
D:\Java>java D Exception in thread "main" java.lang.NoSuchMethodError: main
D:\Java>java Ashok Exception in thread "main" java.lang.NoClassDefFoundError: Ashok
- We can compile a java Program but not java class in that Program for every class one dot class file will be created.
- We can run a java class but not java source file whenever we are trying to run a class the corresponding class main method will be executed.
- If the class won't contain main method then we will get runtime exception saying "NoSuchMethodError: main".
- If we are trying to execute a java class and if the corresponding .class file is not available then we will get runtime execution saying "NoClassDefFoundError: Ashok".
Import Statement
Example:
class Test{public static void main(String args[]){ArrayList l=new ArrayList();}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:3: cannot find symbol
symbol : class ArrayList
location: class Test
ArrayList l=new ArrayList();
- We can resolve this problem by using fully qualified name "java.util.ArrayList l=new java.util.ArrayList();". But problem with using fully qualified name every time is it increases length of the code and reduces readability.
- We can resolve this problem by using import statements. Example:import java.util.ArrayList;
Example:
import java.util.ArrayList;class Test{public static void main(String args[]){ArrayList l=new ArrayList();}}
Output:
D:\Java>javac Test.java
Hence whenever we are using import statement it is not require to use fully qualified names we can use short names directly. This approach decreases length of the code and improves readability.
Case 1: There are 2 types of import statements.
There are 2 types of import statements.
- Explicit class import
- Implicit class import.
1.Explicit class import:
Example: Import java.util.ArrayList
- This type of import is highly recommended to use because it improves readability of the code.
- Best suitable for Hi-Tech city where readability is important.
2. Implicit class import:
Example: import java.util.*;
- It is never recommended to use because it reduces readability of the code.
- Best suitable for Ameerpet where typing is important.
Case 2:
Which of the following import statements are meaningful ?
Case 3:
consider the following code.
class MyArrayList extends java.util.ArrayList {
}
- The code compiles fine even though we are not using import statements because we used fully qualified name.
- Whenever we are using fully qualified name it is not required to use import statement. Similarly whenever we are using import statements it is not require to use fully qualified name.
Case 4:
Example:
import java.util.*;import java.sql.*;class Test {public static void main(String args[]) {Date d=new Date();}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:7: reference to Date is ambiguous,
both class java.sql.Date in java.sql and class java.util.Date in java.util match
Date d=new Date();
Note:
- Even in the List case also we may get the same ambiguity problem because it is available in both util and awt packages.
Case 5:
While resolving class names compiler will always gives the importance in the following order.
- Explicit class import
- Classes present in current working directory.
- Implicit class import.
Example:
import java.util.Date; import java.sql.*; class Test {public static void main(String args[]){Date d=new Date();}}
The code compiles fine and in this case util package Date will be considered.
Case 6:
Whenever we are importing a package all classes and interfaces present in that package are by default available but not sub package classes.
Example:
To use pattern class in our Program directly which import statement is required ?
Case7:
In any java Program the following 2 packages are not require to import because these are available by default to every java Program.
- java.lang package
- default package(current working directory)
Case 8:
"Import statement is totally compile time concept" if more no of imports are there then more will be the compile time but there is "no change in execution time".
Difference between C language #include and java language import ?
#include
- It can be used in C & C++
- It is static inclusion wastage of memory Ex : <jsp:@ file="">
- At compile time only compiler copy the code from standard library and placed in current program.
import
- It can be used in Java
- It is dynamic inclusion No wastage of memory Ex : <jsp:include >
- At runtime JVM will execute the corresponding standard library and use it's result in current program.
- In the case of C language #include all the header files will be loaded at the time of include statement hence it follows static loading.
- But in java import statement no ".class" will be loaded at the time of import statements in the next lines of the code whenever we are using a particular class then only corresponding ".class" file will be loaded. Hence it follows "dynamic loading" or "load-on -demand" or "load-on-fly".
1.5 Version new Features
- For-Each
- Var-arg
- Queue
- Generics
- Auto boxing and Auto unboxing
- Co-varient return types
- Annotations
- Enum
- Static import
- String builder
Static import:
- This concept introduced in 1.5 versions. According to sun static import improves readability of the code but according to worldwide Programming exports (like us) static imports creates confusion and reduces readability of the code. Hence if there is no specific requirement never recommended to use a static import.
- Usually we can access static members by using class name but whenever we are using static import it is not require to use class name we can access directly.
Without static import:
Example:
class Test {
public static void main(String args[]){
System.out.println(Math.sqrt(4));
System.out.println(Math.max(10,20));
System.out.println(Math.random());
}
}
Output:
D:\Java>javac Test.java
D:\Java>java Test
2.0
20
0.841306154315576
With static import:
Example:
import static java.lang.Math.sqrt;
import static java.lang.Math.*;
class Test {
public static void main(String args[]){
System.out.println(sqrt(4));
System.out.println(max(10,20));
System.out.println(random());
}
}
Output:
D:\Java>javac Test.java
D:\Java>java Test
2.0
20
0.4302853847363891
Explain about System.out.println statement ?
Example 1 Example 2:
Example 3:
import static java.lang.System.out;class Test {public static void main(String args[]){out.println("hello");out.println("hi");}}
Output:
D:\Java>javac Test.java
D:\Java>java Test hello
hi
Example 4:
import static java.lang.Integer.*;import static java.lang.Byte.*;class Test {public static void main(String args[]){System.out.println(MAX_VALUE);}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:6: reference to MAX_VALUE is ambiguous, both variable MAX_VALUE in java.lang.Integer and variable MAX_VALUE in java.lang.Byte match System.out.println(MAX_VALUE);
Note:
- Two packages contain a class or interface with the same is very rare hence ambiguity problem is very rare in normal import.
- But 2 classes or interfaces can contain a method or variable with the same name is very common hence ambiguity problem is also very common in static import.
While resolving static members compiler will give the precedence in the following order.
- Current class static members
- Explicit static import
- Implict static import
Example:
- If we comet line one then we will get Integer class MAX_VALUE 2147483647.
- If we comet lines one and two then Byte class MAX_VALUE will be considered 127.
Which of the following import statements are valid ?
Diagram:
Usage of static import reduces readability and creates confusion hence if there is no specific requirement never recommended to use static import.
What is the difference between general import and static import ?
- We can use normal imports to import classes and interfaces of a package. whenever we are using normal import we can access class and interfaces directly by their short name it is not require to use fully qualified names.
- We can use static import to import static members of a particular class. whenever we are using static import it is not require to use class name we can access static members directly..
Package Statement
It is an encapsulation mechanism to group related classes and interfaces into a single module.
The main objectives of packages are:
- To resolve name confects.
- To improve modularity of the application.
- To provide security.
- There is one universally accepted naming conversion for packages that is to use internet domain name in reverse.
Example:
How to compile package Program:
Example:
package com.jobs.itjobs;class HydJobs {public static void main(String args[]){System.out.println("package demo");}}
Javac HydJobs.java generated class file will be placed in current working directory.
Diagram:
- Javac -d . HydJobs.java
- -d means destination to place generated class files "." means current working directory.
- Generated class file will be placed into corresponding package structure.
Diagram:
- If the specified package structure is not already available then this command itself will create the required package structure.
- As the destination we can use any valid directory.
- If the specified destination is not available then we will get compile time error.
Example:
D:\Java>javac -d c: HydJobs.java
Diagram:
If the specified destination is not available then we will get compile time error.
Example:
D:\Java>javac -d z: HydJobs.java
If Z: is not available then we will get compile time error.
How to execute package Program:
D:\Java>java com.jobs.itjobs.HydJobs
At the time of execution compulsory we should provide fully qualified name.
Conclusion 1:
In any java Program there should be at most one package statement that is if we are taking more than one package statement we will get compile time error.
Example:
package pack1;
package pack2;
class A {
}
Output:
Compile time error.
D:\Java>javac A.java
A.java:2: class, interface, or enum expected package pack2;
Conclusion 2:
In any java Program the 1st non comment statement should be package statement [if it is available] otherwise we will get compile time error.
Example:
import java.util.*;
package pack1;
class A {
}
Output:
Compile time error.
D:\Java>javac A.java
A.java:2: class, interface, or enum expected package pack1;
All the following are valid java Programs.
Note: An empty source file is a valid java Program.
Class Modifiers
Whenever we are writing our own classes compulsory we have to provide some information about our class to the jvm.
Like
- Whether this class can be accessible from anywhere or not.
- Whether child class creation is possible or not.
- Whether object creation is possible or not etc.
We can specify this information by using the corresponding modifiers.
The only applicable modifiers for Top Level classes are:
- Public
- Default
- Final
- Abstract
- Strictfp
If we are using any other modifier we will get compile time error.
Example:
private class Test {public static void main(String args[]){int i=0;for(int j=0;j<3;j++) {i=i+j;}System.out.println(i);}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:1: modifier private not allowed here private class Test
But For the inner classes the following modifiers are allowed.
Diagram:
What is the difference between access specifier and access modifier ?
- In old languages 'C' (or) 'C++' public, private, protected, default are considered as access specifiers and all the remaining are considered as access modifiers.
- But in java there is no such type of division all are considered as access modifiers.
Public Classes:
If a class declared as public then we can access that class from anywhere. With in the package or outside the package.
Example:
Program1:
package pack1;public class Test {public void methodOne(){System.out.println("test class methodone is executed");}}
Compile the above Program:
D:\Java>javac -d .
Test.java
Program2:
package pack2;import pack1.Test;class Test1 {public static void main(String arg []) {Test t=new Test();t.methodOne();}}
Output:
D:\Java>javac -d . Test1.java
D:\Java>java pack2.Test1
Test class methodone is executed
If class Test is not public then while compiling Test1 class we will get compile time error saying pack1.Test is not public in pack1; cannot be accessed from outside package.
Default Classes:
If a class declared as the default then we can access that class only within the current package hence default access is also known as "package level access".
Example:
Program 1:
package pack1;class Test {public void methodOne(){System.out.println("test class methodone is executed");}}
Program 2:
package pack1;import pack1.Test;class Test1 {public static void main(String args[]){Test t=new Test(); t.methodOne();}}
Output:
D:\Java>javac -d .
D:\Java>javac -d .
D:\Java>java pack1.Test1
Test class methodone is executed
Final Modifier:
Final is the modifier applicable for classes, methods and variables.
Final Methods:
- Whatever the methods parent has by default available to the child.
- If the child is not allowed to override any method, that method we have to declare with final in parent class. That is final methods cannot overridden.
Example:
Program 1::
class Parent {public void property() {System.out.println("cash+gold+land");}public final void marriage() {System.out.println("subbalakshmi");}}
Program 2:
class child extends Parent {public void marriage() {System.out.println("Thamanna");}}
Output:
Compile time error.
D:\Java>javac Parent.java
D:\Java>javac child.java
child.java:3: marriage() in child cannot override marriage() in Parent; overridden method is finalpublic void marriage()
Final Class
If a class declared as the final then we cann't creates the child class that is inheritance concept is not applicable for final classes.
Example:
Program 1:
final class Parent{
}
Program 2:
class child extends Parent {
}
Output:
Compile time error.
D:\Java>javac Parent.java
D:\Java>javac child.java
child.java:1: cannot inherit from final Parent class child extends Parent
Note: Every method present inside a final class is always final by default whether we are declaring or not. But every variable present inside a final class need not be final.
Example:
final class parent {
static int x=10;
static { x=999;
}
}
Abstract Modifier:
Abstract is the modifier applicable only for methods and classes but not for variables.
Abstract Methods:
- Even though we don't have implementation still we can declare a method with abstract modifier.
- That is abstract methods have only declaration but not implementation.
- Hence abstract method declaration should compulsory ends with semicolon.
Example:
Child classes are responsible to provide implementation for parent class abstract methods.
Example:
Program:
- The main advantage of abstract methods is , by declaring abstract method in parent class we can provide guide lines to the child class such that which methods they should compulsory implement.
- Abstract method never talks about implementation whereas if any modifier talks about implementation then the modifier will be enemy to abstract and that is always illegal combination for methods.
The following are the various illegal combinations for methods.
Diagram:
All the 6 combinations are illegal.
Abstract class
For any java class if we are not allow to create an object such type of class we have to declare with abstract modifier that is for abstract class instantiation is not possible.
Example:
abstract class Test {public static void main(String args[]){Test t=new Test();}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:4: Test is abstract; cannot be instantiated Test t=new Test();
What is the difference between abstract class and abstract method ?
- If a class contain at least on abstract method then compulsory the corresponding class should be declare with abstract modifier. Because implementation is not complete and hence we can't create object of that class.
- Even though class doesn't contain any abstract methods still we can declare the class as abstract that is an abstract class can contain zero no of abstract methods also.
Example1: HttpServlet class is abstract but it doesn't contain any abstract method.
Example2: Every adapter class is abstract but it doesn't contain any abstract method.
Example1::
class Parent {public void methodOne();}
Output:
Compile time error.
D:\Java>javac Parent.java
Parent.java:3: missing method body, or declare abstract public void methodOne();
Example2::
class Parent {public abstract void methodOne(){}}
Output:
Compile time error.
Parent.java:3: abstract methods cannot have a body public abstract void methodOne(){}
Example3:
class Parent {public abstract void methodOne();}
Output:
Compile time error. D:\Java>javac Parent.java
Parent.java:1: Parent is not abstract and does not override abstract method methodOne() in Parent
class Parent
If a class extends any abstract class then compulsory we should provide implementation for every abstract method of the parent class otherwise we have to declare child class as abstract.
Example:
abstract class Parent {public abstract void methodOne();public abstract void methodTwo();}class child extends Parent {public void methodOne(){}}
Output:
Compile time error.
D:\Java>javac Parent.java
Parent.java:6: child is not abstract and does not
override abstract method methodTwo() in Parent class child extends Parent
If we declare class child as abstract then the code compiles fine but child of child is responsible to provide implementation for methodTwo().
What is the difference between final and abstract ?
- For abstract methods compulsory we should override in the child class to provide implementation. Whereas for final methods we can't override hence abstract final combination is illegal for methods.
- For abstract classes we should compulsory create child class to provide implementation whereas for final class we can't create child class. Hence final abstract combination is illegal for classes.
- Final class cannot contain abstract methods whereas abstract class can contain final method.
Example:
Note:
Usage of abstract methods, abstract classes and interfaces is always good Programming practice.
Strictfp
- strictfp is the modifier applicable for methods and classes but not for variables.
- Strictfp modifier introduced in 1.2 versions.
- Usually the result of floating point of arithmetic is varing from platform to platform , to overcome this problem we should use strictfp modifier.
- If a method declare as the Strictfp then all the floating point calculations in that method has to follow IEEE754 standard, So that we will get platform independent results.
Example:
If a class declares as the Strictfp then every concrete method(which has body) of that class has to follow IEEE754 standard for floating point arithmetic, so we will get platform independent results.
What is the difference between abstract and strictfp ?
- Strictfp method talks about implementation where as abstract method never talks about implementation hence abstract, strictfp combination is illegal for methods.
- But we can declare a class with abstract and strictfp modifier simultaneously. That is abstract strictfp combination is legal for classes but illegal for methods.
Example:
Member Modifiers
Public members:
- If a member declared as the public then we can access that member from anywhere "but the corresponding class must be visible" hence before checking member visibility we have to check class visibility.
Example:
Program 1:
package pack1;class A {public void methodOne(){System.out.println("a class method");
- }
}D:\Java>javac -d . A.java
Program 2:
package pack2;import pack1.A;class B {public static void main(String args[]){A a=new A();a.methodOne();}}
Output:
Compile time error.
D:\Java>javac -d . B.java
B.java:2: pack1.A is not public in pack1;
cannot be accessed from outside package import pack1.A;
In the above Program even though methodOne() method is public we can't access from class B because the corresponding class A is not public that is both classes and methods are public then only we can access.
Default member
- If a member declared as the default then we can access that member only within the current package hence default member is also known as package level access.
Example 1:
Program 1::
package pack1;class A {void methodOne(){System.out.println("methodOne is executed");}}
Program 2:
package pack1;import pack1.A;class B {public static void main(String args[]) {A a=new A();a.methodOne();}}
Output:
D:\Java>javac -d . A.java
D:\Java>javac -d . B.java
D:\Java>java pack1.B methodOne is executed
Example 2:
Program 1:
package pack1;class A {void methodOne() {System.out.println("methodOne is executed");}}
Program 2:
package pack2;import pack1.A;class B {public static void main(String args[]){A a=new A();a.methodOne();}}
Output:
Compile time error.
D:\Java>javac -d . A.java
D:\Java>javac -d . B.java
B.java:2: pack1.A is not public in pack1; cannot be accessed from outside package import pack1.A;
Private members:
- If a member declared as the private then we can access that member only with in the current class.
- Private methods are not visible in child classes where as abstract methods should be visible in child classes to provide implementation hence private, abstract combination is illegal for methods.
Protected members:
- If a member declared as the protected then we can access that member within the current package anywhere but outside package only in child classes. Protected=default+kids.
- We can access protected members within the current package anywhere either by child reference or by parent reference But from outside package we can access protected members only in child classes and should be by child reference only that is we can't use parent reference to call protected members from outside package.
Example:
Program 1:
package pack1;public class A {protected void methodOne() {System.out.println("methodOne is executed");}}
Program 2:
package pack1;class B extends A {public static void main(String args[]){A a=new A();a.methodOne();B b=new B();b.methodOne();A a1=new B();a1.methodOne();}}
Output:
D:\Java>javac -d . A.java
D:\Java>javac -d . B.java
D:\Java>java pack1.B
methodOne is executed
methodOne is executed
methodOne is executed
Example 2:
Final Variables:
Final instance variables
If the value of a variable is varied from object to object such type of variables are called instance variables.
For every object a separate copy of instance variables will be created.
Diagaram :
For the instance variables it is not required to perform initialization explicitly jvm will
always provide default values.
Example:
class Test {int i;public static void main(String args[]){Test t=new Test(); System.out.println(t.i);}}
Output:
D:\Java>javac Test.java
D:\Java>java Test
0
If the instance variable declared as the final compulsory we should perform initialization explicitly and JVM won't provide any default values. whether we are using or not otherwise we will get compile time error.
Example:
Program 1:
class Test {int i;}
Output:
D:\Java>javac Test.java D:\Java>
Program 2:
class Test {final int i;}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:1: variable i might not have been initialized class Test
Rule:
For the final instance variables we should perform initialization before constructor completion. That is the following are various possible places for this.
1) At the time of declaration:
Example:
class Test {
final int i=10;
}
Output:
D:\Java>javac Test.java
D:\Java>
2) Inside instance block:
Example:
class Test {
final int i;
{ i=10;}
}
Output:
D:\Java>javac Test.java
D:\Java>
3) Inside constructor:
Example:
class Test {
final int i;
Test() {
i=10;
}
}
Output:
D:\Java>javac Test.java
D:\Java>
If we are performing initialization anywhere else we will get compile time error.
Example:
class Test {final int i;public void methodOne(){i=10;}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: cannot assign a value to final variable i i=10;
Final static variables:
- If the value of a variable is not varied from object to object such type of variables is not recommended to declare as the instance variables. We have to declare those variables at class level by using static modifier.
- In the case of instance variables for every object a seperate copy will be created but in the case of static variables a single copy will be created at class level and shared by every object of that class.
- For the static variables it is not required to perform initialization explicitly jvm will always provide default values.
Example:
class Test {static int i;public static void main(String args[]) {System.out.println("value of i is :"+i);}}
Output:
D:\Java>javac Test.java
D:\Java>java Test
Value of i is: 0
If the static variable declare as final then compulsory we should perform initialization explicitly whether we are using or not otherwise we will get compile time error.(The JVM won't provide any default values)
Example:
Rule:
For the final static variables we should perform initialization before class loading completion otherwise we will get compile time error. That is the following are possible places.
1) At the time of declaration:
Example:
class Test {
final static int i=10;
}
Output:
D:\Java>javac Test.java
D:\Java>
2) Inside static block:
Example:
class Test {
final static int i;
static {
i=10;
}
}
Output:
Compile successfully.
If we are performing initialization anywhere else we will get compile time error.
Example:
class Test {final static int i;public static void main(String args[]){i=10;}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: cannot assign a value to final variable i i=10;
Final local variables:
- To meet temporary requirement of the Programmer sometime we can declare the variable inside a method or block or constructor such type of variables are called local variables.
- For the local variables jvm won't provide any default value compulsory we should perform initialization explicitly before using that variable.
Example:
class Test {public static void main(String args[]) {int i;System.out.println("hello");}}
Output:
D:\Java>javac Test.java
D:\Java>java Test
Hello
Example:
class Test {public static void main(String args[]){int i;System.out.println(i);}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: variable i might not have been initialized System.out.println(i);
Even though local variable declared as the final before using only we should perform initialization.
Example:
class Test {public static void main(String args[]){final int i; System.out.println("hello");}}
Output:
D:\Java>javac Test.java
D:\Java>java Test
hello
Note: The only applicable modifier for local variables is final if we are using any other modifier we will get compile time error.
Example:
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: illegal start of expression private int x=10;
Formal parameters
- The formal parameters of a method are simply acts as local variables of that method hence it is possible to declare formal parameters as final.
- If we declare formal parameters as final then we can't change its value within the method.
Example:
- For instance and static variables JVM will provide default values but if instance and static declared as final JVM won't provide default value compulsory we should perform initialization whether we are using or not .
- For the local variables JVM won't provide any default values we have to perform explicitly before using that variables , this rule is same whether local variable final or not.
Static Modifier
- Static is the modifier applicable for methods, variables and blocks.
- We can't declare a class with static but inner classes can be declaring as the static.
- In the case of instance variables for every object a separate copy will be created but in the case of static variables a single copy will be created at class level and shared by all objects of that class..
Example:
Output:
D:\Java>javac Test.java
D:\Java>java Test
888.....20
Instance variables can be accessed only from the instance area directly and we can't access them from the static area directly.
But static variables can be accessed from both instance and static areas directly.
1) Int x=10;
2) Static int x=10;
3) Public void methodOne(){ System.out.println(x);}
4) Public static void methodOne(){ System.out.println(x);}
Which are the following declarations are allow within the same class simultaneously ?
a) 1 and 3
Example:
class Test {int x=10;public void methodOne(){System.out.println(x);}}
Output:
Compile successfully.
b) 1 and 4
Example:
class Test {int x=10;public static void methodOne() {System.out.println(x);}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: non-static variable x cannot be referenced from a static context System.out.println(x);
c) 2 and 3
Example:
class Test {static int x=10;public void methodOne(){System.out.println(x);}}
Output:
Compile successfully.
d) 2 and 4
Example:
class Test {static int x=10;public static void methodOne(){System.out.println(x);}}
Output:
Compile successfully.
e) 1 and 2
Example:
class Test {int x=10;static int x=10;}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:4: x is already defined in Test static int x=10;
f) 3 and 4
Example:
class Test {public void methodOne(){System.out.println(x);public static void methodOne(){System.out.println(x);}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: methodOne() is already defined in Test public static void methodOne(){ For static methods implementation should be available but for abstract methods implementation is not available hence static abstract combination is illegal for methods.
case 1:
- Overloading concept is applicable for static method including main method also.But JVM will always call String[] args main method .
- The other overloaded method we have to call explicitly then it will be executed just like a normal method call .
Example:
Output :
String() method is called
case 2:
- Inheritance concept is applicable for static methods including main() method hence while executing child class, if the child doesn't contain main() method then the parent class main method will be executed.
Example:
class Parent{public static void main(String args[]){System.out.println("parent main() method called");}}class child extends Parent{}
Output:
Example:
It seems to be overriding concept is applicable for static methods but it is not overriding it is method hiding.
Native modifier
- Native is a modifier applicable only for methods but not for variables and classes.
- The methods which are implemented in non java are called native methods or foreign methods.
- The main objectives of native keyword are:
- To improve performance of the system.
- To use already existing legacy non-java code.
- To achieve machine level communication(memory level - address)
- Pseudo code to use native keyword in java.
To use native keyword:
Pseudo code:
- For native methods implementation is already available and we are not responsible to provide implementation hence native method declaration should compulsory ends with semicolon.
- Public native void methodOne()----invalid
- Public native void methodOne();---valid
- For native methods implementation is already available where as for abstract methods implementation should not be available child class is responsible to provide that, hence abstract native combination is illegal for methods.
- We can't declare a native method as strictfp because there is no guaranty whether the old language supports IEEE754 standard or not. That is native strictfp combination is illegal for methods.
- For native methods inheritance, overriding and overloading concepts are applicable.
- The main advantage of native keyword is performence will be improves.
- The main disadvantage of native keyword is usage of native keyword in java breaks platform independent nature of java language.
Synchronized
- Synchronized is the modifier applicable for methods and blocks but not for variables and classes.
- If a method or block declared with synchronized keyword then at a time only one thread is allow to execute that method or block on the given object.
- The main advantage of synchronized keyword is we can resolve data inconsistency problems.
- But the main disadvantage is it increases waiting time of the threads and effects performance of the system. Hence if there is no specific requirement never recommended to use synchronized keyword.
- For syncronized methods compulsory implementation should be available , but for abstract methods implementation won't be available , Hence abstract - syncronized combination is illegal for methods.
Transient modifier
- Transient is the modifier applicable only for variables but not for methods and classes.
- At the time of serialization if we don't want to serialize the value of a particular variable to meet the security constraints then we should declare that variable with transient modifier.
- At the time of serialization jvm ignores the original value of the transient variable and save default value that is transient means "not to serialize".
- Static variables are not part of object state hence serialization concept is not applicable for static variables duo to this declaring a static variable as transient there is no use.
- Final variables will be participated into serialization directly by their values due to this declaring a final variable as transient there is no impact.
Volatile modifier
- Volatile is the modifier applicable only for variables but not for classes and methods.
- If the value of variable keeps on changing such type of variables we have to declare with volatile modifier.
- If a variable declared as volatile then for every thread a separate local copy will be created by the jvm, all intermediate modifications performed by the thread will takes place in the local copy instead of master copy.
- Once the value got finalized before terminating the thread that final value will be updated in master copy.
- The main advantage of volatile modifier is we can resolve data inconsistency problems, but creating and maintaining a separate copy for every thread increases complexity of the Programming and effects performance of the system. Hence if there is no specific requirement never recommended to use volatile modifier and it's almost outdated.
- Volatile means the value keep on changing where as final means the value never changes hence final volatile combination is illegal for variables.
Java Modifiers Important Questions
- 1) For the TopLevelClasseswhichModifiersareAllowed?
- 2) Is it Possible to Declare a Class as static, private, and protected?
- 3) WhatareExtraModifiersApplicableforInnerClasseswhencomparedwithOuter Classes?
- 4) WhatisafinalClass?
- 5) ExplaintheDifferencesbetweenfinal,finallyandfinalize?
- 6) IsEveryMethodPresentinfinalClassisfinal?
- 7) IsEveryVariablePresentInsideafinalClassisfinal?
- 8) WhatisabstractClass?
- 9) WhatisabstractMethod?
- 10)If a Class contain at least One abstract Method is it required to declared that Class Compulsory abstract?
- 11)If a Class doesn’t contain any abstract Methods is it Possible to Declare that Class as abstract?
- 12)Whenever we are extending abstract Class is it Compulsory required to Provide Implementation for Every abstract Method of that Class?
- 13)Is final Class can contain abstract Method?
- 14)Is abstract Class can contain final Methods?
- 15)Can You give Example for abstract Class which doesn’t contain any abstract Method?
- 16)Which of the following Modifiers Combinations are Legal for Methods? public – static
- static – abstract
- abstract - final
- final - synchronized
- synchronized - native native – abstract
- 17) Which of the following Modifiers Combinations are Legal for Classes? public - final
- final - abstract
- abstract - strictfp strictfp – public
- 18) What is the Difference between abstract Class and Interface? 19)What is strictfp Modifier?
- 20) Is it Possible to Declare a Variable with strictfp?
- 21) abstract - strictfp Combination, is Legal for Classes OR Methods? 22)Is it Possible to Override a native Method?
- 23) What is the Difference between Instance and Static Variable?
- 24) What is the Difference between General Static Variable and final Static Variable?
- 25) Which Modifiers are Applicable for Local Variable?
- 26) When the Static Variables will be Created?
- 27) What are Various Memory Locations of Instance Variables, Local Variables and Static Variables?
- 28) Is it Possible to Overload a main()?
- 29) Is it Possible to Override Static Methods?
- 30) What is native Key Word and where it is Applicable?
- 31) What is the Main Advantage of the native Key Word?
- 32) If we are using native Modifier how we can Maintain Platform Independent Nature?
- 33)How we can Declare a native Method?
- 34)Is abstract Method can contain Body?
- 35)What is synchronized Key Word where we can Apply?
- 36)What are Advantages and Disadvantages of synchronized Key Word?
- 37)Which Modifiers are the Most Dangerous in Java?
- 38)What is Serialization and Explain how its Process?
- 39)What is Deserialization?
- 40)By using which Classes we can Achieve Serialization and Deserialization?
- 41)What is Serializable interface and Explain its Methods?
- 42)What is a Marker Interface and give an Example?
- 43)Without having any Method in Serializable Interface, how we can get Serializable Ability for Our Object?
- 44)What is the Purpose of transient Key Word and Explain its Advantages? 45)Is it Possible to Serialize Every Java Object?
- 46)Is it Possible to Declare a Method, a Class with transient?
- 47)If we Declare Static Variable with transient is there any Impact? 48)What is the Impact of declaring final Variable a transient?
- 49)What is volatile Variable?
- 50)Is it Possible to Declare a Class OR a Method with volatile? 51)What is the Advantage and Disadvantage of volatile Modifier?
Note :
- The modifiers which are applicable for inner classes but not for outer classes are private, protected, static.
- The modifiers which are applicable only for methods native.
- The modifiers which are applicable only for variables transient and volatile.
- The modifiers which are applicable for constructor public, private, protected,default.
- The only applicable modifier for local variables is final.
- The modifiers which are applicable for classes but not for enums are final ,
- abstract.
- The modifiers which are applicable for classes but not for interface are final.
Interfaces
Def1:
- Any service requirement specification (srs) is called an interface. Example1: Sun people responsible to define JDBC API and database vendor will provide implementation for that.
Diagram:
Example:
- Sun people define Servlet API to develop web applications web server vendor is responsible to provide implementation.
Diagram:
Def2:
- From the client point of view an interface define the set of services what is expecting. From the service provider point of view an interface defines the set of services what is offering. Hence an interface is considered as a contract between client and service provider.
Example:
- ATM GUI screen describes the set of services what bank people offering, at the same time the same GUI screen the set of services what customer is expecting hence this GUI screen acts as a contract between bank and customer.
Def3:
- Inside interface every method is always abstract whether we are declaring or not hence interface is considered as 100% pure abstract class.
Summery def:
- Any service requirement specification (SRS) or any contract between client and service provider or 100% pure abstract classes is considered as an interface.
Declaration and implementation of an interface:
Note1:
- Whenever we are implementing an interface compulsory for every method of that interface we should provide implementation otherwise we have to declare class as abstract in that case child class is responsible to provide implementation for remaining methods.
Note2:
- Whenever we are implementing an interface method compulsory it should be declared as public otherwise we will get compile time error.
Example:
interface Interf {
void methodOne();
void methodTwo();
}
class SubServiceProvider extends ServiceProvider {
}
Output:
Compile time error.
D:\Java>javac SubServiceProvider.java SubServiceProvider.java:1:
SubServiceProvider is not abstract and does not override bstract method methodTwo() in Interf class SubServiceProvider extends ServiceProvider
Extends vs implements:
A class can extends only one class at a time.
Example:
class One{public void methodOne(){ }}class Two extends One{ }A class can implements any no. Of interfaces at a time.
Example:
interface One{public void methodOne();}interface Two{public void methodTwo();}class Three implements One,Two{public void methodOne(){}public void methodTwo(){}}
A class can extend a class and can implement any no. Of interfaces simultaneously.
interface One{void methodOne();}}class Two {public void methodTwo(){}}class Three extends Two implements One{public void methodOne(){}}An interface can extend any no. Of interfaces at a time.Example:interface One{void methodOne();}interface Two{void methodTwo();}interface Three extends One,Two {}
Which of the following is true?
- 1. A class can extend any no.Of classes at a time.
- 2. An interface can extend only one interface at a time.
- 3. A class can implement only one interface at a time.
- 4. A class can extend a class and can implement an interface but not both
- simultaneously.
- 5. An interface can implement any no.Of interfaces at a time.
- 6. None of the above Ans: 6
Consider the expression X extends Y for which of the possibility of X and Y this expression is true?
- 1. Both x and y should be classes.
- 2. Both x and y should be interfaces.
- 3. Both x and y can be classes or can be interfaces.
- 4. No restriction. Ans: 3
X extends Y, Z ?
X, Y, Z should be interfaces.
X extends Y implements Z ?
X, Y should be classes.
Z should be interface.
X implements Y, Z ?
X should be class.
Y, Z should be interfaces.
X implements Y extend Z ?
Example:
interface One{
}
class Two {
}
class Three implements One extends Two{ }
Output:
Compile time error.
D:\Java>javac Three.java
Three.java:5: '{' expected
class Three implements One extends Two
Interface methods:
- Every method present inside interface is always public and abstract whether we are declaring or not. Hence inside interface the following method declarations are equal.
- void methodOne();
- public Void methodOne();
- abstract Void methodOne(); Equal public abstract Void methodOne();
- public: To make this method available for every implementation class. abstract: Implementation class is responsible to provide implementation .
- As every interface method is always public and abstract we can't use the following modifiers for interface methods.Private, protected, final, static, synchronized, native, strictfp.
Inside interface which method declarations are valid?
- 1. public void methodOne(){}
- 2. private void methodOne();
- 3. public final void methodOne();
- 4. public static void methodOne();
- 5. public abstract void methodOne();
Ans: 5
Interface variables:
- An interface can contain variables
- The main purpose of interface variables is to define requirement level constants.
- Every interface variable is always public static and final whether we are declaring or not.
Example:
interface interf {
int x=10;
}
public:
- To make it available for every implementation class.
static:
- Without existing object also we have to access this variable. final: Implementation class can access this value but cannot modify.
Hence inside interface the following declarations are equal.
- int x=10;
- public int x=10;
- static int x=10;
- final int x=10;
- public static int x=10; public final int x=10; static final int x=10; public static final int x=10;
- Equal
As every interface variable by default public static final we can't declare with the following modifiers
- Private
- Protected
- Transient
- Volatile
For the interface variables compulsory we should perform initialization at the time of declaration only otherwise we will get compile time error.
Example:
interface Interf {
int x;
}
Output:
Compile time error. D:\Java>javac Interf.java Interf.java:3: = expected int x;
Which of the following declarations are valid inside interface ?
- 1. int x;
- 2. private int x=10;
- 3. public volatile int x=10;
- 4. public transient int x=10;
- 5. public static final int x=10;
Ans: 5
nterface variables can be access from implementation class but cannot be modified.
Example:
interface Interf {
int x=10;
}
Example 1:
Example 2:
class Test implements Interf {
public static void main(String args[]){
int x=20;
//here we declaring the variable x. System.out.println(x);
}
}
Output:
D:\Java>javac Test.java
D:\Java>java Test
20\
Interface naming conflicts
Method naming conflicts:
Case 1:
- If two interfaces contain a method with same signature and same return type in the implementation class only one method implementation is enough.
Example 1:
interface Left {
public void methodOne();
}
Example 2:
interface Right {
public void methodOne();
}
Example 3:
class Test implements Left,Right {
public void methodOne() {
}
}
Output:
D:\Java>javac Left.java
D:\Java>javac Right.java
D:\Java>javac Test.java
Case 2:
- if two interfaces contain a method with same name but different arguments in the implementation class we have to provide implementation for both methods and these methods acts as a overloaded methods
Example 1:
interface Left {
public void methodOne();
}
Example 2:
interface Right {
public void methodOne(int i);
}
Example 3:
class Test implements Left,Right {
public void methodOne() {
}
public void methodOne(int i) {
}
}
Output:
D:\Java>javac Left.java
D:\Java>javac Right.java
D:\Java>javac Test.java
Case 3:
- If two interfaces contain a method with same signature but different return types then it is not possible to implement both interfaces simultaneously.
Example 1:
interface Left {
public void methodOne();
}
Example 2:
interface Right {
public int methodOne(int i);
}
We can't write any java class that implements both interfaces simultaneously.
Is a java class can implement any no. Of interfaces simultaneously ?
Yes, except if two interfaces contains a method with same signature but different return types.
Variable naming conflicts
- Two interfaces can contain a variable with the same name and there may be a chance variable naming conflicts but we can resolve variable naming conflicts by using interface names.
Example 1:
interface Left {
int x=888;
}
Example 2:
interface Right {
int x=999;
}
Example 3:
class Test implements Left,Right {
public static void main(String args[]){
//System.out.println(x);
System.out.println(Left.x);
System.out.println(Right.x);
}
}
Output:
D:\Java>javac Left.java
D:\Java>javac Right.java
D:\Java>javac Test.java
D:\Java>java Test
888
999
Marker interface
- If an interface doesn't contain any methods and by implementing that interface if our objects will get some ability such type of interfaces are called Marker interface (or) Tag interface (or) Ability interface.
Example:
Serializable
Cloneable
RandomAccess These are marked for some ability
SingleThreadModel
.
.
.
.
Example 1:
- By implementing Serilaizable interface we can send that object across the network and we can save state of an object into a file.
Example 2:
- By implementing SingleThreadModel interface Servlet can process only one client request at a time so that we can get "Thread Safety".
Example 3:
- By implementing Cloneable interface our object is in a position to provide exactly duplicate cloned object.
- Without having any methods in marker interface how objects will get ability ? Internally JVM is responsible to provide required ability.
- Why JVM is providing the required ability in marker interfaces ? To reduce complexity of the programming.
- Is it possible to create our own marker interface ? Yes, but customization of JVM must be required. Ex : Sleepable , Jumpable , ....
What is the Difference between interface and abstract class ?
interface
- If we don't' know anything about implementation just we have requirement specification then we should go for interface.
- Every method present inside interface is always public and abstract whether we are declaring or not.
- We can't declare interface methods with the modifiers private, protected, final, static, synchronized, native, strictfp.
- Every interface variable is always public static final whether we are declaring or not.
- Every interface variable is always public static final we can't declare with the following modifiers.
- Private, protected, transient, volatile.
- For the interface variables compulsory we should perform initialization at the time of declaration otherwise we will get compile time error.
- Inside interface we can't take static and instance blocks.
- Inside interface we can't take constructor.
Abstract class
- If we are talking about implementation but not completely (partial implementation) then we should go for abstract class.
- Every method present inside abstract class need not be public and abstract
- There are no restrictions on abstract class method modifiers.
- Every abstract class variable need not be public static final.
- There are no restrictions on abstract class variable modifiers.
- It is not require to perform initialization for abstract class variables at the time of declaration.
- Inside abstract class we can take both static and instance blocks
- Inside abstract class we can take constructor.
We can't create object for abstract class but abstract class can contain constructor what is the need ?
- abstract class constructor will be executed when ever we are creating child class object to perform initialization of child object.
Example:
class Parent{
Parent(){
System.out.println(this.hashCode());
}
}
class child extends Parent{
child(){
System.out.println(this.hashCode());
}
}
class Test{
public static void main(String args[]){
child c=new child();
System.out.println(c.hashCode());
}
}
Note :
- We can't create object for abstract class either directly or indirectly.
- Every method present inside interface is abstract but in abstract class also we can take only abstract methods then what is the need of interface concept ?
- We can replace interface concept with abstract class. But it is not a good programming practice. We are misusing the roll of abstract class. It may create performence problems also.(this is just like recruiting IAS officer for sweeping purpose)
If every thing is abstract then it is recommended to go for interafce.
Why abstract class can contain constructor where as interface doesn't contain constructor ?
- The main purpose of constructor is to perform initialization of an object i.e., provide values for the instance variables, Inside interface every variable is always static and there is no chance of existing instance variables. Hence constructor is not required for interface.
- But abstract class can contains instance variable which are required for the child object to perform initialization for those instance variables constructor is required in the case of abstract class.
Interfaces Important Questions
- 1) WhatisInterface?
- 2) WhatisDifferencebetweenInterfaceandAbstractClass?
- 3) WhenweshouldGoforInterfaceandAbstractClassandConcreteClass?
- 4) What Modifiers Applicable for Interfaces?
- 5) ExplainaboutInterfaceVariablesandwhatModifiersareApplicableforthem?
- 6) ExplainaboutInterfaceMethodsandwhatModifiersareApplicableforthem?
- 7) CanJavaClassimplementanyNumberofInterfaces?
- 8) If2InterfacescontainsaMethodwithSameSignaturebutdifferentReturnTypes, then how we can implement Both Interfaces Simultaneously?
- 9) DifferencebetweenextendsandimplementsKeyWord?
- 10)We cannot Create an Object of Abstract Class then what is Necessity of having Constructor Inside Abstract Class?
- 11)What is a Marker Interface? Give an Example?
- 12)What is Adapter Class and Explain its Usage?
- 13)An Interface contains only Abstract Methods and an Abstract Class also can contain only Abstract Methods then what is the Necessity of Interface?
- 14)In Your Previous Project where You used the following Marker Interface, Abstract Class, Interface and Adapter Class?
The Purpose of the Constructor is
- To Initialize an Object but Not to Create an Object.
- Whenever we are creating an Object after Object Creation automatically Constructor will be executed to Initialize that Object.
- Object Creation by New Operator and then Initialization by Constructor.
- Before Constructor Only Object is Ready and Hence within the Constructor we can Access Object Properties Like Hash Code
- Whenever we are creating Child Class Object automatically Parent Constructor will be executed but Parent Object won’t be created.
- The Purpose of Parent Constructor Execution is to Initialize Child Object Only. Of Course for the Instance Variables which are inheriting from parent Class.
- In the Above Example whenever we are creating Child Object Both Parent and Child Constructors will be executed for Child Object Purpose Only.
- In the Above Example we are Just creating Student Object but Both Person and Student Constructor to Initialize Student Object Only.
- Whenever we are creating an Object automatically Constructor will be executed but it May be One Constructor OR Multiple Constructors.
- Either Directly OR Indirectly we can’t Create Object for Abstract Class but Abstract Class can contain Constructor what is the Need.
- Whenever we are creating Child Object Automatically Abstract Class Constructor will be executed to Perform Initialization of Child Object for the Properties whether inheriting from Abstract Class (Code Reusability).
- Any Way we can’t Create Object for Abstract Class and Interface. But Abstract Class can contain Constructor but Interface doesn’t Why?
- The Main Purpose of Constructor is to Perform Initialization of an Object i.e. to Provide Values for Instance Variables.
- Abstract Class can contain Instance Variables which are required for Child Class Object to Perform Initialization of these Instance Variables Constructor is required Inside Abstract Class.
- But Every Variable Present Inside Interface is Always public, static and final whether we are declaring OR Not and Every Interface Variable we should Perform Initialization at the Time of Declaration and Hence Inside Interface there is No Chance of existing Instance Variable.
- Due to this Initialization of Instance Variables Concept Not Applicable for Interfaces.
- Hence Constructor Concept Not required for Interface.
- Inside Interface we can take Only Abstract Methods. But in Abstract Class Also we can take Only Abstract Methods Based on Our Requirement. Then what is the Need of Interface? i.e. Is it Possible to Replace Interface Concept with Abstract Class?
- We can Replace Interface with Abstract Class but it is Not Good Programming Practice (This is Like requesting IAS Officer for sweeping Activity)
- While extending X we can’t extend any Other Class.
- While implementing Interface we can extend any Other Class and Hence we won’t Miss any Inheritance Benefit.
- In the Case Object Creation is Costly.
- Test t = new Test(); -> 2 Mins
- In the Case Object Creation is Not Costly.
- Test t = new Test(); -> 2 Sec
- Hence if everything is Abstract Highly Recommended to Use Interface but Not Abstract Class.
- If we are talking About Implementation of Course Partial Implementation then Only we should go for Abstract Class.
Which of the following are Valid?
- 1) ThePurposeofConstructoristoCreateanObject. X
- 2) ThePurposeofConstructoristoInitializeanObjectbutNottoCreateObject.√
- 3) OnceConstructorcompletesthenOnlyObjectCreationcompletes. X
- 4) FirstObjectwillbeCreatedandthenConstructorwillbeexecuted.√
- 5) ThePurposeofnewKeyWordistoCreateObjectandthePurposeof Constructor is to Initialize that Object. √
- 6) Wecan’tCreateObjectforAbstractClassDirectlybutIndirectlywecanCreate. X
- 7) WheneverwearecreatingChildClassObjectAutomaticallyParentClassObject will be created Internally. X
- 8) Whenever we are creating Child Class Object Automatically Abstract Class Constructor will be executed. √
- 9) WheneverwearecreatingChildClassObjectAutomaticallyParentObjectwill be Created. X
- 10)Whenever we are creating Child Class Object Automatically Parent Constructor will be executed but Parent Object won’t be Created. √
- 11)Either Directly OR Indirectly we can’t Create Object for Abstract Class and Hence Constructor Concept is Not Applicable for Abstract Class. X
- 12)Interface can contain Constructor. X