Search This Blog

29.12.17

COUNT STOPKEY ROWNUM optimization

No COUNT STOPKEY in explain plan :- ROWNUM optimization

Product :- Oracle Server (Rdbms)

Range of versions believed to be affected:-  12.1

confirmed affected:- 1. 11.1.0.7
                                        2. 10.2.0.4
Platforms affected:-         all

So i was doing explain plan for below SQL on database version 11.2.0.1.0  :-

select * from test where rownum = 0;

no rows selected


Execution Plan
----------------------------------------------------------
Plan hash value: 1829668517

-------------------------------------------------------------------------------------
| Id  | Operation           | Name          | Rows  | Bytes | Cost (%CPU)| Time     |
-------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT    |               |  3219K|   733M| 35580   (2)| 00:07:07 |
|   1 |  COUNT              |               |       |       |            |          |
|*  2 |   FILTER            |               |       |       |            |          |
|   3 |    TABLE ACCESS FULL| TEST          |  3219K|   733M| 35580   (2)| 00:07:07 |
-------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - filter(ROWNUM=0)


Statistics
----------------------------------------------------------
          0  recursive calls
          0  db block gets
     129363  consistent gets
     129358  physical reads
          0  redo size
       6210  bytes sent via SQL*Net to client
        513  bytes received via SQL*Net from client
          1  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
          0  rows processed

On Database version 11.2.0.4.0 it was :-

no rows selected


Execution Plan
----------------------------------------------------------
Plan hash value: 2416982823

------------------------------------------------------------------------------------
| Id  | Operation          | Name          | Rows  | Bytes | Cost (%CPU)| Time     |
------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT   |               |     1 |   240 |     2   (0)| 00:00:01 |
|*  1 |  COUNT STOPKEY     |               |       |       |            |          |
|   2 |   TABLE ACCESS FULL| TEST            |     1 |   240 |     2   (0)| 00:00:01 |
------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter(ROWNUM=0)


Statistics
----------------------------------------------------------
          0  recursive calls
          0  db block gets
          0  consistent gets
          0  physical reads
          0  redo size
       6210  bytes sent via SQL*Net to client
        513  bytes received via SQL*Net from client
          1  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
          0  rows processed


After studying on oracle i found this as bug on 11.2.0.1.0 explained under Oracle
PLease check your version for the bug because you can easily see the difference and performance matrix between both explain plans.

Beware! This use of rownum< can cause performance problems. Using rownum may change the all_rows optimizer mode for a query to first_rows, causing unexpected sub-optimal execution plans. One solution is to always include an all_rows hint when using rownum to perform a top-n query.

Keep sharing :)

21.12.17

SQL*Loader

SQL*Loader


What is this?

SQL*Loader loads data to an oracle database.With the help of SQL*Loader you can load data from external files to Oracle database. With the powerful data parsing engine that puts little limitation on the format of the data in the datafile.

Below key points taken from Oracle documention:-

1. Load data across a network. This means that you can run the SQL*Loader client on a different system from the one that is running the SQL*Loader server.

2. Load data from multiple datafiles during the same load session.

3. Load data into multiple tables during the same load session.

4. Specify the character set of the data.

5. Selectively load data (you can load records based on the records' values).

6. Manipulate the data before loading it, using SQL functions.

7. Generate unique sequential key values in specified columns.

8. Use the operating system's file system to access the datafiles.

9. Load data from disk, tape, or named pipe.

10. Generate sophisticated error reports, which greatly aid troubleshooting.

11. Load arbitrarily complex object-relational data.

12. Use secondary datafiles for loading LOBs and collections.


Example to load data in fixed format:- 

load data
infile 'test.dat'  "fix 12"
into table test
fields terminated by ',' optionally enclosed by '"'
(col_1, col_2)

example.dat:
007,   cd, 0008,fghi,
00009,lmn,
1, "pqrs",
0010,uvwx,

9.11.17

total size of oracle database

How to check the total size of oracle database

We know  oracle database consists of data files, redo log files, control files, temporary files and temporary files.

The size of the database actually means the total size of all these files.


col "Database Size" format a20
col "Free space" format a20
col "Used space" format a20
select round(sum(used.bytes) / 1024 / 1024 / 1024 ) || ' GB' "Database Size"
, round(sum(used.bytes) / 1024 / 1024 / 1024 ) -
round(free.p / 1024 / 1024 / 1024) || ' GB' "Used space"
, round(free.p / 1024 / 1024 / 1024) || ' GB' "Free space"
from (select bytes
from v$datafile
union all
select bytes
from v$tempfile
union all
select bytes
from v$log) used
, (select sum(bytes) as p
from dba_free_space) free
group by free.p
/

I found this on a blog and very use full. It will show you the total size and the used size. Total size includes size of  all files.

output will be like :-



Database Size        Used space           Free space
-------------------- -------------------- --------------------
78 GB                59 GB                19 GB

Keep sharing :)

7.11.17

ORA-65016: FILE_NAME_CONVERT must be specified

ORA-65016: FILE_NAME_CONVERT must be specified

I just started working on 12C version of oracle database.It's new to me and facing many problems.


Error code: ORA-65016: FILE_NAME_CONVERT must be specified


Description:"ORA-65016: FILE_NAME_CONVERT must be specified" normally occurs when you create a PDB.I will explain later what is a PDB.


Cause and solution :

 ORA-65016: FILE_NAME_CONVERT must be specified caused when Data files, and possibly other files, needed to be copied as a part of creating a pluggable database.Enable OMF or define PDB_FILE_NAME_CONVERT system parameter before issuing CREATE PLUGGABLE DATABASE statement, or specify FILE_NAME_CONVERT clause as a part of the statement and make sure the path you are giving to convert the file exists.

I think if you are creating the PDB's using GUI then you will not face this error "ORA-65016: FILE_NAME_CONVERT must be specified". If you creating ODB using script and you have gave a wrong path then may you face "ORA-65016: FILE_NAME_CONVERT must be specified".


Syntax to create PDB:-

create pluggable database TEST admin user TEST identified by TEST  file_name_convert = ('lcoation/', '/lcoation/');


Please write in comment box if you think there is better explanation on this error "ORA-65016: FILE_NAME_CONVERT must be specified".

25.9.17

ORA-01578: ORACLE data block corrupted (file # XX, block # XXXXX)

ORA-01578: ORACLE data block corrupted (file # XX, block # XXXXX)


As this error (ORA-01578: ORACLE data block corrupted) message shows that you have a corrupt block. So for data corruption you need to check what is going wrong.Check alert logs for more detail.

You can also use below sql:-

select * from v$database_block_corruption;

When i run the SQL. I found that one file # in my case 14 and some block 15353 is corrupted. As we know Corruption can occur in a table or index. So i have checked for this. In my case it was an index. So for a solution i just drop the index and created again and rebuild it. Just remember you cannot rebuild the index if it is having error ORA-01578: ORACLE data block corrupted.

So drop and create index works for me and now i can rebuild. Dropping a index will not harm you much because it's already on corrupt block.

Also i think when we create index again then it will take a different block. I am not sure about this because i have checked with sql after dropping and creating the index:-

select relative_fno, owner,segment_name,segment_type from dba_extents where file_id = 14 and 15353 between block_id and block_id + blocks - 1;

And found the same file and block information. It is strange as when i run the SQL : -select * from v$database_block_corruption;
It also shows me the same information that showed me that i still have the corroupt block for the same index and same file. But the thing is my DB is working now.  For now It's working fine.


Please if someone has faced it before let me know in comment section. How to get rid of the error ORA-01578: ORACLE data block corrupted.

For a table label corruption you can use RMAN. I am just putting the link below.

click here

Hope this will save your day.

Can anyone can tell, what are the reasons for block corruption?

13.7.17

ORA-12541: TNS:no listener

ORA-1254: TNS: could not resolve the connect identifier specified

This error is because the connect identifier given, wrongalias, cannot be resolved
into database connection details by the TNS (Transparent Network Substrate—not an
acronym particularly worth remembering) layer of Oracle Net. The name resolution
method to be used and its configuration is a matter for the database administrator. In
this case, the error is obvious: the user entered the wrong connect identifier.
The second connect attempt gives the correct identifier, orcl.

This fails with
ORA-12541: TNS:no listener

This indicates that the connect identifier has resolved correctly into the address
of a database listener, but that the listener is not actually running. Note that another
possibility would be that the address resolution is faulty and is sending SQL*Plus
to the wrong address. Following this error, the user should contact the database
administrator and ask him or her to start the listener. Then try again.
The third connect request fails with

ORA-12514: TNS:listener does not currently know of service

requested in connect descriptor
This error is generated by the database listener. SQL*Plus has found the listener
with no problems, but the listener cannot make the onward connection to the database
service. The most likely reason for this is that the database instance has not been
started, so the user should ask the database administrator to start it and then try again.

21.6.17

Cómo solucionar ORA-12505, Listener no conoce actualmente de SID

Cómo solucionar ORA-12505, Listener no conoce actualmente de SID



Este es un error muy común y realmente se chupar la sangre si no estás camino correcto. Intentaré explicarle sobre este error.

Como se puede ver este error se muestra que el oyente está en marcha y en funcionamiento, pero no sirve el SID que está destinado a. Y sí primero usted necesita comprobar donde usted está haciendo frente a este error. Es en el lado del cliente o en el lado del servidor.

Entonces, ¿cuál es el SID que está buscando este oyente?

SID es el nombre de su base de datos o puede decir identificador de servicio, que es ayudar a identificar el servicio como utilizamos PROD para la producción de UAT para el servidor de pruebas. SID de la base de datos debe ser idéntico para evitar la confusión. Su longitud es de 8 caracteres sólo significa que no se puede extender más de 8 caracteres.

¿Cómo funciona el oyente?

Como todos sabemos que es como un coche, que nos caen desde el aeropuerto al hotel, hahah lo siento, no soy bueno en los ejemplos. Así que permítanme explicar técnicamente, cada vez que intenta hacer la conexión de una máquina cliente con el servidor DB en lugar de conectar directamente oracle tiene esta utilidad llamada oyente. Como usted puede entender por su nombre, sí, sí sí que va a escuchar su reqst y luego pasar que a DB. Wow gran derecho.?


Ahora, ¿qué pasa si usted está tomando un taxi a algún hotel y ese hotel no existe? Lo mismo ocurre con este error. El conductor del taxi no sabe adonde usted va tan él a través de usted el error: -

"ORA-12505, TNS: Listener no sabe actualmente de SID dado en el descriptor de conexión"


¿Cómo solucionar esto "ORA-12505, TNS: el oyente no está actualmente"?



Es muy fácil. Dile al taxista nombre del hotel que realmente existe. La tarifa suficiente ¿verdad?

OK Sugerencias para solucionar problemas.

Todos sabemos que listner.ora y tnsnames.ora son dos archivos que están involucrados en este caso. Y la ubicación de estos archivos son $ ORACLE_HOME \ network \ admin

Ahora compruebe su tnsnames.ora que SID se menciona es correcto o no. Al igual que para mi prueba de DB es debe ser como a continuación: -
TEST_TNS = (DESCRIPCION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP) (HOST = *******) (PORT = 0000))) (CONNECT_DATA = (SERVICE_NAME = TEST) (INSTANCE_NAME = TEST)


Usted puede cambiar el formato también pero me gusta esta manera. Y sí PORT no puede ser 0000.;)

Ahora sabe que el nombre del servicio SID TEST está escuchando en el número de puerto 0000.

Si he establecido entradas exactas de las que no debe enfrentar ningún problema. Por favor, compruebe estas entradas. También verifique el archivo listner.ora también. Si hay desajuste en las entradas. Que vas a enfrentar el mismo problema

Eso resolverá su problema.
También compruebe este enlace: - ora-12154-error-en-oracle-11g-and-12c

Sigue compartiendo. Mantén la sonrisa

ORA-00240控製文件入隊持續超過XXX秒

ORA-00240控製文件入隊持續超過XXX秒


說明:控製文件排隊持有超過字符串秒

原因:1.當前進程沒有在最大允許時間內釋放控製文件入隊。
       2.未經發布的Bug 7570453 - [3 RAC NODE] ORA-00240在升級到10.2.0.4.0之後啟動的問題已被調查,該錯誤被關閉為Not Bug。開發人員確認這只是一個警告,讓DBA知道一個CF入隊被持有超過120秒。這不是一個錯誤,如果CF入隊超過900秒(15分鐘),則不會發生錯誤。
當數據庫中有很多數據文件時,會發生該消息。 DBWriter(dbw0)由於不得不打開這些數據文件而花費太多的時間來釋放CF入隊。

操作:1.重新發出失敗的任何命令,並與事件信息聯繫Oracle支持服務。

   2.建議通過減少數據庫文件的數量來減少這個時間。更多的是建議使用較少但較大的數據文件,而不是較小的數據文件。


  如何照顧Oracle審計


  什麼是Oracle 10天規則?

20.6.17

ORA-12505, TNS:listener does not currently know of SID given in connect descriptor


How to solve ORA-12505, Listener does not currently know of SID  


This is very common error and really it will suck your blood if you are not right path. I will try to explain you about this error.

As you can see this error is showing itself that listener is up and running but not serving  the SID that it is meant for. And yes 1st you need to check where you are facing this error. Is it on client side or on server side.

So what is the SID this listener looking for?

SID is name for your database or you can say service identifier, That is help to to identify the the service like we use PROD for production UAT for testing server. SID of Database should be identical to avoid the confusion. It's length is 8 character only that means you can not extend it more then 8 character.

Now how listener works ?

As we all know its like a car, That drop us from airport to hotel, hahah sorry I am not good in examples. So let me explain technically, whenever you try to make connection from a client machine to the DB server rather than connecting directly oracle have this utility called listener. As you can understand by name it self, yes yes it is going to listen your reqst and then pass that to DB. wow great right.?


Now what if you are taking a taxi to some hotel and that hotel does not exist? Same happens with this error. Taxi driver don't know where you are going so it will through you the error :-

"ORA-12505, TNS:Listener does not currently know of SID given in connect descriptor"


How to solve this "ORA-12505, TNS:listener does not currently" ?



It's very easy. Tell the taxi driver name of hotel that really exist. Fare enough right?

OK Tips for troubleshooting.

We all know that listner.ora and tnsnames.ora  are two files that are involved in this case. and location of these files are $ORACLE_HOME\network\admin

Now check your tnsnames.ora that SID is mentioned is correct or not. Like for my TEST DB is should be like below :-
TEST_TNS = (DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=*******)(PORT=0000)))(CONNECT_DATA=(SERVICE_NAME=TEST)(INSTANCE_NAME=TEST)))


You can change the format also but i like this way. and yes PORT can't be 0000. ;)

Now you know SID service name TEST is listening at 0000 port number.

If I have set accurate entries than you shouldn't face any issue. So Please check these entries. Also check listner.ora file too. If there is mismatch in entries. Than you going to face same issue

That will solve your problem.
Also check this link :- ora-12154-error-in-oracle-11g-and-12c

Keep sharing. Keep smile ;)

20.5.17

ORA-02291: integrity constraint violated - parent key not found

“Error: ORA-02291: integrity constraint violated - parent key not found”



Reason:   A Primary key does not have the same value as the foreign key. We will discuss it in detail later in this article.

Action:   For ORA-02291: integrity constraint violated - parent key not found You may either delete the foreign key or the matching primary key can be added. In either way, you may try to get this error corrected.


Let's understand more about ORA-02291: integrity constraint violated - parent key not found?


The Oracle software brought us the strength by which multiple tables in the database can pass on information so efficiently. Not only this, there are numerous devices in this software which enables access to and sourcing data from multiple tables. You can easily execute complicated database issues without an unusual uncertainty by creating statements with the fantastic characteristic of this software. Realistically, if we talk about user or database no one is perfect or 100% error-free or have the sense to identify forthcoming possible errors occurs throughout the regular activities.


The most well-known error occurs while manipulating data across multiple data tables is the ORA-02291.Now, we will have a brief discussion about ORA-02291: integrity constraint violated - parent key not found:-

" integrity constraint <constraint name> violated – parent key not found” is the standard message co-occurred with the ORA-02291.Which means someone used the primary key in order to execute a reference to a specific table but somehow, during this process specified column failed to match the primary key. As well as, the other reason for executing the error can be non-existence of primary key for the table in question.It is useful to secure a note of few important things related to the primary key before we proceed further.




In oracle, a primary key is a single field or combination of fields that defines a record in a unique way. Every field of the primary key must contain some value, it means, the value of any field can never be null and each table contains only one primary key. One last important thing about a primary key that it cannot hold more than thirty-two columns.


Now while we are familiar with all concepts of a primary key, it will not be difficult for us to determine the error and fix it with fewer efforts (ORA-02291: integrity constraint violated - parent key not found). 

Usually, the error occurs when foreign key plays a parent-child relation between two tables. The process of foreign key states that each table shares the same value. overall, the referenced table is a parent table. On the other hand, the child table will take place where foreign key originates from. It is quite often that a foreign key in a child table will reference to a primary key in a parent table. The cause why the ORA-02291 trigger is when the corresponding parent is empty (does not have any value) and by the time, you still try to insert a value into a child table which includes a foreign key. Your this action disrupts the integrity of referential relationship, bother standard functionality and provoking oracle to produce an error message "ORA-02291: integrity constraint violated - parent key not found".



“The valid method to fix the error ORA-02291: integrity constraint violated - parent key not found “--- the primary table to insert the value will be the parent and obviously secondary table to insert value will be the child table. To elaborate, you should insert the value inside the parent table first and later, add it to the child table.



keep sharing :) 




17.5.17

ORA-01033: ORACLE initialization or shutdown in progress

ORA-01033: ORACLE initialization or shutdown in progress



Cause: You are trying to access oracle database while  database is either starting up or shuting down (ORA-01033: ORACLE initialization or shutdown in progress).

Action: For ORA-01033: ORACLE initialization or shutdown in progress you need to wait for some time. Then retry the operation again (connect after some time) to check if ORA-01033: ORACLE initialization or shutdown in progress is there or not.


What is ORA-01033: ORACLE initialization or shutdown in progress?

This is very common error and not occurs much. But you must have some idea if you face ORA-01033: ORACLE initialization or shutdown in progress occurs. As we know We can only set database to  Shutdown or startup using SYSDBA privileges. So you must have SYSDBA privileges to troubleshoot. I suggest  to  wait for 5mins because may be your DBA has shutdown the Database and it's in progress.Or if you are a DBA then check the status of database  do start if it is down. My case below:-

[server@****** ~]$ sqlplus /nolog

SQL*Plus: Release 12.1.0.1.0 Production on Wed May 17 14:24:19 2017

Copyright (c) 1982, 2013, Oracle.  All rights reserved.

SQL>conn test/test@test
ERROR:
ORA-01033: ORACLE initialization or shutdown in progress
Process ID: 0
Session ID: 0 Serial number: 0

The ORA-01033 error also happens when the database is not open. SO in this case below is the solution :

"alter database open"


Brief about ORA-01033: ORACLE initialization or shutdown in progress :- 


Sometime when We stop our oracle database then if at the same time any user will try to access the database then that user will face the issue ORA-01033: ORACLE initialization or shutdown in progress .For work around to solve "The ORA-01033: ORACLE initialization or shutdown in progress" ask your user to wait for some time and check the status of the database. Also check the alert logs for error ORA-01033: ORACLE initialization or shutdown in progress.You need to check the status and see if your database is in the middle of startup or shutdown.

There may be other cause for error ORA-01033: ORACLE initialization or shutdown in progress is like when RAM regions held by the OS and that makes Oracle think that instance is already running. Then also Database will through the error ORA-01033: ORACLE initialization or shutdown in progress.

Solution for ORA-01033: ORACLE initialization or shutdown in progress provided by oracle. Check your database status and paas below command by SYSDBA if your database is not open.
1. wait for some time
2. check the status of DB
3. "alter database open"

Keep sharing :)

10.5.17

ORA-12714 invalid national character set specified

Error: ORA-12714

ORA-12714  invalid national character set specified 

ORA-12714 invalid national character set specified  is very common error and related to database parameters and sessions parameters.


Cause 

Only UTF8 and AL16UTF16 are allowed to be used as the national character set. Check your NLS_NCHAR_CHARACTERSET which is set using:

select value from NLS_DATABASE_PARAMETERS where parameter = 'NLS_NCHAR_CHARACTERSET';

it should return UTF8 Or AL16UTF16

Action

Ensure that the specified national character set is valid

Please aware that at session level, some parameters could be different. If you want to be sure, compare the results of:

select * from nls_database_parameters;

with:

select * from nls_session_parameters;



Please find the below information:-    

Bug No :- 2834295 

Cause :-  declaring cursor for a function that returns a table of NVARCHAR2

 Affects below products :
Product (Component)
Oracle Server (Rdbms)
Range of versions believed to be affected
Versions BELOW 11.1
Versions confirmed as being affected
  • 10.2.0.3
  • 9.2.0.8
  • 9.2.0.2
Platforms affected
Generic (all / most platforms affected)

Fixed:

The fix for 2834295 is first included in
  • 11.1.0.6 (Base Release)
  • 10.2.0.4 (Server Patch Set)

Please check for document number on oracle support :-  2834295.8



4.4.17

Core Java Interview Questions

1) Explain run time polymorphism in Java ?
Polymorphism can be explained as an object's ability to adapt to the program's context and take multiple forms. The method overriding is an example of run time polymorphism. You can have a method in a subclass, which overrides the method in its super classes with the same name and signature. At run time, Java virtual machine determines the appropriate method to be called.
2) What are the rules (method access permission and exception) that needs to be followed, during method overloading and overriding ?

During method Overloading, method name should remain same. But method signature can vary. Components of signature that can vary are
  • Number of arguments
  • Datatype of arguments
  • Order of arguments
During method Overriding, make sure that the method is not throwing checked exceptions that are new or higher than those declared by the overridden method.But we can't override Static and Final methods.
3) What is the difference between an Interface and abstract class?
AbstractInterface
Supports Single inheritanceSupports Multiple inheritance
Supports abstract and Non-abstract methodsAllows only abstract methods
Supports Non-static and non-final variables also.Variables must be static and final(implicitly)
Supports non public memberOnly public members are allowed
Using extends keywordUsing implements keyword
It can invoke if main existsPure abstract
FasterFlexible


4) Explain the difference between compile time and run time polymorphism in Java ?

Compile time PolymorphismRun time Polymorphism
Method are called at compile timeMethod are called at run time
Ex: OverloadingEx: Overriding


5) What is the difference between Overloading and Overriding ?

OverloadingOverriding
Methods are overloaded during compile timeMethod overriding takes place during runtime
All the overloaded methods should be placed in the same classWe can override methods in sub class
We can overload static methodsStatic methods can't be overridden
Methods are bonded together using static binding.Overridden method are bonded via dynamic bonding based upon actual Object.
To overload a method, method signature needs to be changedThere is no need to change the signature
Private and final method can be overloaded.Private and final method can't be overridden
Method is relatively fast.Method is relatively slow.

6) What is the difference between class and object ?
ClassObject
Template/Blue print of an object.It is an instance of a class. Object have states and behaviors.
A logical construct.A Physical reality.

7) What are the major object oriented concepts in Java ?
Abstraction
It denotes the critical properties of an object which differentiate from other object and thus provide crisply defined conceptual boundaries relative to the perspective viewer.

Encapsulation
Encapsulation can be explained as a mechanism which binds the code and the data it manipulates. It also keeps them safe from external intervention and misuse.

Inheritance:
One object inherits the properties and methods of another Object.

Polymorphism
It is an ability of an object to take on many forms. Ex: Compile time polymorphism – method over loading. Run time polymorphism – method overriding

8) Why Java is not supporting multiple inheritance ?


Main features of java are very Simple. if multiple inheritance is supported, it creates ambiguity around Diamond problem and it does complicate the design and creates problem during casting, chaining etc. So Java will support multi-inheritance via single inheritance with interfaces to overcome above issues.

9) What is meant by final keyword in Java ?
  • If final variable is used in front of variable, we can't change the value.
  • If the variable is used in front of method, it can't be overridden.
  • If it is used in front of Class, class can't be extended by any other class.

10) What is meant by static keyword in Java ?


A static is a member of a class that's not associated with instance. So static members can be accessed without creating an instance of a class.

11) What is meant by JVM ?
JVM(Java Virtual Machine) is a run time environment for the compiled java class files. Main function of JVM is to convert byte code(.class file) to machine code and send appropriate commands to underlying machine for execution.
12) What is the difference between interpreter and compiler in Java ?
CompilerInterpreter:
Compiler translates source code to JVM byte code.Executes the byte code by running the program.
Compiling happens when programmers invoke compiler after the program is writtem.Interpretation happens at run time
For compilation, use command "javac Employee.java". Compilation of java file will generate class file (ex: Employee.class).Command java Employee, executes the class file (i.e Employee.class)

13)  Can abstract class implements another interface ?

Yes. It's just a special case of implementation by which subclasses are forced to implement the methods.

14) Can abstract class extend another abstract class?
Yes. It is perfectly valid for an abstract class to extend another abstract class.
15) Can a interface extend another interface?
Yes. An interface can extend another interface in Java.
16) What Is Stack?
  • Each Java thread have a private JVM stack, created along with thread.
  • Stack stores frames. Frames are used for storing data (Variable and Object Data as well as partial results) and to perform operations such as
    • Dynamic linking
    • Dispatch exceptions when error occurs
    • Return values when methods are invoked. Since the stack can't be accessed directly, it push and pop frames.
  • It is not mandatory that the Java virtual machine stack had to be continuous.
  • JVM throws StackOverflowError, if any computation inside a thread needs larger JVM stack than allocated .

17) What Is Heap?
  • When JVM starts, heap is created
  • Heap is the runtime data area of the JVM
  • It is shared by all the threads inside the JVM
  • It allocates memory for all class instances and arrays
  • Heap storage for objects is reclaimed by garbage collector when it is not used.
  • JVM throws OutOfMemoryError, If a computation needs more heap than what can be supplied by the automatic storage management system.

18) Can you explain about Upcasting and Downcasting in Java ?
  • Upcasting : Casting a Sub class to Super class. Upcasting is called as widening.
  • Downcasting : Casting a Super class to Sub class. Downcasting is called as narrowing.

19) Can you explain about Implicit and Explicit type casting ?


Implicit casting (widening conversion)
 :

When JVM encounters a data type of lower size which occupies less memory, it is assigned to a data type of higher size implicitly by the JVM. This is also known as automatic type conversion. For Example
int i = 1; // 4 bytes
double d = i; // 8 bytes

Explicit casting:


When a data type of higher size which occupies more memory, needs to be assigned to a data type of lower size, it is called explicit casting. This type of casting won't be done implicitly by the JVM. This casting operation should be performed by the programmer. For example 
double d = 1.0; 
int i = (int) d;

20) Can you explain about markable interface in Java ?
Interfaces with no methods are known as Marker interface. Some of the markable interfaces are
 java.lang.Cloneable
 java.io.Serializable
 java.util.EventListener

21) Can you explain about reflection in Java ?

If a programmer wants to access entities or invoke methods in a program dynamically, i.e. if the programmer is unaware of the methods and variables that needs to be invoked at runtime but unaware of it while coding, we can use reflection. For example
Method method = ABC.getClass().getMethod("doSomething", null);
method.invoke(ABC, null);
22) Can you explain about java.lang.class ?

When JVM creates an instance of a class, it creates an object "java.lang.Class object" which describes the type of the object. This class object is shared by all the objects of a class. If you want to access the class object of an instance, use getClass() method of the object. This method is inherited from java.lang.Object
Ex: Created two instances class called Programmer
Programmer A = new Programmer();
Programmer B = new Programmer();
// For check Instances
if(A.getClass() == B.getClass())
{
 System.out.println("A and B are instances of same class");
}else{
 System.out.println("A and B are instances of different class");
}

23) Can you explain about Singleton class in Java ?


Singleton class is used to control no of object created for a class, limiting the number to one. But if the situation changes in future, it allows to create more objects without affecting existing clients.

24) Can you explain about Static class in Java ?


A class can be made static provided that the class is a nested class. A nested class is class which is defined inside a class. But top class can't me made static. Example :
public class Test
{ 
 static class StaticInnerClass
 {
 public static void innerMethod()
 { System.out.println("Static Inner Class!"); }
 } 
 public static void main(String args[])
 {
 Test.StaticInnerClass.innerMethod();
 }
}

25) Can you explain about volatile Keywords in Java ?
  • Volatile keyword is used to indicate the threads using a common variable that, the variable which is declared as Volatile can be updated by multiple threads. So threads should not cache the threads locally and in turn should get the value for the variable from main memory. 
  • If a variable is declared as volatile, it won't be serialized.

26) What are the advantages of organizing classes and interfaces into a package ?
  • Determination of a category of a file is simplified.
  • Name space collision is avoided.
  • Access restriction can be applied with the use of packages.
  • Packages provide reusability of code

27) Can you explain about Java naming convention ? 


Common Naming conventions as below :
  • package names always start with lowercase characters. Ex: java.util
  • Class names always begin with a capital letter and followed next word start with a capital letter. Ex: GregorianCalendar
  • Java Naming convention specifies that instances and other variables must start with lowercase followed next word should be capital letter. Ex : MyClass myClass = new MyClass();
  • Constant variables are declared using “static final” modifiers. And such variables must contain only UpperCase charachters and multiple words must be seperated using ‘_’. Ex: static final char END_OF_FILE = 'e';
  • Methods in Java also follow the same like Objects and variables. For example
void myMethod(){
String strVal = "ABCD";
}
28) How to call a garbage collector in java?
System.gc() or Runtime.getRuntime().gc().

29) What are the new features available in Java 1.7 ?
  • Strings in switch Statement 
  • Type Inference for Generic Instance Creation 
  • Multiple Exception Handling 
  • Support for Dynamic Languages 
  • Try with Resources 
  • Java nio Package 
  • Binary Literals, underscore in literals 
  • Diamond Syntax 
  • Automatic null Handling

30) What are the advantage of Inheritance in Java ?
  • Re-usability : Inheritance helps derived class to use methods of base class without rewriting them
  • Extensibility : Extending the base class logic as per business logic of the derived class
  • Data hiding : Allows base class to keep some private data which can't be altered by the derived class

31) Why String is immutable in Java ?
String is a special type of immutable class. Immutable class is a class which once created, it’s contents can not be changed. Immutable objects are the objects whose state can't be changed once constructed.

32) Can you explain about information hiding in Java ?


Information hiding helps objects to hide critical information from other other objects accessing it. It effectively decouples the method being invoked from the internal workings of a function. By doing so, object can change the hidden portions of the function without changing the calling code. Encapsulation is a common technique programmers use to implement information hiding.

33) Can you explain about encapsulation in Java ?


Encapsulation helps java to bind code and data it manipulates, restrict outside interference and misuse of data. It also hides irrelevant details of an object.

34) Can you explain about the access modifier in Java ?


Access modifiers specifies the access levels of a variable or method. Java access modifiers are public, private, protected, default modifier (Default access modifier).
Access ModifiersSame ClassSame PackageSubclassOther packages
publicYesYesYesYes
protectedYesYesYesNo
defaultYesYesNoNo
privateYesNoNoNo

35) What is the difference between super() and this() in Java ?
If you want to access methods of the base class from derived class "super" keyword is used. To access methods of the same class "this" keyword is used.

36) Can you explain about the constructor in Java ?
  • Java constructors are special methods that are called when an object is instantiated. 
  • When objects are instantiated, arguments passed to the constructor will initialized the variables in an object. 
  • Name of the constructor should be same as the name of the Class. It can't have any return type.
  • A class can have multiple constructors. Calling a constructor from another constructor in the same class is called Constructor chaining. 
  • All classes have a default empty constructor.

37) Can constructor take parameters ?


Yes. Constructor can take arguments.

38) Can you explain about the default constructor in Java ?


When a constructor is not specified explicitly, java compiler automatically creates a "Default Constructor". When we creates and object instance, default constructor initialize variables with it's default values. 

39) What are the common reasons to define a default constructor ?
  • To construct an object with default values. 
  • To initialize an object that doesn't need parameters in that initialization process. 
  • To redefine the scope of the constructor. By making the default constructor private, Java prevents everyone other than the class from constructing an object.

40) Can you explain about native method in Java ?
  • Native is non access modifier. It can be applied only to method. 
  • It indicates the Platform-Dependent implementation of method or code.

41) Can you explain about strictfp keyword in Java ?
If we want floating point values to be consistent across platforms, then we need to use "strictfp" as per IEEE 754 standard. When a program runs on multiple platforms, precision of floating point differ which in turn given different results. strictfp helps to enforce the precision across all platforms. For example
Class Level - public strictfp class StrictFpModifierExample{}
Method Level - public strictfp void example() {}

42) Can you explain about String pool ?


String Pool is a pool of strings stored in Java heap memory. String objects can be created either by new operator or by specifying the values in double quotes. 
Case 1 : When a new string is created using double quotes, JVM searches string pool for the string with the same value. if it finds a string which matches the values, it will return the reference of the string. Else it will create a new string in the pool and returns that reference.
String s1 = "Cat"; 
String s2 = "Cat"; 
if(s1 == s2) System.out.println("equal"); //Prints equal.
Case 2 : When new operator is used to create a string, String class will be forced to create a new String object. To put the newly created string into the pool or assign it to another string, use intern(). 
String n1 = new String("ABCD"); 
String n2 = new String("ABCD"); 
if(n1 == n2) System.out.println("equal"); //No output.

43) Differences between String, StringBuffer and StringBuilder in Java ?

StringStringBufferStringBuilder
ImmutableMutablemutable
String operations such as append would be less efficientString operations such as append would be more efficient,String operations such as append would be more efficient
-synchronizedNot synchronized.
-versions 1.4 or below you’ll have to use StringBuffer.StringBuilder was introduced in Java 1.5

44) What are the advantage of using unicode characters ?
  • Much larger number of characters or group of characters
  • Contains some non western European characters
  • Supported by all modern technologies
  • Enhance integration opportunities
  • Easy conversion from legacy code pages

45) Can you explain about literals in Java ?


Literals are used to represent a fixed value in source code. Literals don't require computation. For Example, we will have a look at using literals to assign a value to an int variable.
int Days = 7;
46) Is it possible to override an overloaded method in Java ?
Yes. We can override an overloaded method if that method in not a static or final.

47) What is the maximum size of an int ?


-(2 power 31) to (2 power 31-1) or -2,147,483,648 to 2,147,483,647

48) Can you explain about autoboxing and unboxing in Java ?


When primitive data types are automatically converted into it's  wrapper type, it is called boxing. The opposite operation of converting wrapper class objects to it's primitive type is known as unboxing.
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1); //autoboxing - primitive to object
int number = list.get(0); // unboxing

49) How to change the heap size of a JVM ?
 

The old generation's default heap size can be overridden by using the -Xms and -Xmx switches to specify the initial and maximum sizes respectively:
Format - java -Xms <initial size> -Xmx <maximum size> program
Example - java -Xms64m -Xmx128m Myprogram

50) Is it possible to have multiple public classes in Java ?
As per java language specification, there can be only one public class in a file (.java) and file name should be same as public class name. If you want another class accessible in other places, you may create a separate java file.

51) Write a program that override equal() and hashcode()?


Object's hash code is a number( 32-bit signed int) that helps hash-based data structure to manage an object. Hash code is supposed to be unique number assigned to an object by JVM. But if two objects are equals, then both the objects will have same hash code. Implementation of hashcode method in a class should be in such way that if two objects are same and when compared by equal method, then those two objects must return same hash code. Both hashCode and equals method should be overridden.
class Person{
 private String name;
 private int age; 
 public Person(String name, int age){
 this.name = name;
 this.age = age;
 }
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public int getAge() {
 return age;
 }
 public void setAge(int age) {
 this.age = age;
 }
 
 public int hashCode(){
 int hashcode = 0;
 hashcode = age*12;
 hashcode += name.hashCode();
 return hashcode;
 }
 
 public boolean equals(Object personObject){
 if (personObject instanceof Person) {
 Person pp = (Price) Person;
 return (pp.name.equals(this.name) && pp.age == this.age);
 } else {
 return false;
 }
 }
}

52) Can you explain about Enum datatype in Java ?


Enum keyword is used to represent a fixed number of related values. Since enum constants are implicitly static and final,there values can't be changed once they are created.
public enum Day {
 SUNDAY, MONDAY, TUESDAY, WEDNESDAY,THURSDAY, FRIDAY, SATURDAY 
}
// Uses 
public void weekDay() {
 switch (day) {
 case MONDAY:
 System.out.println("Mondays are bad.");
 break;
 }
}

53) Can you explain about the recursion ?
The function called itself is called recursion. For example, a factorial program
int factorial(int number) {
 if(number == 0) {
 return 1;
 }
 factorial_i(number, 1);
}
int factorial_i(int currentNumber, int sum) {
 if(currentNumber == 1) {
 return sum;
 } else {
 return factorial_i(currentNumber - 1, sum*currentNumber);
 }
}

54) Can you explain about call by value and call by reference ?
  • Call by Value - When a method receives a value as an argument, the value received is a copy of the original value of the calling method. Even if the value is altered inside the method, it won't be reflected in the variable in the calling method.
  • Call by reference - When a method receives reference of a variable, any change made to it in the called method won't be reflected in the calling method.

55) What is responsibility of Garbage Collector ?
For efficient memory utilization, Java uses Garbage collector. The main objective of the garbage collector is free up memory by detecting unused objects and deleting them. Garbage Collector gets invoked automatically and it won't assure required memory for a program to run.

56) What is the use of finalize method ?
The Object class has a special method named finalize() that is called by garbage collector to allow an object to do the necessary cleanup that needs to occur before the memory used by the object are reclaimed. The finalize() method can be overridden by any class that uses system resources (file , db connection) and needs to release those resources or to perform other cleanup as part of implicit destruction by the garbage collector.

57) Explain JDBC ?
Java Database Connectivity is a technique of connect java front end to back end database and allowing the retrieval and manipulation of data in the database using java.

58) How do you connect to the Database ?
The process of using JDBC to connect to the database is as follows:
Register the driver: Class.forName(”driverName”); For example, sun.jdbc.odbc.JdbcOdbcDriver
Connection con = DriverManager.getConnection(”url,”myLogin”,myPassword”);
For example url may be jdbc:odbc:dsn_name.

Creating the JDBC Statement and Retreiving:
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);

59) What are the drivers and when it will use ?
  • JDBC-ODBC Bridge Driver for Java and Database (Java Application)
  • JDBC-Net pure java driver for Applet and Database(Applet application)
  • Native-API partly Java driver for Native class and Database (for network application)
  • Native Protocol pure java driver for vendor specific application (EJB application)