Monday, October 31, 2011

SQL Interview Question and Answers for Beginners

What the difference between UNION and UNIONALL?
Union will remove the duplicate rows from the result set while Union all does'nt.
What is the difference between TRUNCATE and DELETE commands?
Both will result in deleting all the rows in the table .TRUNCATE call cannot be rolled back as it is a DDL command and all memory space for that table is released back to the server. TRUNCATE is much faster.Whereas DELETE call is an DML command and can be rolled back.
Which system table contains information on constraints on all the tables created ? 
yes,
USER_CONSTRAINTS,
system table contains information on constraints on all the tables created
How to find out the database name from SQL*PLUS command prompt?
Select * from global_name;
This will give the datbase name which u r currently connected to.....
What is the difference between SQL and SQL Server ?
SQLServer is an RDBMS just like oracle,DB2 from Microsoft
whereas
Structured Query Language (SQL), pronounced "sequel", is a language that provides an interface to relational database systems. It was developed by IBM in the 1970s for use in System R. SQL is a de facto standard, as well as an ISO and ANSI standard. SQL is used to perform various operations on RDBMS.
What is diffrence between Co-related sub query and nested sub query?
Correlated subquery runs once for each row selected by the outer query. It contains a reference to a value from the row selected by the outer query.
Nested subquery runs only once for the entire nesting (outer) query. It does not contain any reference to the outer query row.
For example,
Correlated Subquery:
select e1.empname, e1.basicsal, e1.deptno from emp e1 where e1.basicsal = (select max(basicsal) from emp e2 where e2.deptno = e1.deptno)
Nested Subquery:
select empname, basicsal, deptno from emp where (deptno, basicsal) in (select deptno, max(basicsal) from emp group by deptno)
WHAT OPERATOR PERFORMS PATTERN MATCHING?
Pattern matching operator is LIKE and it has to used with two attributes
1. % and
2. _ ( underscore )
% means matches zero or more characters and under score means mathing exactly one character
1)What is difference between Oracle and MS Access?
2) What are disadvantages in Oracle and MS Access?
3) What are feratures&advantages in Oracle and MS Access?

Oracle's features for distributed transactions, materialized views and replication are not available with MS Access. These features enable Oracle to efficiently store data for multinational companies across the globe. Also these features increase scalability of applications based on Oracle.
What is database?
A database is a collection of data that is organized so that itscontents can easily be accessed, managed and updated. open this url : http://www.webopedia.com/TERM/d/database.html
What is cluster.cluster index and non cluster index ? 
Clustered Index:- A Clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table may have only one clustered index.Non-Clustered Index:- A Non-Clustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows in the disk. The leaf nodes of a non-clustered index does not consists of the data pages. instead the leaf node contains index rows.
How can i hide a particular table name of our schema?
you can hide the table name by creating synonyms.
e.g) you can create a synonym y for table x
create synonym y for x;
What is difference between DBMS and RDBMS?
The main difference of DBMS & RDBMS is
RDBMS have Normalization. Normalization means to refining the redundant and maintain the stablization.
the DBMS hasn't normalization concept.
What are the advantages and disadvantages of primary key and foreign key in SQL?
Primary key
Advantages
1) It is a unique key on which all the other candidate keys are functionally dependent
Disadvantage
1) There can be more than one keys on which all the other attributes are dependent on.
Foreign Key
Advantage
1)It allows refrencing another table using the primary key for the other table

JAVA Interview Questions

JAVA Interview Questions


Question: How could Java classes direct program messages to the system console, but error messages, say to a file?
Answer: The class System has a variable out that represents the standard output, and the variable errthat represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);

Question: What's the difference between an interface and an abstract class?
Answer: An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.

Question: Why would you use a synchronized block vs. synchronized method?
Answer: Synchronized blocks place locks for shorter periods than synchronized methods.

Question: Explain the usage of the keyword transient?
Answer: This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

Question: How can you force garbage collection?
Answer: You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.

Question: How do you know if an explicit object casting is needed?
Answer: If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example:
Object a; Customer b; b = (Customer) a;
When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.

Question: What's the difference between the methods sleep() and wait()
Answer: The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

Question: Can you write a Java class that could be used both as an applet as well as an application?
Answer: Yes. Add a main() method to the applet.

Question: What's the difference between constructors and other methods?
Answer: Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.

Question: Can you call one constructor from another if a class has multiple constructors
Answer: Yes. Use this() syntax.

Question: Explain the usage of Java packages.
Answer: This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.

Question: If a class is located in a package, what do you need to change in the OS environment to be able to use it?
Answer: You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:
c:\>java com.xyz.hr.Employee

Question: What's the difference between J2SDK 1.5 and J2SDK 5.0?
Answer:  There's no difference, Sun Microsystems just re-branded this version.

Question: What would you use to compare two String variables - the operator == or the method equals()?
Answer:  I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.



Question: Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?
Answer: Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.

Question: Can an inner class declared inside of a method access local variables of this method?
Answer: It's possible if these variables are final.

Question: What can go wrong if you replace && with & in the following code: String a=null; if (a!=null && a.length()>10) {...}
Answer: A single ampersand here would lead to a NullPointerException.

Question: What's the main difference between a Vector and an ArrayList
Answer: Java Vector class is internally synchronized and ArrayList is not.

Question: 
When should the method invokeLater()be used?
Answer: This method is used to ensure that Swing components are updated through the event-dispatching thread.


Question: How can a subclass call a method or a constructor defined in a superclass?
Answer: Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor.

Question: When you declare a method as abstract method ?
Answer: When i want child class to implement the behavior of the method.

Question: Can I call a abstract method from a non abstract method ? 
Answer: Yes, We can call a abstract method from a Non abstract method in a Java abstract class      

Question: What is the difference between an Abstract class and Interface in Java ? or can you explain when you use Abstract classes ? 
Answer: Abstract classes let you define some behaviors; they force your subclasses to provide others. These abstract classes will provide the basic funcationality of your applicatoin, child class which inherited this class will provide the funtionality of the abstract methods in abstract class. When base class calls this method, Java calls the method defined by the child class.
  • An Interface can only declare constants and instance methods, but cannot implement default behavior.
  • Interfaces provide a form of multiple inheritance. A class can extend only one other class.
  • Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
  • A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
  • Interfaces are slow as it requires extra indirection to find corresponding method in the actual class. Abstract classes are fast.
Question: What is user-defined exception in java ? 
Answer: User-defined expections are the exceptions defined by the application developer which are errors related to specific application. Application Developer can define the user defined exception by inherite the Exception class as shown below. Using this class we can throw new exceptions.
Java Example : public class noFundException extends Exception { } Throw an exception using a throw statement: public class Fund { ... public Object getFunds() throws noFundException { if (Empty())throw new noFundException(); ... } } User-defined exceptions should usually be checked.



Saturday, October 29, 2011

SQL For Beginners

A Database is one which has 1 or more tables.
A Table is the actual data with rows and columns. Table has a unique name. SQL is used to interact with database.

SQL -- Structured Query Language, its not case sensitive.
SQL commands comes under the following catagories

1. DML -- Data Manipulation Language
SELECT - extracts data from a database
UPDATE - updates data in a database
DELETE - deletes data from a database
INSERT INTO - inserts new data into a database

2. DDL -- Data Definitaion Language
CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index

3. DCL -- Data Control Language
GRANT - SQL GRANT is a command used to provide access or privileges on the database objects to the users
REVOKE - command removes user access rights or privileges to the database objects.

4. TCL -- Transactional Control Language
COMMIT - it successfully saves the transaction that we did.
ROLLBACK - is used to revert the transactions that we did before.

SQL COMMANDS

SELECT : -- is used to extract the data from db
Syntax : SELECT colName FROM tableName;

DISTINCT: -- is used to select distinct data from column if any duplicate data exists.
Syntax: SELECT DISTINCT colName FROM tableName;

WHERE: -- is used to extract only those records that fulfill a specified criterion.
Syntax: SELECT colName FROM tableName WHERE colName operator Value;
Operator can be =, <> , >, <, >=, <=, BETWEEN, LIKE, IN ORDER BY: -- is used to sort the result-set by a specified column. Syntax: SELECT colName FROM tableName ORDER BY colName ASC or DESC

INSERT INTO: statement is used to insert a new row in a table. Syntax: INSERT INTO table_name VALUES (value1, value2, value3,...) We can Insert data in specified columns as Eg: INSERT INTO Persons (P_Id, LastName, FirstName) VALUES (5, 'Tjessem', 'Jakob') ;

UPDATE: -- is used to update existing records in a table.
Syntax: UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value

DELETE: is used to delete records / rows in a table.
Syntax: DELETE FROM tableName WHERE colName = othercolName;
To delete all records from a table, then give below command
DELETE * FROM table_name

TOP: TOP clause is used to specify the number of records to return.
Syntax: SELECT TOP number|percent column_name(s) FROM table_name
Eg1 : SELECT TOP 2 * FROM tableName; -- returns top 2 records from table.
Eg2: SELECT TOP 50 PERCENT * FROM tableName; -- returns top 50 % records from table.
Eg3: SELECT * FROM Persons WHERE ROWNUM <=5 -- returns top 5 records from table. (IN ORACLE)
Eg4: SELECT * FROM Persons LIMIT 5 -- returns top 5 records from table. ( IN MYSQL)


LIKE: operator is used to search for a specified pattern in a column.
Syntax: SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern;
Eg1: SELECT empName FROM Employee WHERE empName LIKE 'a%' --- selects employee names starting with a .
Eg2: SELECT empName FROM Employee WHERE empName LIKE '%a' --- selects employee names ending with a .
Eg3: SELECT empName FROM Employee WHERE empName LIKE '%ab%' --- selects employee names which has ab in their names .
Eg4: SELECT empName FROM Employee WHERE empName NOT LIKE 'b%' --- selects employee names which doesn't starts with b.

SQL Wildcards: -- can be used when searching for data in a database.
% -- percentage -- matches zero or more characters
_ -- underscore -- matches exactly one character
Eg: SELECT * FROM Persons WHERE FirstName LIKE '_la' --- this will return matching single character at begining.
[charlist] -- matches with list of characters
Eg: SELECT * FROM Persons WHERE LastName LIKE '[bsp]%'--- this will return LastNames starting with b or s or p.

IN Operator: -- allows you to specify multiple values in a WHERE clause.
Syntax: SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,...)
Eg: SELECT LastName FROM Persons WHERE LastName IN ('kareem', 'khan') -- this will select LastName from Persons who have last name as karee and khan.

BETWEEN Operator: -- BETWEEN operator is used in a WHERE clause to select a range of data between two values.
Syntax: SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2
Eg1: SELECT * FROM Persons WHERE LastName BETWEEN 'kareem' AND 'khan' ; -- Selects LastName between kareem and khan.
Eg2: SELECT * FROM Persons WHERE LastName NOT BETWEEN 'kareem' AND 'khan' ; -- Selects all LastName except kareem and khan.

Alias: You can give a table or a column another name by using an alias
Syntax: SELECT column_name(s) FROM table_name AS alias_name --- for tables Syntax: SELECT column_name AS alias_name FROM table_name --- for columns  

JOINS: -- are used to extract the data from 2 or more number of tables. While extracting data from different tables, each table will have kyes to relate each other. Primary Key is a column with unique value for each row.There are different types of joins

1. JOIN / INNER JOIN -- Return rows when there is at least one match in both tables
2. LEFT JOIN -- Return all rows from the left table, even if there are no matches in the right table
3. RIGHT JOIN -- Return all rows from the right table, even if there are no matches in the left table
4. FULL JOIN -- Return all rows from left and right tables when there is a match in one of the tables

UNION: -- UNION operator is used to combine the result-set of two or more SELECT statements.

Syntax: SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2

Eg: SELECT e_EuroName FROM European UNION SELECT e_INDIA FROM INDIAN --- returns only distinct values, it wont return duplicate values.

Column_name should of same data type and columns should be in same order in the tables on which we perform UNION operation.
Syntax: SELECT column_name(s) FROM table_name1 UNION ALL SELECT column_name(s) FROM table_name2

Eg: SELECT e_EuroName FROM European UNION ALL SELECT e_INDIA FROM INDIAN --- returns all values even if there are mutilple values with same value.  

CREATE: -- is used to create a table in a database.

Syntax: CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, .... )

Eg: CREATE TABLE employee ( EName varchar2(20), EmpID int(5), EmpAddr varchar20(30) )

SQL CONSTRAINTS: -- are used to limit the type of data that can go into a table. These constraints will be given while creating table or after creating tables.  
NOT NULL
UNIQUE KEY
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT -- are constraints

1. NOT NULL :- By default a table column can hold NULL values. So while creating a table specifying NOT NULL will make users wont accept NULL Values anymore
Eg: CREATE TABLE employee ( EName varchar2(20) NOT NULL, EmpID int(5) NOT NULL, EmpAddr varchar20(30) )

2. UNIQUE :- this constraint uniquely identifies each record in a database table.
UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.

Eg: CREATE TABLE employee ( EName varchar2(20) NOT NULL, EmpID int(5) NOT NULL UNIQUE, EmpAddr varchar20(30) )

Whenever a table has been created without unique constraint, then through ALTER command we can create UNIQUE constraint as follows:
 Eg: ALTER TABLE employee ADD UNIQUE (EmpID)


If you want to drop unique constraint in the table, then
Eg: ALTER TABLE employee DROP CONSTRAINT EmpID  

3. PRIMARY KEY :- uniquely identifies each record in a database table.
Primary keys should contain unique values.
A Primary key column cannot contain NULL values. Each table should have a primary key. and each table can have only one primary key.

Eg: CREATE TABLE persons ( P_Id int NOT NULL, L_name varchar(100) NOT NULL, F_name varchar(100), city varchar(100), PRIMARY_KEY(P_Id) );

If want to ALTER the table then
ALTER TABLE persons ADD PRIMARY KEY (P_Id);
If want to DROP the table then
ALTER TABLE persons DROP PRIMARY KEY;

4. FOREIGN KEY :- is one which points to a PRIMAY KEY in another table.

Eg: CREATE TABLE Orders (O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, PRIMARY KEY (O_Id), FOREIGN KEY (P_Id) REFERENCES Persons(P_Id));

If we want to ALTER the table
ALTER TABLE Orders ADD FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) ;

If we want to DROP the table
ALTER TABLE Orders DROP FOREIGN KEY fk_PerOrders;

5. CHECK :- is used to limit the value range that can be placed in a column.
If CHECK is defined on a single column, then it allows only certain values for this column.
If CHECK is defined on a table, it can limit the values in certain columns based on values in other columns in the row.

Eg: CREATE TABLE Persons ( P_Id int NOT NULL, L_name varchar(30) NOT NULL, F_name varchar(30), City varchar(30), CHECK(P_Id>0) ) ;

the above will accepts the input values in P_Id which should be greater than 0 (Zero).

If we want to ALTER the table
ALTER TABLE Persons ADD CHECK (P_Id>0) ;
If we want to DROP the table
ALTER TABLE Persons DROP CONSTRAINT check_persons;

6. DEFAULT :- is used to insert a default value into a column. The default value will be added to all the records in the table.

Eg: CREATE TABLE Persons
( P_Id int NOT NULL,
L_name varchar(30) NOT NULL,
F_name varchar(30),
city varchar(30) DEFAULT 'Bangalore' );

the above will create table Persons with city column for all persons as Bangalore.

If we want to ALTER the table
ALTER TABLE Persons ADD COLUMN City SET DEFAULT 'Bangalore';
If we want to DROP the table
ALTER TABLE Persons DROP City DEFAULT;


SQL ALTER COMMAND: is used to add/delete/modify the columns in an existing table.

the below command is used to ADD a new column DateOFBirth with Date as datatype.

Eg: ALTER TABLE Persons ADD DateOFBirth date;
the below command is used to MODIFY the datatype of the column

Eg: ALTER TABLE Persons ALTER COLUMN DateOFBirth Year;
the below is used to DROP the column

Eg: ALTER TABLE Persons DROP COLUMN DateOFBIrth;

AUTO INCREMENT : used to increment value in column automatically. By default it will increment from 1.

Eg: CREATE TABLE Persons
( P_Id int NOT NULL AUTO_INCREMENT,
L_name varchar(30) NOT NULL,
F_name varchar(30),
city varchar(30),
PRIMARY KEY(P_Id));

If we want to increment value other than 1 , say increment from 100

ALTER TABLE Persons AUTO_INCREMENT =100;

DATA TYPES IN SQL:- mostly there are 3 main types : text, number and Date/time types.

CHAR(size) -- Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is specified in parenthesis. Can store up to 255 characters

VARCHAR(size) --Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 characters. Note: If you put a greater value than 255 it will be converted to a TEXT type

INT(size) -- -2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum number of digits may be specified in parenthesis

DATE() -- A date. Format: YYYY-MM-DD


SQL FUNCTIONS: -- are the functions which returns a single value, calculated from values in a column.

The below are Aggregate functions:
 1. AVG() -- returns the average value.
2. COUNT() -- returns number of rows.
3.MAX() -- returns the largest value
4.MIN() -- returns the smallest value
5.SUM() --- returns the sum of all columns
6.FIRST() -- returns the first value
7.LAST() -- returns the last value

The below are Scalar functions:

1. UCASE() -- converts a field to uppercase
2. LCASE() -- converts a field to lowecase
3. LEN() -- returns the length of a text field
4. ROUND() -- round the numeric field to the number of decimals specified.
5. FORMAT() -- formats how a field is to be displayed.





JAVA Questions And Answers


Q) What is difference between Java and C++?
A) (i) Java does not support pointers. Pointers are inherently insecure and troublesome. Since pointers do not exist in Java. (ii) Java does not support operator overloading. (iii) Java does not perform any automatic type conversions that result in a loss of precision (iv) All the code in a Java program is encapsulated within one or more classes. Therefore, Java does not have global variables or global functions. (v) Java does not support multiple inheritance.
Java does not support destructors, but rather, add the finalize() function. (vi) Java does not have the delete operator. (vii) The << and >> are not overloaded for I/O operations

Q) Opps concepts
Polymorphism
Ability to take more than one form, in java we achieve this using Method Overloading (compile time polymorphism), Method overriding (runtime polymorphism)

Inheritance
Is the process by which one object acquires the properties of another object. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses.
           
Encapsulation
Wrapping of data and function into a single unit called encapsulation. Ex:- all java programs.
(Or)
Nothing but data hiding, like the variables declared under private of a particular class are accessed only in that class and cannot access in any other the class. Or Hiding the information from others is called as Encapsulation. Or Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse.

Abstraction
Nothing but representing the essential futures without including background details.

Dynamicbinding
            Code associated with a given procedural call is not known until the time of the call at runtime. Dynamic binding is nothing but late binding.

Q) class & object?
    class   à class is a blue print of an object
    Object  à instance of class.

Q) Object creation?
     Object is constructed either on a memory heap or on a stack.
Memory heap
Generally the objects are created using the
new keyword. Some heap memory is allocated to this newly created object. This memory remains allocated throughout the life cycle of the object. When the object is no more referred, the memory allocated to the object is eligible to be back on the heap.
Stack
During method calls, objects are created for method arguments and method variables. These objects are created on stack.

Q) System.out.println()
     à println() is a methd of java.io.printWriter.
     à “out” is an instance variable of java.lang.System class.

Q) Transient & volatile
Transient --> The transient modifier applies to variables only, the object are variable will not persist. Transient variables are not serialized.
    Volatile --> value will be changed unexpectedly by the other part of the program, "it tells the compiler a variable    may change asynchronously due to threads"



Q) Access Specifiers & Access modifiers?
Access Specifiers à A.S gives access privileges to outside of application (or) others, they are Public, Protected, Private, Defaults.
Access Modifiers  à A.M which gives additional meaning to data, methods and classes, final cannot be modified at any point of time.


Private
Public
Protected
No modifier
Same class
No
Yes
Yes
Yes
Same package Subclass
No
Yes
Yes
Yes
Same package non-subclass
No
Yes
Yes
Yes
Different package subclass
No
Yes
Yes
No
Different package non-subclass
No
Yes
No
No

Q) Default Values
           
long    
-2^63 to 2^63 –1 à 0L
double
0.0d
Int
-2^31 to 2^31 –1 à 0
float
0.0f
Short
-2^15 to 2^15 –1 à 0
Boolean
false
Byte
-2^7 to 2^7 –1     à 0
char
0 to 2^7 –1 à null character (or) ‘\u 0000’
    
Q) Byte code  & JIT compiler & JVM & JRE & JDK
à Byte code is a highly optimized set of instructions. JVM is an interpreter for byte code. Translating a java   program into byte code helps makes it much easier to run a program in a wide variety of environment.
à JVM is an interpreter for byte code
à JIT (Just In Time) is a part of JVM, it compiles byte code into executable code in real time, will increase the performance of the interpretations.
à JRE is an implementation of the Java Virtual Machine, which actually executes Java programs.
à JDK is bundle of software that you can use to develop Java based software, Tools provided by JDK is
(i) javac – compiler        (ii) java – interpretor       (iii) jdb – debugger        (iv) javap - Disassembles
(v) appletviewer – Applets          (vi) javadoc - documentation generator   (vii) javah - 'C' header file generator

Q) Wrapper classes
Primitive data types can be converted into objects by using wrapper classes. These are java.lang.package.

Q) Does Java pass method arguments by value or by reference?
Java passes all arguments by value, not by reference

Q) Arguments & Parameters
While defining method, variable passed in the method are called parameters. While using those methods, values passed to those variables are called arguments.

Q) Public static void main (String [] args)
à We can overLoad the main() method.
à What if the main method is declared as “Private”?
    The program compiles properly but at runtime it will give "Main method not public." Message
à What if the static modifier is removed from the signature of the main method?
    Program compiles. But at runtime throws an error "NoSuchMethodError".
à We can write “static public void” instead of “public static void” but not “public void static”.
à Protected static void main(), static void main(), private static void main() are also valid.
à If I do not provide the String array as the argument to the method?
    Program compiles but throws a runtime error "NoSuchMethodError".
à If no arguments on the command line, String array of Main method will be empty or null?
    It is empty. But not null.
à Variables can have the same name as a method or a class

Q) Can an application have multiple classes having main() method?
A) Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.

Q) Can I have multiple main methods in the same class?
A) No the program fails to compile. The compiler says that the main method is already defined in the class.

Q) Constructor
            The automatic initialization is performed through the constructor, constructor has same name has class name. Constructor has no return type not even void. We can pass the parameters to the constructor. this() is used to invoke a constructor of the same class. Super() is used to invoke a super class constructor. Constructor is called immediately after the object is created before the new operator completes.

à Constructor can use the access modifiers public, protected, private or have no access modifier
à Constructor can not use the modifiers abstract, static, final, native, synchronized or strictfp
à Constructor can be overloaded, we cannot override.
à You cannot use this() and Super() in the same constructor.

Class A(
A(){
     System.out.println(“hello”);
}}

Class B extends A {
B(){
     System.out.println(“friend”);
}}

Class print {
Public static void main (String args []){
B b = new B();
}
o/p:- hello friend


Q) Garbage collection
G.C is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program cann't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use, calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. Garbage collection is a low-priority thread.

G.C is a low priority thread in java, G.C cannot be forced explicitly. JVM may do garbage collection if it is running short of memory. The call System.gc() does NOT force the garbage collection but only suggests that the JVM may make an effort to do garbage collection.


Q) How an object becomes eligible for Garbage Collection?
A) An object is eligible for garbage collection when no object refers to it, An object also becomes eligible when its reference is set to null. The objects referred by method variables or local variables are eligible for garbage collection when they go out of scope.
Integer i = new Integer(7);
i =
null;
Q) Final, Finally, Finalize
Final: - When we declare a sub class a final the compiler will give error as “cannot subclass final class” Final to prevent inheritance and method overriding. Once to declare a variable as final it cannot occupy memory per instance basis.
     à  Final class cannot have static methods   
     à  Final class cannot have abstract methods (Because of final class never allows any class to inherit it)
     à  Final class can have a final method.

Finally: - Finally create a block of code that will be executed after try catch block has completed. Finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also execute.
                       
    Using System.exit() in try block will not allow finally code to execute

Finalize: - some times an object need to perform some actions when it is going to destroy, if an object holding some non-java resource such as file handle (or) window character font, these resources are freed before the object is going to destroy.

Q) Can we declare abstract method in final class?
A) It indicates an error to declare abstract method in final class. Because of final class never allows any class to inherit it.

Q) Can we declare final method in abstract class?
A) If a method is defined as final then we can’t provide the reimplementation for that final method in it’s derived classes i.e overriding is not possible for that method. We can declare final method in abstract class suppose of it is abstract too, then there is no used to declare like that.

Q) Superclass & Subclass
                A super class is a class that is inherited whereas subclass is a class that does the inheriting

Q) How will u implement 1) polymorphism 2) multiple inheritance 3) multilevel inheritance in java?
A) Polymorphism           – overloading and overriding
    Multiple inheritances  – interfaces.
    Multilevel inheritance – extending class.

Q) Overloading & Overriding?
Overloading (Compile time polymorphism)
 Define two or more methods within the same class (or) subclass that share the same name and their number of parameter, order of parameter & return type are different then the methods are said to be overloaded.
· Overloaded methods do not have any restrictions on what return type of Method (Return type are different) (or) exceptions can be thrown. That is something to worry about with overriding.
· Overloading is used while implementing several methods that implement similar behavior but for different data types.

Overriding (Runtime polymorphism)
When a method in a subclass has the same name, return type & parameters as the method in the super class then the method in the subclass is override the method in the super class.

à The access modifier for the overriding method may not be more restrictive than the access modifier of the superclass method.

· If the superclass method is public, the overriding method must be public.
· If the superclass method is protected, the overriding method may be protected or public.
· If the superclass method is package, the overriding method may be packagage, protected, or public.
· If the superclass methods is private, it is not inherited and overriding is not an issue.
· Methods declared as final cannot be overridden.

à The throws clause of the overriding method may only include exceptions that can be thrown by the superclass method, including its subclasses.
  
à Only member method can be overriden, not member variable     
            class Parent{
    int i = 0;
    void amethod(){
                System.out.println("in Parent");
                }
             }         
class Child extends Parent{
    int i = 10;
    void amethod(){
                System.out.println("in Child");
    }
}          
class Test{
public static void main(String[] args){
Parent p = new Child();
Child  c = new Child();
System.out.print("i="+p.i+" ");
p.amethod ();
System.out.print("i="+c.i+" ");
c.amethod();
}
}
o/p: - i=0 in Child     i=10 in Child

Q) Final variable
            Once to declare a variable as final it cannot occupy memory per instance basis.

Q) Static block
            Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to  the main method the static block will execute.

Q) Static variable & Static method
Static variables & methods are instantiated only once per class. In other words they are class variables,   not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class.
Static methods can be referenced with the name of the class. It may not access the instance variables of that class, only its static variables. Further it may not invoke instance (non-static) methods of that class unless it provides them with some object.

à When a member is declared a static it can be accessed before any object of its class are created.
à Instance variables declared as static are essentially global variables.
à If you do not specify an initial value to an instance & Static variable a default value will be assigned   automatically.
à Methods declared as static have some restrictions they can access only static data, they can only call other            static data, they cannot refer this or super.
à Static methods cant be overriden to non-static methods.
à Static methods is called by the static methods only, an ordinary method can call the static methods, but static methods cannot call ordinary methods.
à Static methods are implicitly "final", because overriding is only done based on the type of the objects
à They cannot refer “this” are “super” in any way.

Q) Class variable & Instance variable  & Instance methods  & class methods
Instance variable à variables defined inside a class are called instance variables with multiple instance of class, each instance has a variable stored in separate memory location.

Class variables à you want a variable to be common to all classes then we crate class variables. To create a class variable put the “static” keyword before the variable name.

Class methods à we create class methods to allow us to call a method without creating instance of the class. To declare a class method use the “static” key word .

Instance methods à we define a method in a class, in order to use that methods we need to first create objects of the class.

Q) Static methods cannot access instance variables why?
 Static methods can be invoked before the object is created; Instance variables are created only when the new object is created. Since there is no possibility to the static method to access the instance variables. Instance variables are called called as non-static variables.

Q) String & StringBuffer
                String is a fixed length of sequence of characters, String is immutable.
               
                StringBuffer represent growable and writeable character sequence, StringBuffer is mutable which means that its value can be changed. It allocates room for 16-addition character space when no specific length is specified. Java.lang.StringBuffer is also a final class hence it cannot be sub classed. StringBuffer cannot be overridden the equals() method.

Q) Conversions
   String to Int Conversion: -
   int I   = integer.valueOf(“24”).intValue();
                           int x  = integer.parseInt(“433”);
                           float f = float.valueOf(23.9).floatValue();
           
    Int to String Conversion :-
                          String arg = String.valueOf(10);

Q) Super()
            Super() always calling the constructor of immediate super class, super() must always be the first statements executed inside a subclass constructor.

Q) What are different types of inner classes?
A) Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. e.g., outer.inner. Top-level inner classes implicitly have access only to static variables. There can also be inner interfaces. All of these are of the nested top-level variety.

Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a more publicly available interface. Because local classes are not members the modifiers public,  protected, private and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.

à Inner class inside method cannot have static members or blocks

Q) Which circumstances you use Abstract Class & Interface?
--> If you need to change your design make it an interface.
--> Abstract class provide some default behaviour, A.C are excellent candidates inside of application framework. A.C allow single inheritance model, which should be very faster.

Q) Abstract Class
Any class that contain one are more abstract methods must also be declared as an abstract, there can be no object of an abstract class, we cannot directly instantiate the abstract classes. A.C can contain concrete methods.
àAny sub class of an Abstract class must either implement all the abstract methods in the super class or be declared itself as Abstract.
à Compile time error occur if an attempt to create an instance of an Abstract class.
à You cannot declare “abstract constructor” and “abstract static method”.
à An “abstract method” also declared private, native, final, synchronized, strictfp, protected.
à Abstract class can have static, final method (but there is no use).
à Abstract class have visibility public, private, protected.
à By default the methods & variables will take the access modifiers is <default>, which is accessibility as package.
à An abstract method declared in a non-abstract class.
à An abstract class can have instance methods that implement a default behavior.
à A class can be declared abstract even if it does not actually have any abstract methods. Declaring such a class abstract indicates that the implementation is somehow incomplete and is meant to serve as a super class for one or more subclasses that will complete the implementation.
à A class with an abstract method. Again note that the class itself is declared abstract, otherwise a compile time error would have occurred.

Abstract class A{
                Public abstract callme();
                Void callmetoo(){
                }
}

class B extends A(
      void callme(){
                }
}

class AbstractDemo{
public static void main(string args[]){
                B b = new B();
                b.callme();
                b.callmetoo();
}
}
 
Q) When we use Abstract class?
A) Let us take the behaviour of animals, animals are capable of doing different things like flying, digging,
Walking. But these are some common operations performed by all animals, but in a different way as well. When an operation is performed in a different way it is a good candidate for an abstract method.

Public Abstarctclass Animal{
  Public void eat(food food)  {
  }
  public void sleep(int hours) {
  }
  public abstract void makeNoise()
}

public Dog extends Animal
{
   public void makeNoise()  {
                System.out.println(“Bark! Bark”);
    }
}

public Cow extends Animal
{
   public void makeNoise() {
                System.out.println(“moo! moo”);
    }
}
 
Q) Interface
            Interface is similar to class but they lack instance variable, their methods are declared with out any body. Interfaces are designed to support dynamic method resolution at run time. All methods in interface are implicitly
abstract, even if the abstract modifier is omitted. Interface methods have no implementation;

Interfaces are useful for?
a) Declaring methods that one or more classes are expected to implement
b) Capturing similarities between unrelated classes without forcing a class relationship.
c) Determining an object's programming interface without revealing the actual body of the class.

Why Interfaces?
“ one interface multiple methods “ signifies the polymorphism concept.

Interface has visibility public.
Interface can be extended & implemented.
An interface body may contain constant declarations, abstract method declarations, inner classes and inner interfaces.
All methods of an interface are implicitly Abstract, Public, even if the public modifier is omitted.
An interface methods cannot be declared protected, private, strictfp, native or synchronized.
All Variables are implicitly final, public, static fields.
A compile time error occurs if an interface has a simple name the same as any of it's enclosing classes or interfaces.
An Interface can only declare constants and instance methods, but cannot implement default behavior.
top-level interfaces may only be declared public, inner interfaces may be declared private and protected but only if they are defined in a class.

A class can only extend one other class.
A class may implements more than one interface.
Interface can extend more than one interface.

Interface A
{
            final static float pi = 3.14f;
}

class B implements A
{
            public float compute(float x, float y) {
                        return(x*y);
            }
}

class test{
public static void main(String args[])
{
            A a = new B();
            a.compute();
}
}
           

Q) Diff Interface & Abstract Class?
à A.C may have some executable methods and methods left unimplemented. Interface contains no implementation code.
à An A.C can have nonabstract methods. All methods of an Interface are abstract.
à An A.C can have instance variables. An Interface cannot.
à An A.C must have subclasses whereas interface can't have subclasses
à An A.C can define constructor. An Interface cannot.
à An A.C can have any visibility: public, private, protected. An Interface visibility must be public (or) none.
à An A.C can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior.

Q) What is the difference between Interface and class?
à A class has instance variable and an Interface has no instance variables.
à Objects can be created for classes where as objects cannot be created for interfaces.
à All methods defined inside class are concrete. Methods declared inside interface are without any body.

Q) What is the difference between Abstract class and Class?
à Classes are fully defined. Abstract classes are not fully defined (incomplete class)
à Objects can be created for classes, there can be no objects of an abstract class.

Q) What are some alternatives to inheritance?
A) Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).

Q) Serializable & Externalizable
Serializable  --> is an interface that extends serializable interface and sends data into streams in compressed format. It has 2 methods writeExternal(objectOutput out), readExternal(objectInput in).

Externalizable à is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)

Q) Internalisation & Localization
                Internalisation -- Making a programme to flexible to run in any locale called internalisation.
                Localization    -- Making a programme to flexible to run in a specific locale called Localization.

Q) Serialization
                Serialization is the process of writing the state of the object to a byte stream, this is useful when ever you want to save the state of your programme to a persistence storage area.

Q) Synchronization
 Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. (Or) When 2 are more threads need to access the shared resources they need to some way ensure that the resources will be used by only one thread at a time. This process which is achieved is called synchronization.

(i) Ex: - Synchronizing a function:
public synchronized void Method1 () {
}

(i) Ex: - Synchronizing a block of code inside a function:
public myFunction (){
 synchronized (this) {
     }
}

(iii) Ex: - public Synchronized void main(String args[])
      But this is not the right approach because it means servlet can handle one request at a time.

(iv) Ex: - public Synchronized void service()
     Servlet handle one request at a time in a serialized manner

Q) Different level of locking using Synchronization?
A) Class level, Object level, Method level, Block level

Q) Monitor
            A monitor is a mutex, once a thread enter a monitor, all other threads must wait until that thread exist the monitor.

Q) Diff = = and  .equals()?
A)   ==          à Compare object references whether they refer to the sane instance are not.
      equals () à method compare the characters in the string object.

   StringBuffer sb1 = new StringBuffer("Amit");
   StringBuffer sb2= new StringBuffer("Amit");
   String s1 = "Amit";
   String s2 = "Amit";
   String s3 = new String("abcd");
   String s4 = new String("abcd");
   String ss1 = "Amit";
           
(sb1==sb2); à F
(s1.equals(s2)); à T
(sb1.equals(sb2)); à F
((s1==s2)); à T
(sb1.equals(ss1)); à F
(s3.equals(s4)); à T

((s3==s4)); à F

    String s1 = "abc";
    String s2 = new String("abc");
    s1 == s2 à F
    s1.equals(s2)) à T
   
Q) Marker Interfaces (or) Tagged Interfaces :-
An Interface with no methods. Is called marker Interfaces, eg. Serializable, SingleThread Model, Cloneable.

Q) URL Encoding & URL Decoding
            URL Encoding is the method of replacing all the spaces and other extra characters into their corresponding Hex Characters and URL Decoding is the reverse process converting all Hex Characters back their normal form.

Q) URL & URLConnection

URL is to identify a resource in a network, is only used to read something from the network.
URL url = new URL(protocol name, host name, port, url specifier)

URLConnection can establish communication between two programs in the network.
                URL hp = new URL(“www.yahoo.com”);
                URLConnection con = hp.openConnection();

Q) Runtime class               
                Runtime class encapsulate the run-time environment. You cannot instantiate a Runtime object. You can get a reference to the current Runtime object by calling the static method Runtime.getRuntime()

Runtime r = Runtime.getRuntime()
Long mem1;
Mem1 = r.freeMemory();
Mem1 = r.totalMemory();


Q) Execute other programs
          You can use java to execute other heavy weight process on your multi tasking operating system, several form of exec() method allow you to name the programme you want to run.
                Runtime r = Runtime.getRuntime();
                Process p = null;
                Try{
                                p = r.exce(“notepad”);
                                p.waiFor()
                     }

Q) System class  
                System class hold a collection of static methods and variables. The standard input, output, error output of the java runtime are stored in the in, out, err variables.

Q) Native Methods
                Native methods are used to call subroutine that is written in a language other than java, this subroutine exist as executable code for the CPU.

Q) Cloneable Interface
          Any class that implements the cloneable interface can be cloned, this interface defines no methods. It is used to indicate that a class allow a bit wise copy of an object to be made.

Q) Clone
          Generate a duplicate copy of the object on which it is called. Cloning is a dangerous action.

Q) Comparable Interface
                Classes that implements comparable contain objects that can be compared in some meaningful manner. This interface having one method compare the invoking object with the object. For sorting comparable interface will be used.
Ex:- int compareTo(Object obj)
               
Q) Class
          Class encapsulate the run-time state of an object or interface. Methods in this class are

static Class forName(String name) throws ClassNotFoundException
getClass()
getClassLoader()
getConstructor()
getField()
getDeclaredFields()
getMethods()
getDeclearedMethods()
getInterface()
getSuperClass()

Q) java.jlang.Reflect (package)
                Reflection is the ability of software to analyse it self, to obtain information about the field, constructor, methods & modifier of class. You need this information to build software tools that enables you to work with java beans components.

Q) InstanceOf
      Instanceof means by which your program can obtain run time type
information about an object.
Ex:- A a = new A();
       a.instanceOf A;
 
Q) Java pass arguments by value are by reference?
A) By value
 
Q) Java lack pointers how do I implements classic pointer structures like 
linked list?
A) Using object reference.
 

Q) Bin & Lib in jdk?
Bin contains all tools such as javac, appletviewer and awt tool.
Lib contains API and all packages.