MY mENU


Thursday 9 February 2012

Local variables in java


A variable declared inside a Method without any keyword is called as Local Variable.

- We have to initialize the local variable when the time of declaring the variable.
- Without initialization, if we call it, we get an error.
JVM doesn't initialize the Local Variable with Default Values.
Local Variable can't be static.

using package members


The types (Classes and Interfaces) that comprise a Package are known as the Package Members.

To use a public Package Member from outside its Package, you must do one of the followings :

- Refer to the member by its fully qualified name
- Import the package member
- Import the member's entire package

Refer to the member by its fully qualified name : However, if you are trying to use a member from a different package and that package has not been imported, you must use the member's fully qualified name, which includes the package name.

Example : bank.Icici a = new bank.Icici();

Import the package member : To import a specific member into the current Java Class, put an import statement at the beginning of the program before any type definitions, if there is any package statement in that Java Class write import statement after that package statement.

Example :
import bank.Icici;
Class Account
{
-----
-----
}

Import the member's entire package : To import all the types contained in a particular Package, use the import statement with the asterisk * .

Example :
import bank.*;
Class Account
{
-----
-----
}

Advantages of InnerClass


There are several reasons for using Nested Classes(InnerClass) :

- It is a way of logically grouping classes that are only used in one place.
- It increases encapsulation.
- Nested classes can lead to more readable and maintainable code.

Logical grouping of classes : If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together.

Increased encapsulation : Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.

More readable, Maintainable code : Nesting small classes within top-level classes places the code closer to where it is used.

Can we access Private members of superclass in sub class?


No, A SubClass does not inherit the Private Members of its SuperClass.

But indirectly we can, how means see bellow :

- If the SuperClass has public or protected methods for accessing its Private Fields, these we can also use in SubClass.

- A Nested Class has access to all the Private Members (fields and methods) of its enclosing Class. Therefore, a public or protected Nested Class inherited by our SubClass has indirect access to all of the Private members of the SuperClass.

Innerclass and Outerclas

Accessing Innerclass and Outer Class Members:


Inner class member are not avaiable outside of the class.But you can access outer class member inside the inner class.

if your member variable are same in inner and outer class then use this keyword with corresponding class name.




We can use all the modifiers for Inner Classes. For example, we can use the access specifiers — private, public, and protected — to restrict access to Inner Classes, just as we do to class members (methods and variables).


see the example given below

public class InnerClassTest {

private int x;
public class Inner{

private int y;
private int x = 5;
public void innerMethod(){
System.out.println("y is " + y);
System.out.println("x is " + this.x);
System.out.println("x is " + InnerClassTest.this.x);
}
}

public void outerMethod(){
// System.out.println("y is " + y);//wrong bcoz y is a member of inner class
}
public static void main(String arg[]){
InnerClassTest ic = new InnerClassTest();

InnerClassTest.Inner in = ic.new Inner();
in.innerMethod();
}
}

Super() Example



Super() Example:  In Java Programming The first statement of a constructer is Super();if u don't call forcefully(explicitly).


Ex:
Public class ConstructerClass{
ConstructerClass(){
super();
}
}

In the above class when you don't write The super() in the constructerClass() then at the time of compilation a default super() call will be add by the compiler.Which is nothing but the constructer of Object class.
 .
Ex2:
public class A{
A()  //constructer defined by user
{
}
}
public class B extends A{
B(int x){
//here the first call is to super class default constructer i.e super()
}
}
when you create "new B(5)" then it will compile and run fine because there is a default constructer (written by us )is present .
Ex3:

public class A{
//no constructer defined by us
}
public class B extends A{
B(int x){
//here the first call is to super class default constructer i.e super()
}
}
by creating "new B(5)"
this also compiles fine because implicitly there is a default constructer
Ex4:

public class A{
A(String s){
}
}
public class B extends A{
B(int x){
//here the first call is to super class default constructer i.e super()
}
}
in this case by creating "new B(5)" we will get compilation error because there is no implicit or explicit default constructor called by B's constructer .
So to compile and run successfully u have to write a default constructer in class A. As


EX.5
public class A{
A(){
}

A(String s){
}
}
public class B extends A{
B(int x){
//here the first call is to super class default constructer i.e super()
}
}
Important note:
A compiler write a default constructer for you if you dont write any constructer ; if u write an arguemented constructer then compile will not write a constructer for you . so be care full.

Singleton class in Java

Java has several design patterns Singleton Pattern being the most commonly used. Java Singleton pattern belongs to the family of design patterns, that govern the instantiation process. This design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JVM.

The class’s default constructor is made private, which prevents the direct instantiation of the object by others (Other Classes). A static modifier is applied to the instance method that returns the object as it then makes this method a class level method that can be accessed without creating an bject.

One such scenario where it might prove useful is when we develop the help
Module in a project. Java Help is an extensible, platform-independent help system that enables authors and developers to incorporate online help into applications.

Singletons can be used to create a Connection Pool. If programmers create a new connection object in every class that requires it, then its clear waste of resources. In this scenario by using a singleton connection class we can maintain a single connection object which can be used throughout the application.

Implementing Singleton Pattern

To implement this design pattern we need to consider the following 4 steps:

Step 1: Provide a default Private constructor


public class SingletonObjectDemo {

// Note that the constructor is private
private SingletonObjectDemo() {
// Optional Code
}
}


Step 2: Create a Method for getting the reference to the Singleton Object

public class SingletonObjectDemo {

private static SingletonObject singletonObject;
// Note that the constructor is private
private SingletonObjectDemo() {
// Optional Code
}
public static SingletonObjectDemo getSingletonObject() {
if (singletonObject == null) {
singletonObject = new SingletonObjectDemo();
}
return singletonObject;
}
}




We write a public static getter or access method to get the instance of the Singleton Object at runtime. First time the object is created inside this method as it is null. Subsequent calls to this method returns the same object created as the object is globally declared (private) and the hence the same referenced object is returned.

Step 3: Make the Access method Synchronized to prevent Thread Problems.

public static synchronized SingletonObjectDemo getSingletonObject()

It could happen that the access method may be called twice from 2 different classes at the same time and hence more than one object being created. This could violate the design patter principle. In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration

Step 4: Override the Object clone method to prevent cloning

We can still be able to create a copy of the Object by cloning it using the Object’s clone method. This can be done as shown below

SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();

This again violates the Singleton Design Pattern's objective. So to deal with this we need to override the Object’s clone method which throws a CloneNotSupportedException exception.

public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}

The below program shows the final Implementation of Singleton Design Pattern in java, by using all the 4 steps mentioned above.


class SingletonClass {

private static SingletonClass singletonObject;
/** A private Constructor prevents any other class from instantiating. */
private SingletonClass() {
// Optional Code
}
public static synchronized SingletonClass getSingletonObject() {
if (singletonObject == null) {
singletonObject = new SingletonClass();
}
return singletonObject;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}

public class SingletonObjectDemo {

public static void main(String args[]) {
//SingletonClass obj = new SingletonClass();
//Compilation error not allowed
SingletonClass obj = SingletonClass.getSingletonObject();
// Your Business Logic
System.out.println("Singleton object obtained");
}
}

Statements in Java


Statements are equivalent to sentences in Natural Languages. A Statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon (.

1. Assignment expressions
2. Any use of ++ or --
3. Method invocations
4. Object creation expressions

Such Statements are called Expression Statements.

Examples :

a = 8933.234;  assignment statement
a++;              increment statement
System.out.println("Hello JAVA !");       method invocation statement
Account acc = new Account();           object creation statement

- There are two other kinds of Statements :

1. Declaration Statements : A Declaration Statement declares a variable.
2. Control Flow Statements : Control Flow Statements regulate the order in which Statements get executed.

Static Import Statement


In some situations where you need frequent access to static final fields (constants) and static methods from one or two classes. Prefixing the name of these classes over and over can result in cluttered code.

The static import statement gives you a way to import the static constants and static methods that you want to use so that you do not need to prefix the name of their class.

The java.lang.Math class defines the PI constant and many static methods, as bellow

public static final double PI 3.141592653589793
public static double cos(double a)

You can use the static import statement to import the static members of java.lang.Math so that you don't need to prefix the class name, Math. Once they have been imported, thestatic members can be used without qualification.

Example
 :

import static java.lang.Math.*;
Class Trigonometry {
double r = cos(PI * theta);
------
}

Switch Statement

The Switch Statement allows for any number of possible execution paths.

An If-then-Else Statement can be used to make decisions based on ranges of values or conditions, whereas a Switch Statement can make decisions based only on a single integer or enumerated value.

- A Switch works with the byte, short, char, and int primitive data types. It also works with enumerated types and a few special classes that "wrap" certain primitive types: Character, Byte, Short, and Integer.

Example :

class SwitchDemo {
public static void main(String[] args) {

int day = 3;
switch (day ) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
case 4: System.out.println("Thursday"); break;
case 5: System.out.println("Friday"); break;
case 6: System.out.println("Saturday"); break;
case 7: System.out.println("Sunday"); break;
default: System.out.println("Invalid day .");break;
}
}
}

In this case, "Wednesday" is printed to standard output.

- The body of a Switch Statement is known as a Switch Block. Any statement immediately contained by the Switch Block may be labelled with one or more case or default labels. TheSwitch Statement evaluates its expression and executes the appropriate case.

- The break statement after each case terminates the enclosing Switch Statement. Control flow continues with the first statement following the Switch Block. The break statementsare necessary because without them, case statements fall through; that is, without an explicit break, control will flow sequentially through subsequent case statements.

- The default section handles all values that aren't explicitly handled by one of the case sections.

Note: 

int day = 8;
switch (day ) {
    default: System.out.println("Invalid day .");
case 1: System.out.println("Monday");
case 2: System.out.println("Tuesday");
case 3: System.out.println("Wednesday");
case 4: System.out.println("Thursday");
case 5: System.out.println("Friday");
case 6: System.out.println("Saturday");
case 7: System.out.println("Sunday");

}
}

see the above example to there switch condition false and it terminates default case and there is no Break statement and it defined default at the top of the cases so it executes all the cases as output.

Output:

Invalid day .
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

Break Statement in Java


The Break Statement has two forms :

1. Labelled
2. Unlabeled

Unlabeled : You can use an Unlabeled break to terminate a for, while, or do-while loop. An Unlabeled Break Statement terminates the innermost switch, for, while, or do-while statement

Example :

class BreakDemo {
public static void main(String[] args) {

int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076,
2000, 8, 622, 127 };
int searchfor = 12;

int i;
boolean foundIt = false;

for (i = 0; i < arrayOfInts.length; i++) {
if (arrayOfInts[i] == searchfor) {
foundIt = true;
break;
}
}

if (foundIt) {
System.out.println("Found " + searchfor
+ " at index " + i);
} else {
System.out.println(searchfor
+ " not in the array");
}
}
}

This program searches for the number 12 in an array. The break statement, shown in boldface, terminates the for loop when that value is found. Control flow then transfers to the print statement at the end of the program. This program's output is:

Found 12 at index 4

Labeled : A Labeled break terminates an outer statement.

Example :

class BreakWithLabelDemo {
public static void main(String[] args) {

int[][] arrayOfInts = { { 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;

int i;
int j = 0;
boolean foundIt = false;

search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}

if (foundIt) {
System.out.println("Found " + searchfor +
" at " + i + ", " + j);
} else {
System.out.println(searchfor
+ " not in the array");
}
}
}

This is the output of the program.

Found 12 at 1, 0

- The following program, BreakWithLabelDemo, is similar to the previous program, but uses nested for loops to search for a value in a two-dimensional array. When the value is found, aLabelled Break terminates the outer for loop (labelled "search").

- The Break Statement terminates the Labelled Statement; it does not transfer the flow of control to the Label. Control flow is transferred to the statement immediately following theLabelled (terminated) statement.

Return Statement in Java


The last of the Branching Statements is the return statement. The return statement exits from the current method, and control flow returns to where the method was invoked.

The return statement has two forms :

1. Returns a value
2. Doesn't returns a value

Returns a value : To return a value, simply put the value (or an expression that calculates the value) after the return keywordThe data type of the returned value must match the type of the method's declared return value.

return ++count;

Doesn't returns a value : When a method is declared void, use the form of return that doesn't return a value.

return;

eg:


 int Java(int x,int y)
{f
int c=x+y;
return c;
}
In the above Eg: the method Java is with a int datatype.so it must contain a return statement. i.e it returns a integer value.

Eg: void Java()
{
System.out.println("This is java");
}

continue statement in java


The Continue Statement skips the current iteration of a for, while, or do-while loop.

Unlabeled : The Unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop.

Example :

class ContinueDemo {
public static void main(String[] args) {

String searchMe = "peter piper picked a peck of pickled peppers";
int max = searchMe.length();
int numPs = 0;

for (int i = 0; i < max; i++) {
//interested only in p's
if (searchMe.charAt(i) != 'p')
continue;

//process p's
numPs++;
}
System.out.println("Found " + numPs + " p's in the string.");
}
}


Here is the output of this program:

Found 9 p's in the string.

- The above program, ContinueDemo , steps through a String, counting the occurences of the letter "p". If the current character is not a p, the Continue Statement skips the rest of the loop and proceeds to the next character. If it is a "p", the program increments the letter counts.


To see this effect more clearly, try removing the Continue Statement and recompiling. When you run the program again, the count will be wrong, saying that it found 35 p's instead of 9.

Labeled
 : A Labeled Continue Statement skips the current iteration of an outer loop marked with the given label.

Example :

class ContinueWithLabelDemo {
public static void main(String[] args) {

String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;

int max = searchMe.length() - substring.length();

test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++)
!= substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" :
"Didn't find it");
}
}


Here is the output from this program.

Found it

- The above example program, ContinueWithLabelDemo, uses nested loops to search for a substring within another string. Two nested loops are required: one to iterate over the substring and one to iterate over the string being searched. The following program, ContinueWithLabelDemo, uses the labeled form of Continue to skip an iteration in the outer loop.

Instance Variable in java

An Instance Variable is a variable whose separate copy is available every object.
- So if the Instance Variable value is modified in one object, it will not effect the value of variable in other objects.
Instance Variables are created in Heap Area of JVM.
- We can call the Instance Variables using Object Reference only

Example : Class A {
int p;
}
Class B {
A a = new A();
a.p = 10;
}




A Static Variable is a variable whose single copy in memory is shared by all the Objects.
- So if any modification to Static Variable will effect the values of variables in all the objects.
- Static Variables are created in Method Area of JVM.
- we can call the Static Variables using Class name itself and Object Refernce also.


Example : Class A { 
static int p; 
}
Class B { 
A.p = 10; 
}

print triangle in java

import java.io.*;
class Triangle {
public static void main(String args[])throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Entert any no");
int re=Integer.parseInt(br.readLine());
int a[]=new int[re+1];
int b[]=new int[re+1];
a[0]=1;
for(int i=0;i<re;i++) {
for(int j=1;j<=i+1;j++) {
if(i==0)
break;
else a[j]=b[j-1]+b[j];
}
for(int j=0;j<a.length;j++) b[j]=a[j];
for(int m=re;m>i;m--)System.out.print(" ");
for(int j=0;j<a.length;j++) {
if(a[j]==0) continue;
System.out.print(a[j]+" ");
}
System.out.println();
}
}
}

programme on String in Java

public boolean str(String s1,String s2)
{
char c=s1.charAt(s1.length()-1);
char c1=s2.charAt(0);
int count=0;
for(int i=0;i<s2.length();i++)
{
if(c1==c+1)
{
count++;
if(i<s2.length()-1)
{
c=s2.charAt(i);
c1=s2.charAt(i+1);
}
}

}
if(count==s2.length())
return true;
else
return false;


}

Object Creation in Java

we create objects in four ways...
1)By using new operator.
2)Factory methods.
3)class.forName();
4)cloning mechanism.

Serialization in Java


Serialization is the process of converting a set of object instances that contain references to each other into a linear stream of bytes, which can then be sent through a socket, stored to a file, or simply manipulated as a stream of data. 

Serialization is the mechanism used by RMI to pass objects between JVMs, either as arguments in a method invocation from a Client to a Server or as return values from a method invocation. In the first section of this book, There are three exceptions in which Serialization doesnot necessarily read and write to the stream.

These are :

1. Serialization ignores static fields, because they are not part of any particular object's state.
2. Base class fields are only handled if the base class itself is serializable.
3. Transient fields. There are four basic things you must do when you are making a class serializable.  They are
a. Implement the Serializable interface.
b. Make sure that instance-level, locally defined state is serialized properly.
c. Make sure that superclass state is serialized properly.
d. Override equals( )and hashCode( ).

It is possible to have control over Serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the Serialization process.

public static void main() in java



public : The method can be accessed outside the class/package.

Static : You need not have an instance of the class to access the method.

Void : Your application need not return a value as the JVM launcher would return the value when it exits.

Main() : This is the entry point for the application.

Properties of  main() method:



- It must be marked static.

- It must have void return type.

- It must have a single String array argument; the name of the argument is flexible, but the convention is args.

- The main() method must be public.

- Improper main() method declarations cause runtime error, not a compile error.

- We can change the order of publicvoid, and static.

- We can change the name of args with any name our own.

Execution will be start from main() method only.


Difference between Constructor and Static


The static block will be executed at compiletime when the class is loaded on to the JVM. It is executed only once.
Constructor will be executed at Runtime while creating the object. The constructor is called only once for an object and it is called as many times as you create the object.
Ex: if a class Test is having one static block and a constructor. Then the static block is executed only once. If you create three objects based on Test class then the constructor is called three times.

how can we run javaprograme without having main() ?

static block are the blocks which are entertained at the time of class loading means there is no need to execute the code(infact with static block u can run your code without the main()) 
where as the static initializers are the static blocks which are used to initialize the static variables"





Static Methods cannot be overriden, although they can be redeclared/ redifined by a SubClass. So although Static Methods can sometimes appear to be overriddenPolymorphismwill not apply.

for ex:

class abc{
public static void show(){}

}
public class first extends abc {

public static void show(){}

public static void main(String[] args){
System.out.println("hi");
}
}

the above code will compile fine. here we have redefined the static method show() and not overriding it.

Why main() is static in java

In java the program execution begins with the main() method. So it must be called before any object exist.As main() is static it is independent of any object.


Why we use main() method in java programme


Jvm needs a default method to start program and from that method it starts instantiating the objects of other classes. so if every one uses their own methods then jvm is not able to find from where it need to start compiling. so Java people kept a default method not main() method, it is argumented main ie "main(String var[])" and this shoubld be always public and static. so that it is visible to the jvm.

Static variables and Methods in Java


static variables & methods: Actually the staic keyword is used to say that the member variables or methods are common variables for all the objects of that class.That means " There is only one copy of variables is there for the Class". Hence these variables can be accessed directly using the Class name or normally with the object name.
Eg:
class ab
{
static x;
--------
--------
}

the 'x' value can be accessed outside the class as
class bb
{
------
-------
ab.x;
or
ab a=new ab();
a.x;
------
------
}

static block:


The static block is the class level one time execution block it is mailnly used to do some operations at the time of class loading.
eg:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Here the class JdbcOdbcDriver contains the static block which contains the operations of registering with the DriverManager for establishing the connection.

In java we hav static and non-static(instance). Generally we members which may static or non-static.
Why static:: Suppose we hav to call member (a method or a variable) without or before creation of a an object, then that member should be declared as static member (eg: static int a; / static void mone(). Now these members can be called by using class name dot member(class name.member). And we know that non-static member can be called by using object. This static member will be shared by all the objects from the memory. But non-static members will be available seperate copy for all the objects.

Example for static::

We know every java program will be executed by the JVM program. That means JVM should call the main method before creation of an object for that class. Because of this, main method should be given as static. i,e public static void main(String args[]). Now jvm internally uses class name for calling the main method. Now after calling main method only object will be created..

static method are the methods which can acess only the static variables.
The use of a static method suffers from the following restrictions:

1. A static method can only call other static methods.

2. A static method must only access static data.

3. A static method cannot reference to the current object using keyword this.

Things you can mark as static:
■ Methods
■ Variables
■ A class nested within another class, but not within a method
■ Initialization blocks

Things you can't mark as static:
■ Constructors (makes no sense; a constructor is used only to create instances)
■ Classes (unless they are nested)
■ Interfaces
■ Method local inner classes (we'll explore this in Chapter 8)
■ Inner class methods and instance variables
■ Local variables




Static Block :Whenever you want to excute a code before execution of main mehtod, you can write a code using static block.

Static Method: Whenever you want to call a method using class name instead of using a object of class.

Static Variable : Static Variable will have a single copy per class.


Difference between Throws and Throw in java


Throws is useful to escape from handling Exception

Throw is useful to create an Exception Class Object and throw it out explicitly.

Advantages of Throw :

1. Throw is used in s/w testing to test a Java Program whether it is handling the Exceptions or not.

2. Throw is useful to create and throw user defined Exceptions

Throw is statement. 

Example:
public static void main(String s[]){
try{
//do ur stuff
}catch(ArithmaticException ae){ //1
s.o.p("caught in main");
}
}

public static int compute(int number){
if(number == 0) throw new ArithmaticException("....");//2
return n;
}

in above program, in 2 exception occur and at 1 it handled

Throws is a clause. Generally useful for checked exception.

Example

public static void main(String s[]){
try{
//do ur stuff
}catch(MyExxception ae){ //1
s.o.p("caught in main");
}
}

public static int compute(int number){
if(number == 0) throw new MyException("....");//2
return n;
}

class MyException extends Exception{
MyException(String str){
super(str);
}
}

Finalize() method in java


The Object class provides a callback method, finalize(), that may be invoked on an object when it becomes garbage.

Java provides us a mechanism to run some code just before our object is deleted by the Garbage Collector. This code is located in a method named finalize().

When JVM trying to delete the objects, then some objects refuse to delete if they held any resource. If our object opened up some resources, and we woluld like to close them before our object is deleted. So before Garbage operation we have to clean up the resources which the object held on, that clean up code we have to put in finalize() method.

- We can override finalize() to do cleanup, such as freeing resources. Any code that we put into our Class's overridden finalize() method is not guarunteed to run, so don't provide essential code in that method.

Execution Engine in JVM


JVM has an Execution Engine, it’s responsible for executing the instructions contained in the methods of loaded classes.

- the purpose of Execution Engine in JVM is when we compile our program then our code will convert into Bytecode but when we run our program then jvm convert our bytecode into machine code.
you know when we execute our program then firstly ClassLoader class will call by JVM after that RunTime class call for running and create run time envioronment.

- It Contanis Interpreter nd JIT(just in time)Compiler which convert the byte code instructions into machine language so that processor can execute them.

Class Loaders in Java


JVM includes at least one class loader that is embedded within the JVM called Bootstrap (primordial) class loader.

Types of class loaders :

Bootstrap : It loads all the JDK internal classes that are present in the rt.jar and i18n.jar.

Extensions : It Loads classes that are in jar files from JDK extensions directory i.e. lib/ext

System : It loads the classes from system classpath, the classes which are set by the CLASSPATH environment variable. CLASSPATH is an environment variable that contain active directory path.

Difference between Interface and Abstract class in Java


1. Abstract class is a class which contain one or more abstract methods, which has to be implemented by sub classes. An abstract class can contain no abstract methods also i.e. abstract class may contain concrete methods. A Java Interface can contain only method declarations and public static final constants and doesn't contain their implementation. The classes which implement the Interface must provide the method definition for all the methods present.

2. Abstract class definition begins with the keyword "abstract" keyword followed by Class definition. An Interface definition begins with the keyword "interface".

3. Abstract classes are useful in a situation when some general methods should be implemented and specialization behavior should be implemented by subclasses. Interfaces are useful in a situation when all its properties need to be implemented by subclasses

4. All variables in an Interface are by default - public static final while an abstract class can have instance variables.

5. An interface is also used in situations when a class needs to extend an other class apart from the abstract class. In such situations its not possible to have multiple inheritance of classes. An interface on the other hand can be used when it is required to implement one or more interfaces. Abstract class does not support Multiple Inheritance whereas an Interface supports multiple Inheritance.

6. An Interface can only have public members whereas an abstract class can contain private as well as protected members.

7. A class implementing an interface must implement all of the methods defined in the interface, while a class extending an abstract class need not implement any of the methods defined in the abstract class.

8. The problem with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement those method in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass

9. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast

10.Interfaces are often used to describe the peripheral abilities of a class, and not its central identity, E.g. an Automobile class might
implement the Recyclable interface, which could apply to many otherwise totally unrelated objects.

Note: There is no difference between a fully abstract class (all methods declared as abstract and all fields are public static final) and an interface.

Note: If the various objects are all of-a-kind, and share a common state and behavior, then tend towards a common base class. If all they
share is a set of method signatures, then tend towards an interface.

Similarities:

Neither Abstract classes nor Interface can be instantiated.

Different answers:


Abstraction:
Abstraction is a way of converting real world objects in terms of class. abstract is a keyword. It is not fully defined or implemented. We cannot create object forabstract class. For eg:
abstract class A
{
abstract void show();
}
calss B extends A
{
void show() // Should be overrided
{
c=10; // Must be define a method
System.out.println(c);
}
}

Interface:
In java we cannot use multiple inheritance. Instead of that we are using interface in java.
-It is pure abstraction.
-Method declaration.
-No need to create object.
-Support multiple inheritance.
-here we can using the access specifier is public and default other access specifier we cannot use.
-It is also a keyword.
-Each and every method in the interface is abstract. So no need to declareabstract explicitly.

For eg:
interface A
{
void show();
void disp();
}
class B implements A
{
show()
{
a=10;
System.out.println(a);
}
disp()
{
b=20;
System.out.println(b);
}
public static void main(String s[])
{
A a=new A();
a.show();
a.disp();
}
}
abstract class means its a partially developed class. It should have subclass immediately.It may have declaration of abstract and concrete methods.

Interface is a pure abstract class that means only declarations are allowed.The access specifier must be public.

Abstract class in java

Abstract Class : It can have without or with one or more Abstract Methods, have Concrete Methods (method with body implementation) and instance variables.

- We should declare Abstract Methods and Abstract Classes with the keyword abstract.

- We should implement all the Abstract Methods of Abstract Class in SubClass. In case if we not implement any one of Abstract Method in our SubClass we must and should declare our SubClass also as abstract.

Example :

abstract Class Manipulation{
int a,b;

/**** abstract method *****/
abstarct int calculate(int x, int y);


/**** concrete method *****/
int mul(int x, int y)
{
return (x * y);
}

}

Interface in Java and Cloneable interface


Interface : It is a reference type, similar to a Class that can contain only constants, method signatures, and nested types. There are no method bodies (abstract methods) means anInterface is a specification of method prototype.
- We should implement all the methods in our implementation class other wise if we left any method without implementation we should declare our Class as abstract.


- An Interface may or may not have any methods.

- An Interface can contain variables which are public, static, and final by default.

Interfaces cannot be instantiated—they can only be implemented by classes or extended by other Interfaces.

- We can use Interface reference variable to refer Implementation Class objects.

- An Interface can't implement another Interface.

- An Interface can extend already existing Interface.

- A single Class can implement multiple Interfaces.



Example :

public interface OperateCar {

// method signatures
int turn(Direction direction, double radius, double startSpeed, double endSpeed);
int changeLanes(Direction direction, double startSpeed, double endSpeed);
int signalTurn(Direction direction, boolean signalOn);
int getRadarFront(double distanceToCar, double speedOfCar);
int getRadarRear(double distanceToCar, double speedOfCar);
......
// more method signatures
}

Cloneable Interface:


Cloneable - It's a Tagged/Marked interface.

Tagged/Marked interface means those interfaces don’t have any methods.
- We use these Tagged/Marked interfaces for the special purposes only.

If we want to Clone any object of Class, that Class must implement the Cloneable interface evan though there is no methods in that interface.

Constructors in Java

Constructors: Constructors are block of codes which gets executed when the class is instantiated. IT provides initial state to the object i.e object initialization and also for resource allocation. It has a public, Private, & protected modifiers. It is used to initialize a class through object. Important properties of constructors are,

• A constructor doesn’t have a return type.
• The name of the constructor must be the same as the name of the class.
• Unlike methods, constructors are not considered to be members of a class.
• A constructor is called when a new instance of an object is created. In fact, it’s the new keyword that calls the constructor. After creating the object, you can’t call the constructor again.


If we create only object the constructor is not called. that is

Example obj; //cant call the constructor


Here’s the syntax for coding a constructor:

public ClassName (parameter-list) [throws exception...]
{
statements...
}


If no user defined constructor is provided for a class, compiler initializes member variables to its default values.
  • numeric data types are set to 0
  • char data types are set to null character(‘\0’)
  • reference variables are set to null

Basic Constructors The most obvious work of a constructor is to initialize the fields with values. The values may come as parameter-list for constructor or as a result of certain expressions or the like. One of such example is given below.

public Triangle(float a, float b, float c){
side1 = a;
side2 = b;
side3 = c;
}

Constructors can also be overloaded. For example the above code initializes the Triangle class which consists of three fields representing three sides of a triangle. If we decide to add another constructor which accepts two sides and one angle as parameters yes, we can. The following code illustrates this.

public Triangle(float a, float b, double theta){
side1 = a;
side2 = b;
side3 = (float) Math.sqrt( (a * a) + (b * b) – 2 * a * b *
Math.cos(theta) );//cosine rule
}

Now both of the below statements can be used to instantiate the Triangle class. 
Triangle t1 = new Triangle(10, 20, 30);//arbitrary triangle
Triangle t2 = new Triangle(10, 20, 90.0);//right angled triangle

Default Constructors Every class should have at least one constructor. If we add none, Java will add one with empty body, empty parameter-list and public access modifier. Such added constructor is known as default constructor. But if we add at least one, Java will add nothing. So be clear, if you added a constructor with parameter-list then you have no way to instantiate the class without passing parameters unless or until you explicitly create a parameter less constructor.

class A { }
class B {
public B(int a){
}
}
class Demo {
public static void main(String args[]){
A a = new A(); //No error
B b = new B(); //Error
B b = new B(10); //No error
}
}

Calling Other Constructors Calling other constructors of the same class is done by using the this keyword. This technique is commonly used when you have several constructors that build on each other.

NOTE One of a good programing practice is, if more than one constructor is used then cascade them as
possible. Make sure that only a single copy of the code actually initializes and all other constructors call it. For example the example in previous page can be rewritten as,

 public Triangle(float a, float b, float c){
side1 = a;
side2 = b;
side3 = c;
}
public Triangle(float a, float b, double theta){
this(a, b, (float)Math.sqrt((a * a) + (b * b) – 2 * a * b *
Math.cos(theta) ));
}

Remember,
• this() must be the first statement in the constructor.
• You can't invoke more than one constructor from a constructor.


Create your First Constructor
Step 1: Type following code in your editor

class Demo{
int value1;
int value2;
Demo(){
value1 = 10;
value2 = 20;
System.out.println("Inside Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[]){
Demo d1 = new Demo();
d1.display();
}
}
}


InstanceOf Keyword in Java


The situation in which knowledge of an object's type at run time is important involves casting. In Java, an invalid cast causes a run-time error. Many invalid casts can be caught at compile time. For example, a superclass called A can produce two subclasses, called B and C. Thus, casting a B object into type A or casting a C object into type A is legal, but casting a B object into type C (or vice versa) isn't legal. Because an object of type A can refer to objects of either B or C. How can you know, at run time, what type of object is actually being referred to before attempting the cast to type C? It could be an object of type A, B, or C. If it is an object of type B, a run-time exception will be thrown. Java provides the run-time operator instanceof for this problem . 
The instanceof keyword can be used to test if an object is of a specified type.its return type is boolean type

Example :

class A {
int i, j;
}
class B {
int i, j;
}
class C extends A {
int k;
}
class D extends A {
int k;
}

class InstanceOf {
public static void main(String args[]) {
A a = new A();
B b = new B();
C c = new C();
D d = new D();
if(a instanceof A)
System.out.println("a is instance of A");
if(b instanceof B)
System.out.println("b is instance of B");
if(c instanceof C)
System.out.println("c is instance of C");
if(c instanceof A)
System.out.println("c can be cast to A");
if(a instanceof C)
System.out.println("a can be cast to C");
System.out.println();
// compare types of derived types
A ob;
ob = d; // A reference to d
System.out.println("ob now refers to d");
if(ob instanceof D)
System.out.println("ob is instance of D");
System.out.println();
ob = c; // A reference to c
System.out.println("ob now refers to c");
if(ob instanceof D)
System.out.println("ob can be cast to D");
else
System.out.println("ob cannot be cast to D");
if(ob instanceof A)
System.out.println("ob can be cast to A");
System.out.println();
// all objects can be cast to Object
if(a instanceof Object)
System.out.println("a may be cast to Object");
if(b instanceof Object)
System.out.println("b may be cast to Object");
if(c instanceof Object)
System.out.println("c may be cast to Object");
if(d instanceof Object)
System.out.println("d may be cast to Object");
}
}

The output from this program is shown here:

a is instance of A
b is instance of B
c is instance of C
c can be cast to A
ob now refers to d
ob is instance of D
ob now refers to c
ob cannot be cast to D
ob can be cast to A
a may be cast to Object
b may be cast to Object
c may be cast to Object
d may be cast to Object .

Another Example:

public class MainClass {
public static void main(String[] a) {

String s = "Hello";
if (s instanceof java.lang.String) {
System.out.println("is a String");
}
}

This Keyword in Java

This :
             If we create any object, internally a reference variable "this" will created and it points to the object.. so we can say ''this'' is a keyword that points to the current object. 
Suppose we hav created an object as Srinivas sri=new Srinivas(); 
then internally 2 reference variables "sri" and "this" will be pointed to the Srinivas object. So by using "this" we can access members of Srinivas object.
this.getName(); is use to access the getName() method for the current ClassInstance.



Eg:
class Sample {
int i;
int j;
Sample(int i, int j) {
this.i=i;
this.j=j;
}}
class Demo {
public static void main(String args[]) {
Sample s=new Sample(10,20);
}}



Immutable class in Java

It's Possible to make a class as immutable.



In order to make a Class Immutable we must restrict changing the state of the Class object by any means. This in turn means avoiding an assignment to a variable. We can achieve this through a final modifier. To further restrict the access we can use a private access modifier. Do not provide any method where we modify the instance variables.

Somebody can create the SubClass, that can contain methods, which over ride our base class (Immutable Class) methods. Here he can change the variable values.
- So to avoid that make the Methods in the Class also final. Or a better approach is to make the Immutable Class itself final. Hence cannot make any sub classes, so no question of over ridding.


public class final ClassName
{
---
--- all properties must be final and private
private final int i =10;

---
--- all behaviours must be final
}



An Object is considered immutable if its state cannot change after it is constructed.

Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.

Search characters and substrings in Strings


The String Class provides accessor methods that return the position within the String of a specific character or substring: indexOf() and lastIndexOf().

- The indexOf() methods search forward from the beginning of the String.

- The lastIndexOf() methods search backward from the end of the String.

If a character or substring is not found, indexOf() and lastIndexOf() return -1.

- The String Class also provides a search method, contains, that returns true if the String contains a particular character sequence. Use this method when only need to know that theString contains a character sequence, but the precise location isn't important.

1. int indexOf(int ch)/int lastIndexOf(int ch) : Returns the index of the first (last) occurrence of the specified character.

2. int indexOf(int ch, int fromIndex)/int lastIndexOf(int ch, int fromIndex) : Returns the index of the first (last) occurrence of the specified character, searching forward (backward) from the specified index.

3. int indexOf(String str)/int lastIndexOf(String str) : Returns the index of the first (last) occurrence of the specified substring.

4. int indexOf(String str, int fromIndex)/int lastIndexOf(String str, int fromIndex) : Returns the index of the first (last) occurrence of the specified substring, searching forward (backward) from the specified index

5. boolean contains(CharSequence s) : Returns true if the string contains the specified character sequence.

Note: CharSequence is an interface that is implemented by the String class. Therefore, you can use a string as an argument for the contains() method.

Strings in Java

String class

public final class String extends Object implements Serializable

The String class represents character strings.
All string literals in Java programs, such as "abc", are implemented as instances of this class.

Strings are constant; their values cannot be changed after they are created.

String str = "abc";
is equivalent to:

char data[] = {'a', 'b', 'c'};
String str = new String(data);

How strings can be used:

System.out.println("abc");
String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2,3);
String d = cde.substring(1, 2);

The String class supports several constructors:

To create an empty String we call the default constructor
String s = new String();
Will create an instance of String with no characters in it.


Methods From String Class:

char charAt(int index)
Returns the char value at the specified index.
String concat(String)
Concatenates the String with the specified String.
String toUpperCase()
String toLowerCase()
boolean startsWith(String)
String subString(int start_index)
String subString(int start_index,int end_index)
int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.

boolean equals(Object anObject)
Compares this string to the specified object.

boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations

int length()
Returns the length of this string.


StringBuffer class:

public final class StringBuffer extends Object implements Serializable, CharSequence

A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.


StringBuffer defines three constructors:
1.StringBuffer();
2.StringBuffer(int size)
3.StringBuffer(String str)

  • The default constructor (the one with no parameters) reserves room for 16 characters without reallocation.
  • The second version accepts an integer that explicitly sets the size of the buffer.
  • The third version accepts a String argument that sets the initial contents of the StringBuffer object and reserves for 16 additional characters without reallocation.


NOTE

All most all the methods from String class are available in StringBuffer class.
int length()
int capacity()
char charAt(int index)
void setChatAt(int index,char ch)
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
StringBuffer insert(int index,String str)
StringBuffer reverse()
StringBuffer delete(int startindex,int endindex)
StringBuffer deleteCharAt(int loc)
StringBuffer replace(int start, int end, String str)
String subString(int startIndex)
String subString(int startIndex,int endIndex)


StringBuffer and StringBuilder class
=>StringBuffer is used to store character strings that will be changed(String objects cannot be changed). It automatically expands as needed.
=>StringBuilder was added in Java 5.
=>It is identical in all respects to StringBuffer except that it is not synchronized, which means that if multiple threads are accessing it at the same time, there could be trouble.
=>For single-threaded programs, the most common case, avoiding the overhead of synchronization makes the StringBuilder very slightly faster.


Comparing Strings and Portion Of Strings:



            The String Class has a number of methods for comparing strings and portions of Strings.

boolean endsWith(String suffix)/boolean startsWith(String prefix) : Returns true if this string ends with or begins with the substring specified as an argument to the method.

- boolean startsWith(String prefix, int offset) : Considers the string beginning at the index offset, and returns true if it begins with the substring specified as an argument.

- int compareTo(String anotherString) : Compares two strings lexicographically. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument.

- int compareToIgnoreCase(String str) : Compares two strings lexicographically, ignoring differences in case. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument.

- boolean equals(Object anObject) : Returns true if and only if the argument is a String object that represents the same sequence of characters as this object.

- boolean equalsIgnoreCase(String anotherString) : Returns true if and only if the argument is a String object that represents the same sequence of characters as this object, ignoring differences in case.

- boolean regionMatches(int toffset, String other, int ooffset, int len) : Tests whether the specified region of this string matches the specified region of the String argument. Region is of length len and begins at the index toffset for this string and ooffset for the other string.

- boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) : Tests whether the specified region of this string matches the specified region of the String argument.

Region is of length len and begins at the index toffset for this string and ooffset for the other string.

The boolean argument indicates whether case should be ignored; if true, case is ignored when comparing characters.

- boolean matches(String regex) : Tests whether this string matches the specified regular expression. Regular expressions are discussed in the lesson titled "Regular Expressions."