Friday 9 December 2011


About the Java Technology

Java technology is both a programming language and a platform.
The Java Programming Language

The Java programming language is a high-level language that can be characterized by all of the following buzzwords:

Simple
Object oriented
Distributed
Multithreaded
Dynamic
Architecture neutral
Portable
High performance
Robust
Secure

Each of the preceding buzzwords is explained in The Java Language Environment , a white paper written by James Gosling and Henry McGilton.

In the Java programming language, all source code is first written in plain text files ending with the .java extension. Those source files are then compiled into .class files by the javac compiler. A .class file does not contain code that is native to your processor; it instead contains bytecodes — the machine language of the Java Virtual Machine1 (Java VM). The java launcher tool then runs your application with an instance of the Java Virtual Machine.










Figure showing MyProgram.java, compiler, MyProgram.class, Java VM, and My Program running on a computer.

An overview of the software development process.

Because the Java VM is available on many different operating systems, the same .class files are capable of running on Microsoft Windows, the Solaris™ Operating System (Solaris OS), Linux, or Mac OS. Some virtual machines, such as the Java HotSpot virtual machine, perform additional steps at runtime to give your application a performance boost. This include various tasks such as finding performance bottlenecks and recompiling (to native code) frequently used sections of code.







Figure showing source code, compiler, and Java VM's for Win32, Solaris OS/Linux, and Mac OS

Through the Java VM, the same application is capable of running on multiple platforms.

The Java Platform

A platform is the hardware or software environment in which a program runs. We've already mentioned some of the most popular platforms like Microsoft Windows, Linux, Solaris OS, and Mac OS. Most platforms can be described as a combination of the operating system and underlying hardware. The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms.

The Java platform has two components:

The Java Virtual Machine
The Java Application Programming Interface (API)











You've already been introduced to the Java Virtual Machine; it's the base for the Java platform and is ported onto various hardware-based platforms.

The API is a large collection of ready-made software components that provide many useful capabilities. It is grouped into libraries of related classes and interfaces; these libraries are known as packages. The next section, What Can Java Technology Do? highlights some of the functionality provided by the API.
Figure showing MyProgram.java, API, Java Virtual Machine, and Hardware-Based Platform

The API and Java Virtual Machine insulate the program from the underlying hardware.

As a platform-independent environment, the Java platform can be a bit slower than native code. However, advances in compiler and virtual machine technologies are bringing performance close to that of native code without threatening portability.

The terms"Java Virtual Machine" and "JVM" mean a Virtual Machine for the Java platform.



Basics Of Java Architecture

A.1 How Java works

Computer programs are usually written in human-readable source code. The compilers convert this source code into machine-readable (executable) programs. Conventional compilers for programming languages like C++ produce machine-readable code that is executed on a specific hardware; for example, the C++ compiler for windows on x86 hardware compiles source code into executable programs, which can run only on Intel x86 compatible hardware. A C++ program needs to be recompiled for a different platform using the platform-specific compiler.



A.1.1 How Java program compiles?

Java takes a different approach than the platform-specific compilers. The Java compiler generates hardware-independent bytecodes from the source code. These bytecodes can be executed only by a Java Virtual machine (JVM). The compilation process is illustrated on the left side of figure A.1. Java source code is compiled into Java bytecode files, also called as class files.










java compilation and Execution
Figure A.1 Java Source compilation and Execution



The class files are special files with a specific format. They are not machine-readable (executable) and cannot be directly executed on a hardware platform. JVM understands the bytecodes in a class file and can execute it. The Java compiler’s job is to convert the Java source code in a class file, which can be understood and executed by the JVM.



A.1.2 How Java program runs?

The Java Virtual Machine actually executes instructions from the class files. JVM is an abstract computing machine. Like a real computing machine, it has an instruction set. It can run code in Java class (bytecode) format.

At runtime, the class loader fetches the .class file from storage media or network. Each class file is fed to a bytecode verifier to ensure that the class file is correctly formatted and is safe for execution. The byte-verification process slows the process to load the class in JVM, but it is performed only once and not every time the program runs. Figure A.1 explains how the JVM fetches classes from disk or network and then verifies that the bytecodes are safe for executing.

Once the class is loaded (the bytecodes become available to JVM), the bytecodes in .class file are actually fed to the JVM. This bytecode is executed by one of the execution units (interpreter or JIT) of JVM at runtime. The execution units carry out the instructions specified in the bytecodes. The interpreter is the simplest execution unit of the JVM. It reads the bytecode, interprets it and performs the associated function. Interpreters are generally slower that the native-code compilers (like C++ compiler), as they need to lookup for meaning of each byte code during the execution. To speed up the execution, the JVM has another execution unit. It is called the JIT or “Just In Time” compiler. It optimizes the runtime bytecode from a class file by compiling it to native code just before the execution.












A.1.3 JVM and platform independence

Since a Java .class file runs only in the JVM, how will you run the same Java code across multiple platforms? For each platform, a platform-specific JVM is provided. JVM for Windows, Linux and Solaris platforms are available on Sun’s website. You can think of a JVM as a software processor which can be plugged-in any hardware platform to make it execute the .class files. Therefore, the same bytecode runs on multiple platforms without any portability issues as it actually runs on the JVM. The JVM takes care of platform dependent issues at runtime.













The Java Virtual Machine knows nothing about the Java programming language. It only needs to know about the class file format. A class file contains Java Virtual Machine instructions (or bytecodes). Therefore, any language capable of generating a valid class file can be hosted by the Java Virtual Machine. To implement the JVM, you only need to be able to read the Java class file’s format and correctly perform the operations specified in it. For security, the Java Virtual Machine imposes strict format and structural constraints on the byte code in a class file.

Java Programs

Quick Sort In Java

 Introduction

In this example we are going to sort integer values of an array using quick sort.

Quick sort algorithm is developed by C. A. R. Hoare. Quick sort is a comparison sort. The working of  quick sort algorithm is depending on a divide-and-conquer strategy. A divide and conquer strategy is  dividing  an array  into two sub-arrays. Quick sort is one of the fastest and simplest sorting algorithm. The complexity of quick sort in the average case is  Θ(n log(n)) and in the  worst case is Θ(n2).
Code description:
In quick sort algorithm pick an element from array of elements. This element is called the pivot. Then compare the the values from left to right until a greater element is find then swap the values. Again start comparison from right with pivot. When lesser element is find then swap the values. Follow the same steps until  all elements which are less than the pivot come before the pivot and all elements greater than the pivot come after it. After this partitioning, the pivot is in its last position. This is called the partition operation. Recursively sort the sub-array of lesser elements and the sub-array of greater elements.

Working of quick sort algorithm:
Input:12 9 4 99 120 1 3 10 13





Output:1 3 4 10 12 13 99 120
The code of the program :

public class QuickSort{
  public static void main(String a[]){
  int i;
  int array[] = {12,9,4,99,120,1,3,10,13};

  System.out.println("\n\n RoseIndia\n\n");
  System.out.println(" Quick Sort\n\n");
  System.out.println("Values Before the sort:\n");
  for(i = 0; i < array.length; i++)
  System.out.print( array[i]+"  ");
  System.out.println();
  quick_srt(array,0,array.length-1);
  System.out.print("Values after the sort:\n");
  for(i = 0; i <array.length; i++)
  System.out.print(array[i]+"  ");
  System.out.println();
  System.out.println("PAUSE");
  }

  public static void quick_srt(int array[],int low, int n){
  int lo = low;
  int hi = n;
  if (lo >= n) {
  return;
  }
  int mid = array[(lo + hi) / 2];
  while (lo < hi) {
  while (lo<hi && array[lo] < mid) {
  lo++;
  }
  while (lo<hi && array[hi] > mid) {
  hi--;
  }
  if (lo < hi) {
  int T = array[lo];
  array[lo] = array[hi];
  array[hi] = T;
  }
  }
  if (hi < lo) {
  int T = hi;
  hi = lo;
  lo = T;
  }
  quick_srt(array, low, lo);
  quick_srt(array, lo == low ? lo+: lo, n);
  }
}
.
Output of the example: .


C:\array\sorting>javac QuickSort.java
C:\array\sorting>java QuickSort
       RoseIndia
       Quick Sort
Values Before the sort:
12  9  4  99  120  1  3  10  13
Values after the sort:
1  3  4  9  10  12  13  99  120
PAUSE
C:\array\sorting>_

 

 

object class

 

Java.lang.package contain several utility classes which are mandatory for writing simple to complex programs.There is no need to import java.lang.package as by default it is available to our program
Java.lang.object class:
It is super class of any java class .all the predefined classes are user defined classes either directly or indirectly extends java.lang.objectclass
This class contain several utility methods which can be applied on any java object.
.for every class parent class in object class 
Class A extends B
{
// code
}

Means, Ie.for B,parent is object but for A parent is B only .so java supports multilevel inheritance
The following are the 11 methods present in object class
1).public string to string()
For string representation of object.
2)public native int hashcode()
Returns the hashcode of an object
3)public Boolean equals(object obj)
For comparing the current object with the specified object 
4)protected native object clone() throws clonesoft support Exception
To produced cloned object
5)protected void finalize()throws throwable
6)public final native class getclass()
7)public final viod wait()throws interrupted exception
8)public final void wait(longms)throws interrupted exception
9)public final void wait(long ms,int ns)throws interrupted exception
10)public final native void notify()
11)public final native void notifyAll()

1.tostring():
to String Example:
Class Sample
{
String name;int rollno;
Student(string name,int rollno)
{
This.name=name;
This.name=rollno;
}
Public static void main(string[]args)
{
Student s1=new student(“visvam”,101);
System.out.println(s1);
}
Public string tostring()
{
//return get class().getName()+’@’+
Integer.toHexstring(hashcode());
//return”this is student object”;
Returnname+”……”+rollno;
}
2.Hashcode():
HashCode Example:
String s1=new string(”visvam”);
String s2=new string(“visvam”);
System.out.println(s1.hasgcode());
System.out.println(s2.hasgcode());
hashcode()---when ever an object is created jvm allocates a number for that object which is considered as hashcode().
Most of the cases the hashcode saving is unique for every object
Jvm uses this hashcode while saving objects to hashtable,hashmap or hashset.
Hashcode never represents the address of an object.
Oppropriate way of overriding of hashCode method:
Ex: class Student
{
String name,int rollno;
Student(string name,int rollno)
{
This.name=name;
This.name=rollno;
}
Public int hashcode()
{
return rollno
}
Public string tostring()
{
return name+”-----“+rollno;
}
Public static void main(string[]args)
{
String s1=new string(“java”,101);
{
System.out.println(s1); // java ...... 101
}
Public int hashcode()
{
retuen rollno;
}

It is highly recomonded to override hashcode .In our classes.overriding hashcode is appropriate if and only if every object we have to assign a different hashcode.This is helpful for the jvm to save object in hashcode,hashmap,hashset and serching also.
3.Equals()
Student s1=new student(“viswam”,101);
Student s1=new student(“surya”,102);
Student s1=new student(“surya”,102);
System.out.println(s1==s2); // false
System.out.println(s1.equal(s2)); // false
System.out.println(s2==s3); // false
System.out.println(s2.equals(s3)); // false
System.out.println(s2==s2); // true
System.out.println(s2.equals(s2)); // true
= = Operator:
This is meant for reference comparision always s1==s2 is true if and only ig both s1 and s2 pointing to the same object on the heap.
Ex: string s1=”visvam”;
Thread t1=new Thread()
System.out.println(s1==t1);
we can’t apply==operator for incomparable types.validation leads to CTE saying incomparable types.
S1==null is always “false”(no CTE&RTE)
equals()method :
The equals method available in object class meant for reference or address comparision only(similar to==operator)but,we can override equals() in our class for content comparision.
Overriding of .equals()
===> public Boolean equals(object o)
{
String name1=this.name;
Int rollno=this.rollno;
Student name2=s2.name;
Int rollno2=s2.rollno;
If(name1.equals(name2)&rollno1==rollno2)
Return true;
else
return false;
}
===>then System.out.println(s2.equals(s3)); //true
System.out.println(s1.equals(s2)); // false
====> in string class. .Equals() method is already overridden for context comparision. Object class.equals method. Satisfy the following two conditions.
1.this is always for address comparision
2.it never rise CTE&RTEs even the arguments are different types.
If the arguments are different types .equals() is simply return false.
public boolean equals(object o)
{
try
{
Name 0=this.name1;
Rollno1=this.rollno1;
Student s=(student)0;
Name2=this.name2;
Rollno2=this.rollno2;
If(name1.equals(name2)&rollno1=rollno2)
return true;
else
return false;
}
Catch(classcastException e)
{
return false;
}
}
Then==>s.o.pln(s1.equals(“visvam”));
Catch(nullpointerException e)
{
Return false;
}
Then==> s.o.pln(“null”));

Comparision between==Operator &.equal :
= = Operator :
1.we can apply for both primitation and object references
2. r1= =r2 is true if and only both r1,r2 pointingly to same object on the heap. ie ==is always for reference comparision.
3.we cant’t override for context comparision.
4.we can’t apply = = operator for different tpes of objects .incomparable types.
5.s1= =null is always false
.equals()
1.we can apply only for object references 
2.by default ,.equals() present in the object class is meant for address comparision onl
3.we can override .
4..equals()never release any CTE&RTEs even the arguments are different types .in that situation it will just simply return false.
5.s1.equals(null) gives false when handle NPE through catch 
Relationship between = =and .Equals
1. if r1==r2 is true then r1.equals(r2) is always true.
2. if r2 = = is false then r1.equals(r2) may returns true.
Contract between hashcode and .equals()
If r1=equals(r2) is true,then r1.hashcode() = = r2.hashcode();
Ie .equalent objects should alwas have same hashcode.
If r1.equals(r2) is false ,then their hashcode may be same.
If R1.hashcode() = = r2.hashcode() may returns true
If R1.hashcode() = = r2.hashcode() may returns true ,then r1.equals(r2)may be true.
If R1.hashcode() = = r2.hashcode() may returns false,then r1.equals(r2)alwas false.
In order to satisfy the above contract we have to override hashcode() whenever we are overriding .equals()
4.clone() 
Protected object clone() throws clone not supported exception.
This method can used to prouduced exactly duplicate copy of an object..
All the objects can’t produce cloned object ,only clonable objects can produce duplicate copies .
An object is said to be conable if and only if the corresponding class implements clonable interface.
By using the folling object class clone() method we can produced cloned objects
Protected object clone() throws clone supported exception
CheckedException so we should handle by using try catch or throws to the caller by using throws clause.

String class

String class it is there in Java.lang package.
Immutability of the String object:
String s=”java”;
s.concat(“soft”);
System.out.println(s);
output:- jaVa

Muatability of StringBuffer object:
StringBuffer s=new StringBuffer(“java”);
s.append(“soft”);
System.out.println(s);
output:- javasoft
  • Once we created a string object we are not allowed to perform any changes in the existing String object.
  • If you want to perform any changes (by using concat() or any other), with the changes a new String object will create.
  • Hence String objects are considered as Immutable
  • In the case of StringBuffer, once we created a StringBuffer object, we are allowed to perform any changes in the existing StringBuffer object only.
  • Hence StringBuffer object is mutable
1. String s1=new String(“java”);
2. String s2=new String(“java”);
System.out.println(s1==s2); --> false
System.out.println(s1.equals(s2)); --> true
But
3. StringBuffer s3=new StringBuffer(“viswan”);
4. StringBuffer s4=new StringBuffer(“viswan”);
System.out.println(s1==s2); --> false
System.out.println(s1.equals(s2)); --> false
  • In the String class .equals() is overridden for content comparision. Here the content of s1 and s2 are equal, that’s why s1.equals(s2) returns true.
  • In the String class .equals() is not overridden for content comparision. whenever we calling .equals()
Method on the StringBuffer object, Object class .eqauals() method will execute, which is meant for address comparision only.
Hence s3.equals(s4) returns false eventhough the contents of s3 and s4 are same.
Difference between the ways of creating String objects:-
1. String s1=”durga”;
2. String s2=new String(“durga”);
• In the first case, the JVM will check, is the any String object with content durga in the “String Constant Pool”. If there is no such object then only a new String object will create and s1 will pointed to that object.
• If the object already present then s1 will simply refers to that object instead of creating a new object.
• In the second case, two String objects will create, one is on the heap, for the other one in the “String Constant Pool” (If the object is not already present) and s2 will pointing to heap object.
Ex: String s=”viswan”;
s.concat(“sw”);

* In this content, three objects are created. One is on heap and another two on “String Constant Pool”

• “String Constant Pool” never allows Garbage Collection.
• Heap durgasw
String Constant Pool software
• I the object does not have any references in the “String Constant Pool”, still this is not eligible for the Garbage Collection.
• All the objects present in the “String Constant Pool” destroy, whenever the JVM restarted.
What is the output and how many String objects are created.
String s1=”spring”;
String s2=s1+”summer”;
s1.concat(“fall”);
s2.covcat(“s1”);
s1+=”winter”;
System.out.println(s1+ “,”+s2);
output: spring , springsummer
string constant pool: spring, summer, fall, winter
Heap: springsummer, springfall, springwinter, springsummerspring
Advantage Of StringConstantPool:
String s1=”you can’t change me”;
String s2=”you can’t change me”;
System.out.println(s1==s2); // true
System.out.println(s1.equals(s2)); //true
String s3=new String(“you cannot change me”);
System.out.println(s1==s3);//false
System.out.println(s1.equals(s3)); //true
String s4=”you can’t” + “change me”;
System.out.println(s1==s4);
String s5=”you can’t”;
String s6=s5+”change me”;
System.out.println(s1==s6); //false
If final String s7=”you can’t”
System.out.println(s1==s7); //true
String s8= s7+”change me”;
s1==s8; //true.
• In our programme., if any String object is repeatedly going to use, we can keep only one copy in the String Constant Pool and shared by several required references. Instead of creating several same content object, we are creating only one object, this is very efficient w.r.t to memory point of view.
• As several refernces pointing to the same object in the StringConstantPool, by using any references , if you allowed to use the content of that object, the remaining references have to suffer.
• Hence once we created a string object we are not allowed to change content.
• If you want to perform any changes, with those changes a new String Object wil create . Hence the String Objects are declared as the Immutable.
• StringConstantPool ---> Performance is improved. (advantages)
----> Immutability ( disadvantages)
Interning Of Strings:
String s1=new String(“viswan”);
String s2=s1;
String s3=s1.intern();
S1==s3; //false
String s4=”viswan”;
s4==s3; //true
• Intern() method used to point the String constant pool object instead of heap object.
String Class Constructors:
1. String s=new String(String s);
2. String s=new String();
3. String s=new String(StringBuffer s1);
4. StringBuffer s1=new StringBuffer(“xxx”);
5. String s=new String(byte[]);
Ex: byte[] b={100,101,102,102}
String s=new String(b);
System.out.println(s); //”defg”
6. String s=new String(char[]);
Ex: Char[] ch={a,b,cd};
String s=new String(ch);
System.out.println(ch); // abcd
String Class Methods (only some imp):
1. public char charAt(int index):
This method returns the character located at the string’s specified index. Remember that String indexes are zero based.
2. public String concat(String s):
This method returns a string with the value of the String passed into the method appended to the end of the String used to invoke the method.
The overloaded + and += operators perform the same function of concat() method.
Ex: String s=”durga”;
s=s.concat(“sw”);
s=s+”sw”;
s+=”sw”;
System.out.println(s); //durgasw
3. public Boolean equals IgnoreCase(String s):
This method returns Boolean value ie., true or false depending on whether the value of the string in the argument is the same as the value of the String used to invoke the method.
Ex: String s=”DURGA”;
System.out.println(s.equalIgnoreCase(“Durga”); //true
s.equals(“Durga”); //false
4. public int length():
length() is the method in the case of String objects where as ‘length’ is the variable in the case of Arrays.
Ex: String s= “durga”;
System.out.println(s.length); //CTE
System.out.println(s.length());// 5
5. public String replace(char old, char new):
String x=”ababab”;
System.out.println(x.replace(‘a’,’b’); //bbbbbb
6. a). public String substring(int begin):
String x=”0123456789”;
System.out.println(s.subString(6)); //6789
b). public String substring(int begin, int end):
System.out.println(s.subStrin(5,8)); //567

* End is not included in o/p.
* This is already overloaded method.
* It considers the index only.

String s=”abcdefgh”;
System.out.println(s.subString(3)); //defgh
System.out.println(s.subString(4,7)); //efg
7. public String toUpperCase():
String s= “ A New Moon”;
System.out.println(s.toUpperCase()); // A New Moon
8. public String toLowerCase()
String s= “ A New Moon”;
System.out.println(s.toLowerCase()); // A New Moon
9. public String trim()
String s=”viswan”;
System.out.println(s.trim()); //viswan
---> Leading or trailing blackspaces removed but not in the middle.
10. public int indexOf(char ch)
---> Returns the index of the first occurance of the specified character.
---> Returns -1, if there is no such character.
String s=”durgascjp”;
s.indexOf(d); //0
11. public int lastIndexOf(char ch)
---> Returns the last occurrence index of the specified character.
String s=”durga”;
String y=s.toUpperCase();
String s=s.toLowerCase();
System.out.println(s==x);//true
System.out.println(s==y); // false

s,x ---> durga y---> durga

• After applying any method of the contest of the String has to change then only a new String object will create with the corresponding changes.

Ex1:
String s1=”abc”; s1 ---> abc
String s2=”def”; s2 ---> def <--- s3
String s3=”s2”; s2 ---> ghi
String s2=”ghi”;
S.o.p(s1+s2+s3); //abcghidef
Ex 2:
String x=new String(“xyz”);
y=”abc”;
x=x+y;
total objects are 4 ---> 2 on heap, 2 on string constant pool

* String objects as well as wrapper class objects are immutable.
* String, StringBuffer, wrapper, Math, StringBuilder classes are the final classes. So, we are not allowed to create the child classes.

StringBuffer , StringBuilder

StringBuffer:
String objects are immutable where as StringBuffer objects are mutable.
Ex: String s=”viswan”;
s.concat(“sw”); -----> Immutability
System.out.println(s);//viswan

But StringBuffer s=new StringBuffer(“viswan”);
s.append(“sw”); -----> Mutability
System.out.println(s); // viswansw

String s1=new String(“java”);
String s2=new String(“java”);
s1==s2; //false
s1.equals(s2); //false
  • Because in StringBuffer class .equals() method is not overridden for content comparision. It is meant for address comparision only.
Constructors Of StringBuffer:
StringBuffer s= new StringBuffer();
---> Creates an empty StringBuffer object with default initial capacity 16.
class SBDemo
{
public static void main(String a[])
{
StringBuffer s=new StringBuffer();
s.append(“abcdefghijklmnop”);
System.out.println(a.capacity());
}
}
---> If we add q then //34=(16+1)*2
• When ever StringBuffer reaches its max capacity a new StringBuffer object is created with the new capacity is (current capacity + 1)*2 ---> (16+1)*2=34
• First time only this can be valid. Afterwards the capacity increases with the increase of characters only.
StringBuffer sb=new StringBuffer(int initialcapacity)
• Creates an empty StringBuffer object with the specified capacity.
StringBuffer sb=new StringBuffer(String s);
• Creates an equivalent StringBuffer object for the given String and with a capacity equal to (length of String + 16).
Ex: StringBuffer s=new StringBuffer(“durga”);
System.out.println(s.capacity()); // 5+16=21
Length of the string “durga” =5

important methods of the StringBuffer :
1. public int length() ---> returns the length of the StringBuffer.
2. public int capacity() --->returns the capacity of the StringBuffer
3. public char charAt(int index)
Ex: StringBuffer s=new StringBuffer(“durga”);
char ch= s.charAt(3); //g
char ch=s.charAt(10); //invalid index
i.e., If the index is invalid we will get a RTE saying “String index of bounds Exception”.
4. public void setCharAt(int index, char ch)
Constructing String from the given StringBuffer Object:
String s= bew String(StringBuffer s)
String s= StringBuffer.toString();
5. public synchronized StringBuffer append(String s); or (int i) or (char ch) or (float f) or (double d) or (char[] ch) or (Boolean b) or (byte[] b)….
Ex: StringBuffer s= new StringBuffer(“PI”);
s.append(3.14 f);
System.out.println(s); //pi=3.14
6. public synchronized StringBuffer insert(int offset, String s) or int/char/float/Boolean etc.,
Ex: StringBuffer s= new StringBuffer(“durga”);
s.insert(2,”012”);
System.out.println(s); //du012rga
7. public synchronized StringBuffer delete(int start, int end)

* delete the substring present in start to end – 1 position.
8. public synchronized stringBuffer delete charAt(int index)

* For deleting the character located at specified index.
9. public synchronized StringBuffer reverse()
Ex: StringBuffer sb= new StringBuffer(“madam”);
System.out.println(s.reverse()); //madam
10. public void setLength(int new length)

* This operation can result in the StringBuffer with the specified length. The Extra characters will be removed.

If the StringBuffer is lessthan the specified length padded or appended with space characters to the required length.
Ex: StringBuffer s=new StringBuffer(“viswan”);
s.length(3);
System.out.println(s); //vis
Chaining Of Methods :
• In the case of String and StringBuffer, the return type of most of the methods are String or StringBuffer only, on that return type we are allowed to call another method, as a result chaining of methods is possible, in the case of String and StringBuffer.
Ex: StringBuffer sb= new StringBuffer(“durga”);
s1.m1().m2().m3().m4().m5().m6();

* All the method calls will execute left to right.
sb.append(“software”).insert(2,”xxx”).delete(4,7).reverse();
System.out.println(sb); // durgasw
--> duxxxrgasw ---> duxxasw
---> erawtfosaxxud
StringBuilder :
  • It is exactly similar to StringBuffer except all the methods are nonsynchronized methods.
  • When compared with StringBuffer the fallowing are the advantages of StringBuilder.high performance and the operation are fast.
  • Data corruption is possible in the StringBuilder which is the major drawback of StringBuilder, when compared with StringBuffer.
Example:
class Sample
{
public static void main(String a[])
{
StringBuilder sb=new StringBuilder(“surya”);
s.append(“software”);
s.reverse();
s.delete(3,5);
System.out.println(s);
}
}
//surya //suryasw
//erawtfosayrces //erafosayrces

Wrapper Class

The Wrapper classes have introduced for the fallowing two purposes by SUN people.
1. To wrap primitives into object form so that we can handle primitives also just like objects.
2. We can get several utility functions for primitives.
• The fallowing are the wrapper classes.
Type --------- Class
byte ---------> Byte
short ---------> Short
int ---------> Integer
long ----------> Long
float ----------> Float
double ----------> Double
char ----------> Character
boolean ----------> Boolean



Constructors of the Wrapper classes :
• Integer class contains the fallowing two constructors.
Integer i= new Integer(int i);
Integer i= new Integer(String s);
Ex: Integer i= new Integer(10);
Integer i= new Integer(“10”);
Integer i=new Integer(“ten”); x given
RTE: NumberFormatException
I.e., If the String is unable to convert into a number then we will get a RTE saying “NumberFormantException”.
---> Byte b=new Byte(byte b);
---> Byte b=new Byte(String s);
Wrapper Class --------- Constructor Arguments
1. Byte --------------------> byte or String
2. Short --------------------> short or String
3. Integer ---------------------> int or String
4. Long ---------------------> long or String
5. Float ---------------------> float or String or double
Ex: float f= new Float(float f); //10.0f //valid
float f= new Float(String s); //”10.0f” //valid
float f= new Float(double d);//10.0 //valid
6. Double ----------------------> double
7. Character ------------------> char
Ex: Character c=new Character(char c);
Character c=new Character(‘d’); //valid
Character c=new Character(“d”); //invalid
8. Boolean ---------------------> Boolean or String
Ex: Boolean b=new Boolean(true); //valid
(false); //valid
(TRUE); //invalid
(FALSE); //invalid
Boolean b=new Boolean(“viswan”); //false
(“yes”); //false
(“no”); //false
Note: Other than “true” everything should return ‘false’.
Which of the fallowing are valid Boolean declarations?
1. boolean b=true; //valid
2. boolean b=false; //valid
3. boolean b=TRUE; //invalid
4. boolean b=FALSE; //invalid
5. Boolean b=new Boolean(“true”); //valid
6. Boolean b=new Boolean(“false”); //valid
7. Boolean b=new Boolean(“yes”); //valid //false
8. Boolean b=new Boolean(“NO”); //valid // false
9. boolean b=yes; //invalid //Compile time error
10. boolean b=NO; //invalid // Compiletime error
valueOf() method:


• Except character class every wrapper class contain a static valueOf() which can be used for converting a String object to corresponding wrapper object.
Ex: Integer i=Integer.valueOf(“10”); //valid
Integer i=Integer.valueOf(“ten”); //invalid // RTE :NumberFormatException
Boolean b= Boolen.valueOf(“xxx”); //false
valueOf(String):
String object ----------to------------> Wrapper Object
• This is a static method.
• The argument is String only.
• Throws NumberFormatException, if we are unable to convert the String to number.
Ex: Integer i= Integer.valueOf(10); //invalid
Argument is not String ,the Second version of valueOf() method:
• Byte. Short, Integer, Long classes contain second version of valueOf() method which can take a String and radix as arguments.
• First the String converted into decimal form and then that decimal value will be stored in the wrapper object.
Ex1: Integer i=Integer.valueOf(”101100”,2) ;
System.out.println(i);//44 base=radix
Signatures:
1. public static wrapper valueOf(String s)
object
2. public static wrapper valueOf(String s, int radix)
object
Ex2: Long l=Long.valueOf(“12”,5);
System.out.println(l); //7
* totally “36” bases or radixes are valid
xxxValue() methods:-
• All the numeric wrapper classes contains the fallowing methods for “converting wrapperclass object to primitive”.
intVlaue(); byteVlaue(); shortVlaue(); longVlaue(); floatVlaue(); doubleVlaue();
• Each wrapper class contains the above six methods, in total 36 xxxValue() methods are possible.
• These xxxValue() methods are instance methods and no arg methods.
Ex: Double d =new(150,263);
System.out.println(d.byteValue()); // -106
System.out.println(d.shortValue()); //150
System.out.println(d.intValue()); //150
System.out.println(d.longValue()); // 150
System.out.println(d.floatValue()); // 150.263
System.out.println(d.doubleValue()); // 150.263



• Character class contains charValue() method for converting character object to primitive.
Ex: Character ch= new Character(‘a’) ;
Char c=ch.charValue();
System.out.println(c); // a
• Boolean class contain booleaValue() method for converting a Boolean object to Boolean primitive.
Ex: Boolean B=new Boolen(“viswan”);
boolean b=B.charValue();
System.out.println(b); //false
parseXxx() methods:


• Every wrapper class except Character class contain parseXxx() for converting a String object to corresponding primitive.
Ex: String s=”10”;
int i=Integer.parseInt(s);
double d=Double.parseDouble(s); //10.0
long l=Long.parseLong(s);
Wrapperclass--------- parseXxx()
Byte ------------> parseByte(String s)
Short -------------> parseShort(String s)
Integer -------------> parseInt(String s)
Long -------------> parseLong(String s)
Float -----------> parseFloat(String s)
Double ------------> parseDouble(String s)
• Boolean class contain a static method getBoolean() method for converting a string to Boolean primitive.. -----> 1.4 version
String s=”123”;
int i=Integer.parseInt(s);
double d=Double.parseDouble(s);
System.out.println(i); //123
System.out.println(d); //123.0
Boolean b=getBoolean(“viswan”);
System.out.println(b); //false
Second version of parseXxx() :-
• All the integral wrapper classes (byte, short, integer, long) contains second version of parseXxx().
public static primitive parseXxx(String s,int radix)
Ex: int i=Integer.parseInt(“10101100”,2);
System.out.println(i); //172
long l=Long.parseLong(“12”,8);
System.out.println(l); //10
• java support max – radix is 36(base)
System.out.println(Character.MAX-RADIX); //036
toString() method:
1st version:-
• All the wrapper classes contains an instance toString() method for converting wrapper class object to corresponding String object.
• public String toString();
Integer i=new Integer(10);
String s= i.toString();
System.out.println(s); // 10
Boolen B=new Boolean(“surya”);
String s=B.toString();
System.out.println(s);//false


2nd Version:


• Every wrapper class contain a static toString() method for converting a primitive to String object.
• This is available in all wrapper classes and object class also includes Boolean and Character classes.
• public static String toString(10);
Ex: String s1=Integer.toString(10);
System.out.println(s);
String s1=Boolean.toString(true);
String s1=Integer.toString(‘a’);
System.out.println(s1);
System.out.println(s2);
3rd Version:


• Integer and Long classes contain the 3rd version of the toString() method for converting given primitive to String of sprcified radix.
• public satic String toString(30,2);
Ex: String s= Integer.toString(30,2);
System.out.println(s); //”11110”
toString(primitive, int radix)
4th version:
• public static String to xxxString(primitive) //int/long
• The version of toString() is available in the Integer and Long classes only. The possible to xxxString() methods are, toBinaryString, toHexString and tooctalString for converting the given primitive to the corresponding String form.
String s=Integr.toBinaryString(100); //1100100
String s=Integr.toOctalString(100); //144
String s=Integr.toHexString(100); //64
• All the wrapper class objects are immutable and all the wrapper classes are final classes.
• ‘void’ is also one type of wrapper class.
• String class and all the wrapper classes are immutable.
• The fallowing are the final classes.
-->String
--> StrringBuffer
--->Math

AutoBoxing , AutoUnBoxing

AutoBoxing:
• Automatic conversion by the compiler from primitive type to the corresponding object form is called AutoBoxing.
Ex: int i=10; //Compile time error in 1.4 but valid in 1.5
Integer I=i; 
• Compiler first constructs the integer object and then assigned that object to the variable.
AutoUnBoxing:
• Automatic conversion from wrapper class object to primitive type by the compiler is called AutoUnBoxing.
Ex: Integer I= new Integer(10);
int i= I; //CTE :1.4
// valid in 1.5

* The compiler coverts Integer object to primitive and that primitive value will assign to variable i.


* Because of these new autuboxing or auto unboxing features, the importance of wrapper classes is not that much in the 1.5 version.
AutoBoxing in expressions:
Integer y=10;
Integer x=y;
Y++;
System.out.println(x); // 10
System.out.println(y); // 11
System.out.println(x==y); // flase
Wapper class objects are immutable .if you want to perform any changes with those changes a new wrapper class object will create.
Special cases:
case1:
Integer i1=new Integer(10);
Integer i2=new Integer(10); 
System.out.println(i1==i2); //false
Case2:
Integer i1=new Integer(10);
Integer i2=10;
System.out.println(i1==i2); //false
Case3:
Integer i1=100;
Integer i2=100; 
System.out.println(i1==i2); //true
Case4:
Integer i1=1000;
Integer i2=1000; 
System.out.println(i1==i2); //false
In the case of autoboxing compalier won’t create any new object If an existing already created object mapped with the reqired one . the existing object should be created bt the autoboxing only.
This poosibility will occur in the following cases.
1.By using autoboxing. If it is required to create a new wrapper object, other wise compiler won’t create any new object, if already an object is present in the fallowing cases. these Objects are Boolean and Byte.
2. Character object ranges from 0 to 127 ------> (‘\u0000’ to ‘\u0007f’).
3. For the integer and short if the value is less than or equal to 127.
4. For the long of the value is less than or equal to 127 L .
But Long l=10; //invalid
CTE: incompatable types
Found:int , req: java.lang.Long
Similarly Float f= 10; //invalid - CTE: incompatable types
Found: int, req: java.lang.Float

Case5:
Boolean b1=true;
Boolean b2=true;
System.out.println(b1==b2); // true
Case6:
Boolean b3=flase;
Boolean b4=flase;
System.out.println(b3==b4); // true

Special case:
Example:
class Sample
{
static Integer I1=10; ---->I1: Initialized
public static void main(String a[])
{
m1(I1); ---> I1 : auto unboxing
}
public static void m1(int i)
{
Integer I2=i; ----> I2: auto boxing
System.out.println(I2); //10
}
}
above example executes fine.
But
class Sample
{
static Integer I1; // not Initialized
public static void main(String a[])
{
m1(I1); // null pointer exception
}
public static void m1(int i)
{
Integer I2=i; 
System.out.println(I2); 
}

Static variables by default initialized with null, which can’t be autoboxing/autounboxing.Hence Run time exception.

overloading when combining with widening and Autoboxing:
class Text
{
static void m1(Integer x)
{
System.out.println(“integer”);
}
static void m1(long l)
{
System.out.println(“long”);
}
public static void main(String arg[])
{
int i=5;
m1(i); //long
}
}
when comparing widening with autoboxing compiler always prefers widening in order to provide the sport for legacy code.
Over loading in case of widening with var-arg method:
Class sample
{
static void m1(int I,int j)
{
System.out.println(“int, int”);
}
static void m1(byte… b)
{
System.out.println(“byte arg”);
}
public static void main(String arg[])
{
byte b=5;
m1(b,b);
}
} // in tint
widening dominates var-arg method .compiler will give the precedence for widening over var-arg method.
Autoboxing vs var-args:
Class Sample
{
static void m1(Byte b)
{
System.out.println(“byte”);
}
static void m1(byte… b)
{
System.out.println(“byte arg”);
}
public static void main(String arg[])
{
byte b=5;
m1(b);
}
}
the compiler prefers autoboxing over var-args
If there is no other method matched,then only var-arg method always seeks to least priority.
Conclusion:
The compiler always gives the precedence in the following order for resolving over loading methods.
1.wid4ening
2.auto boxing & unboxing
3.var- args
Special cases:
Class Sampe

public static void m1(Long l)
{
System.out.println(“long”);
}
public static void main(String arg[])
{
byte b=5;
m1(b);
}
}

In java widening followed by autoboxing is not allowed.Hence the above code raise a CTE saying m1(java.lang.long) in sample can not be applied to (byte).
i.e Byte --------> Long is not possible.
But byte ----->long is possible.
Widening followed by autoboxing is not allowed. But the reverse is allowed in java i.e autoboxing follwed by widening is possible.
Class Sample
{
static void m1(Object o)
{
System.out.println(“object”);
}
public static void main(String arg[])
{
byte b=5;
m1(b); // object
}
}
i.e byte -----> Byte -----> Object
i.e Here autoboxing is followed by widening .

class Samle
{
static void m1(byte… b)
{
System.out.println(“byte……”);
}
static void m1(byte b,byte… b1)
{
System.out.println(“byte, byte….”);
}
public static void main(String arg[])
{
byte b=5;
m1(b); // CTE saying reference to m1 is ambiguous.
}
}
Here both methods are matched because of var-args feature.Hence compailer can’t give any precedence results in CTE
Static variable by default initialized with null,which can’t be autoboxing /autounboxing 

enum

It defines a list of named constants.This is interdused in 1.5 version.
Java enum is powerful than c,c++ enums because java enum may contain methods ,constructors and instance variables in addition to constants.But c,c++ enum contain only constants.
Example:
enum Month
{
Jan,Feb,Mar,Apr…….;
}
Example:
enum Beer
{
KF,RC,H5,H2,…….;
}
No variables in enum.At the end ( ; ) no need to specify (optional)
Use:we can reduce the number of bugs by using enumeration because We are providing a set of predefined values for the variables.
Enum Example code:
enum Month
{
Jan,Feb,Mar,Apr;
}
class Sample
{
public static void main(String arg[])
{
Month m=Month.Mar;
System.out.println(m); // Mar
}
}
  • We can keep enum outside the class or inside the class.If we are declaring enum outside the class,the allowed modifiers are public ,<default>.we can declare enum with in a class the allowed modifiers are public ,<default>,protected,private.
  • We never allowed to declare enum inside a method,violation leads to compile time error saying enum type must not be local.
  • Enum types is allowed to used as argument for the switch statement.
Example:
Enum Beer
{
KF,RC,H5;
}
class Sample
{
public static void main(String arg[])
{
Beer b= Beer.KF;
Switch(b)
{
case KF:
System.out.println(“too Bitter”);
break;
case RC:
System.out.println(“too Hot”);
break;
case H5:
System.out.println(“too strong”);
break;
}
}
}
until 1.4 version the allowed arguments for the switch statement are byte,short,int,char.But 1.5 version onwords in addition to these arguments Byte,Short,Character,Integer and enum also.
Values() method:
Enum contains a predefined method values to list the constants available in that enum.
Example :
enum Month
{
Jan,Feb,Mar,Apr;
}
class Client
{
public static void main(String arg[])
{
Month[] m=Month.values();
for(Month m1:m)
{
System.out.println(m1); // Jan,Feb,Mar,Apr
}
}
enum never participated in inheritance hierarchy because every enum class implicitly extends java.lang .enum .Thats why we never allowed to create a child classfor the enum.As Month enum already extends java.lang.enum hence it never allowed to extend any other.
Enum Month extends Some ---> not possible
If we are writing any enum it is extending java.lang.enum class.Hence it never extends any thing else.So inheritance concept not applicable for enums.
Example:
Enum Beer
{
KF(65),RC(50),H5(100),KO;
int price;
Beer(int price)
{
this.price=price;
}
public int getPrice()
{
return price;
}
Beer()
{
this.price=100;
}
}
class Sample
{
public static void main(String arg[])
{
Beer b=Beer.KF;
System.out.println(b); //KF
System.out.println(Beer.KF.ordinal());
System.out.println(b.price); //65
System.out.println(b.getPrice()); //65
Beer[] s=Beer.values();
for(Beer s1:s)
{
System.out.println(s1+”……….”+s1.getPrice());
}
}
}
• When ever enum is loaded into the memory, all the enum constants will be assigned and JVM calls Constructor automatically. The programmer is not allowed to call enum constructor explicitly.
• The Constructors of enum can be overloaded if the enum contain both enum constants, instance variables, the first line should be enum constants and ends with semicolon.
i.e. 
enum Beer
{
KF, RC //invalid ; missing
int price;
}
enum Beer
{
int price; //invalid because the 1st stmt should be enum constants.
KF, RC;
}
enum Beer
{
KF, RC;
int price; //valid
}

Ordinal Value

• The position of enum constant is important and indicated by their ordinal values. We can ordinal value for any enum constant by the fallowing method.

Public final int ordinal();
Ordinal value starts from zero(0).

Enum Month
{
JAN,FEB;
public static void main(String a[])
{
Month[] m=Month.values();
for(Month m1:m)
System.out.println(m1);//JAN,FEB
}
}//Save:Month.java, Run:Java Month
  • So just like a normal class, we can run enum also.
System.out.println(Month.JAN==Month.FEB); //false
  • So we can compare the constants declared in enum. Otherthan ‘= =’operators, remaining <=, >=,<,> will gave CTE.
  • Duplicate constants can’t be declared. So, constants are unique.

enum Month
{
Jan,Feb,Jan; //invalid,CTE:Jan already defined
}

But

enum Month
{
Jan,Feb,JAN; //valid, due to case sensitive jan!=JAN
}

Comparable Interface and clonable interface

Comparable Interface:
This is present in java.lang.package
Contains the following one method.
1.public int compareTo(Object o)
if returns –ve integer if o1 has to place before o2.
If returns +ve integer if o1 has to to place after o2.
If returns zero then o1 and o2 are equal.
All the wrapper classes and string class already implemented comparable interface. But the StringBuffer doesn’t implement comparable interface.
Comparable Interface Example:
Interface comparable
{
public int compareTo(Object o)
{
TreeSet t=new TreeSet(0;
t.add(“a”);
t.add(‘z”);
System.out.println(t); // a,z (:: z.compareTo(“a”);)
System.out.println((“a”).compareTo(“z”)); //-25 
System.out.println((new Integer(10).compareTo(new Intege(1)); // +1
}
}|
Marker or Tag Interface:
If an interface is marked for some ability such type of interfaces are called Marker interfaces.
Ex: clonable,serializable
If an interface with out any method obviously accept ass marker interface.
Eventhough interface contains some methods,still we can consider as marker interface .If it is marked for some ability.
Ex:Comparable interface.
Intreger i1=new Integer(10);
Integer i2=new Integer(20);
System.out.println(i2.compareTo i1); // -1
System.out.println(i1.compareTo i2); // +1
System.out.println(i1.compareTo i1); // 0
System.out.println(i1.compareTo(“a”)); // CTE nullpointer exception


Cloneable interface:
Uptaining exact copy of a plant ,a bird,an animal or a human being is called cloning.
Cloning in programming uptaining bit wist exact copy of an object is called cloning.
cloning Example:

Class sample() implements cloneable
{
Int i=10;
Public static void main(string args[])throwsClone notSupportedEexception
{
Sample s1=new sample();
Sample s2=s1;
Sample s3=(sample)s1.clone();
S1.i=1000;
System.out.println(s3.i);
System.out.println(s1==s3);
we should type cast otherwise
CTE:in compatable types
Found: Object reqired=sample
The class must implements cloneable interface otherwise at runtime clone() results cloneNotsupportException
Example:
Class sample implements clonable
{
Int i=10;
Public static void main(string[]args)throws cloneNot support Exception
{
Object o=new object();
Object o2=o.clone();
}
CTE:clone() has protected access in java.lang.object
The protected numbers we can access, from with in the same package or from outside package but from outside package,the protected number can be accessed b using child class reference only.ie we can’t use parentclass reference to access protected number from outside package,validation leadsto CTE.
clone() method:
Protected object clone() throws clone not supported exception.
This method can used to prouduced exactly duplicate copy of an object..
All the objects can’t produce cloned object ,only clonable objects can produce duplicate copies .
An object is said to be conable if and only if the corresponding class implements clonable interface.
By using the folling object class clone() method we can produced cloned objects
Protected object clone() throws clone supported exception
CheckedException so we should handle by using try catch or throws to the caller by using throws clause.

Shallow cloning Example:
Class Student implements cloneable
{
String name;
String age;
Student(String name,String age)
{
This.name;
This.age=age;
]
Public Object clone()throws cloneNotSupportedException
{
Return this;
}
}
Class Student cloneDemo
{
Student s1= new Student(“hai”,”22”);
Student s2= (Student)s1.clone();
S2.name=”abc”;
System.out.println(s1.name);
Public static void main (String ar[])
{
StudentCloneDemo s1= new Student cloneDemo();
}
}
Deep cloning example:
Class Student implements cloneable
{
String name;
String age;
}
Student(String name ,String age)
{
This.name=name;
This.age=age;
}

Public Object clone(0throws CloneNotSuport Exception
{
try
{
ByteArrayOutputStream bas=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(bas);
Oos.writeObject(this);
ByteArrayInputStream bias=new ByteArrayInputStream(bas.toByteArray());
ObjectInputStream oos=new ObjectInputStream(bias);
Return ois.readObject();
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
class DcloneDemo
{
DcloneDemo()throws CloneNotSuportException
{
Student s1=new Student(“hello”,”200”);
Student s2=(Student)s1.clone();
S2.name=”java”;
System.out.println(s1.name);
Public static void main(String[] arg)
{
new DcloneDemo();
}
}

Thank you for visiting Java Examples.