Beruflich Dokumente
Kultur Dokumente
Instance Variables
Start Comparing Local and Instance variable...
1. Local variables must be initialized before use while it is not necessary to initialize Instance
variables
Instance variables always get a default value.
Local variables do not get default value. If you use local variable without initializing it then there
will be a compiler error.
Declaration
Instance Variables are declared inside class.
Hash Set
import java.util.HashSet;
import java.util.Iterator;
/**
*
* @author Darur venu gopal
* This class Demonstrates ability to store values in HashSet and Retrieve.
* First Step Store some values in HashSet,
* Observe the Storage. Hashset Stores the values randomly.
* Hashset stores no duplicate values, and stores in random order.
*
*/public class HashSetDemo {
/**
* This method add values (Label number) to a hashSet.
* @return
*/
public HashSet addValuesInHashSet( ){
HashSet hashSet = new HashSet();
for( int i = 0; i< 100; i++ ){
String name = "LABEL";
String valueToAdd = name + i;
hashSet.add( valueToAdd );
}
return hashSet;
}
/**
* Iterate and hashset. and print all the values in this Hashset.
* @param hashSet
*/
public void retrieveHashSet( HashSet hashSet ){
Iterator iterator = hashSet.iterator();
while ( iterator.hasNext() ){
String labelNo=( String ) iterator.next();
System.out.println( "LabelNo: " + labelNo );
}
}
..
LabelNo: LABEL76
LabelNo: LABEL75
LabelNo: LABEL74
LabelNo: LABEL73
LabelNo: LABEL72
LabelNo: LABEL71
LabelNo: LABEL70
LabelNo: LABEL69
LabelNo: LABEL68
LabelNo: LABEL67
LabelNo: LABEL66
LabelNo: LABEL65
LabelNo: LABEL64
LabelNo: LABEL63
LabelNo: LABEL62
LabelNo: LABEL61
LabelNo: LABEL60
LabelNo: LABEL59
LabelNo: LABEL58
LabelNo: LABEL57
LabelNo: LABEL56
LabelNo: LABEL55
LabelNo: LABEL54
..
..
import java.util.Iterator;
import java.util.TreeSet;
/**
*
* @author Darur venu gopal
* This class Demonstrates ability to store values in TreeSet and *Retrieve.
* First Step Store some values in TreeSet,
* Observe the Storage. Treeset Stores the values in a particular sorted *order.
*.*.
*
*/
public class TreeSetDemo {
/**
* This method add values (Label number) to a TreeSet.
* @return
*/
public TreeSet addValuesInTreeSet( ){
TreeSet treeSet = new TreeSet();
for( int i = 0; i< 20 ; i++ ){
Integer number = new Integer( i );
treeSet.add( number);
}
return treeSet;
}
/**
* Iterate and treesett. and print all the values in this Treeset.
* @param treeSet
*/
public void retrieveHashSet( TreeSet treeSet ){
Iterator iterator = treeSet.iterator();
while ( iterator.hasNext() ){
int labelNo=( ( Integer ) iterator.next() ).intValue();
System.out.println( "LabelNo: " + labelNo );
}
}
Output :
LabelNo: 0
LabelNo: 1
LabelNo: 2
LabelNo: 3
LabelNo: 4
LabelNo: 5
LabelNo: 6
LabelNo: 7
LabelNo: 8
LabelNo: 9
LabelNo: 10
LabelNo: 11
LabelNo: 12
LabelNo: 13
LabelNo: 14
LabelNo: 15
LabelNo: 16
LabelNo: 17
LabelNo: 18
LabelNo: 19
//Java.util.LinkedHashSet
//Java Collections -LinkedHashSet
//LinkedHashSet implements Set Interface
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.TreeSet;
/**
*
* @author Darur venu gopal
* This class Demonstrates ability to store values in LinkedHashSet and Retrieve.
* First Step Store some values in LinkedHashSet,
* Observe the Storage. LinkedHashset Stores the values in order of entry.
*
*/
public class LinkedHashSetDemo {
/**
* This method add values (Label number) to a TreeSet.
* @return
*/
public LinkedHashSet addValuesInLinkedHashSet( ){
LinkedHashSet linkedHashSet = new LinkedHashSet();
// observe the order of entry, while retieve the same order of entry is guaranteed.
linkedHashSet.add( "DARUR" );
linkedHashSet.add( "ARORA" );
linkedHashSet.add( "SAVANT" );
linkedHashSet.add( "INTELLIGENT" );
linkedHashSet.add( "APPLICATIONS" );
linkedHashSet.add( "IBM MACHINES" );
linkedHashSet.add( "SUN MICRO SYSTEM" );
linkedHashSet.add( "GREAT GATES" );
return linkedHashSet;
}
/**
* Iterate and hashset. and print all the values in this Hashset.
* @param linkedHashSet
*/
public void getLinkedHashSet( LinkedHashSet linkedHashSet ){
Iterator iterator = linkedHashSet.iterator();
while ( iterator.hasNext() ){
String label= ( String) iterator.next() ;
System.out.println( "WORD: " + label );
}
System.out.println( "THUS ORDER OF ENTRY IS SAME AS ORDER YOU ENTERED" );
}
Output :
WORD: DARUR
WORD: ARORA
WORD: SAVANT
WORD: INTELLIGENT
WORD: APPLICATIONS
WORD: IBM MACHINES
WORD: SUN MICRO SYSTEM
WORD: GREAT GATES
THUS ORDER OF ENTRY IS SAME AS ORDER YOU ENTERED
import java.util.ArrayList;
import java.util.Iterator;
// Darur
public class ArraylistDemo {
return arrayList;
}
//
public void printValuesInArrayList( ArrayList arrayList ){
System.out.println( "--------USING FOR ITERATOR------------" );
Iterator iterator = arrayList.iterator();
while( iterator.hasNext() ){
String name = ( ( String ) iterator.next() ).toUpperCase();
System.out.println( "Name: " + name );
}
System.out.println( "--------USING FOR ITERATOR------------" );
}
//
public void printValuesInArrayListUsingForLoop( ArrayList arrayList ){
System.out.println( "--------USING FOR LOOP START------------" );
for( int i = 0 ; i < arrayList.size() ; i++ ){
String name = ( ( String ) arrayList.get( i ) ).toUpperCase();
System.out.println( "Name: " + name );
}
System.out.println( "--------USING FOR LOOP END------------" );
}
Example
import java.util.Iterator;
import java.util.Vector;
return vector;
Output :
--------USING FOR ITERATOR------------
Name: VNU
Name: RAVI
Name: HARANATH
Name: DEV
Name: SREERAM
Name: GIRI
Name: SREEDHAR
Name: JANARDHAN
Name: KRISI
Name: SISI
Name: VASUDEV
Name: MPRAVEEN
Name: KPRAVEEN
Name: SIDHU
Name: 95MECHVASAVI99
Name: SHAHENSHA
Name: ENGINE OIL
Name: MECHANICAL DRAWING
Name: HEAD OF MECHANICAL DEPARTMENT
Name: VASAVI COLLEGE OF ENGINEEERING
Name: RAKESH RAVI DEV SLIDED TO ELECTRONICS
--------USING FOR ITERATOR------------
--------USING FOR LOOP START------------
Name: VNU
Name: RAVI
Name: HARANATH
Name: DEV
Name: SREERAM
Name: GIRI
Name: SREEDHAR
Name: JANARDHAN
Name: KRISI
Name: SISI
Name: VASUDEV
Name: MPRAVEEN
Name: KPRAVEEN
Name: SIDHU
Name: 95MECHVASAVI99
Name: SHAHENSHA
Name: ENGINE OIL
Name: MECHANICAL DRAWING
Name: HEAD OF MECHANICAL DEPARTMENT
Name: VASAVI COLLEGE OF ENGINEEERING
Name: RAKESH RAVI DEV SLIDED TO ELECTRONICS
--------USING FOR LOOP END-----------
-Java.util.LinkedList
Java Collections -LinkedList
Example
import java.util.Iterator;
import java.util.LinkedList;
/**
* LinkedList implements interface. Implements all optional list operations,
* and permits all elements (including null). In addition to implementing the List interface,
* provides uniformly named methods to get, remove and insert an element ( addFirst, addLast)
* at the beginning and end of the list.
* linkedlists would be used as a stack, queue, or double-ended queue (deque).
* Above is extract from www.SUN.com
* CHAITANYA KANDIKONDA
* @author Darur
*
*/
public class LinkedListDemo {
public LinkedList addValuestoLinkedList( ){
LinkedList linkedList = new LinkedList();
linkedList.add( 1 );
linkedList.add( 2 );
linkedList.add( 7 );
linkedList.add( 7 );
linkedList.add( 8 );
linkedList.add( 3 );
linkedList.add( 4 );
linkedList.add( 5 );
linkedList.add( 6 );
linkedList.add( 7 );
return linkedList;
}
// add first element
// add last element and print
public void PrintLinkedList( LinkedList linkedList ){
linkedList.addFirst( 0 );
linkedList.addLast( 10 );
Iterator iterator = linkedList.iterator();
while( iterator.hasNext() ){
System.out.println( "THE VALUE: " + iterator.next());
}
}
Output :
THE VALUE: 0
THE VALUE: 1
THE VALUE: 2
THE VALUE: 7
THE VALUE: 7
THE VALUE: 8
THE VALUE: 3
THE VALUE: 4
THE VALUE: 5
THE VALUE: 6
THE VALUE: 7
THE VALUE: 10
Java.util.Properties
Java Collections -Properties
Example
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
/**
* This class Demonstrates a way to use properties.
* In huge applications projects may need to have many things as configurable properties,
* this may be because the business needs.
* It is a very bad habbit to hard code the values in the program.
* It's best practise to use properties in a property file.
*
* Also most desginers will have this in mind for any application.
* Generally the properties loaded from the file are kept in the application scope.
* So the properties will be loaded once when the application triggers a start point.
* Web environment, best way to initiliaze properties, is when
* Application Context is started.
* Write a class which implements HttpContextListener, call your property initializer in context
startup.
*
*
* Your File may have duplicate entries, generally you have to avoid duplicate entries
* in the file
* @author Darur
*
*/
public class PropertiesDemo {
//
/**
* @return
*/
public static Properties readPropertiesFromFile( String fileName ) {
Properties properties = new Properties();
InputStream inStream;
try{
inStream = new FileInputStream( new File( fileName ) );
properties.load(inStream);
}catch( FileNotFoundException fileNotFoundException ){
System.err.println( "FILE NOT FOUND EXCEPTION WHILE READING THE FILE: "+ fileName +
"\n" + fileNotFoundException);
}catch( IOException ioException ){
System.err.println( "IOEXCETION WHILE READING THE FILE: " + fileName + "\n" +
ioException);
}
return properties;
}
/**
* add all the prope
* @param args
*/
Output :
usertype : premium
port : 1046
driver : jdbc
connectionport : 127.0.0.1
------------------------------------------------------------------------------------
usertype = premium
driver = jdbc
connectionport = 127.0.0.1
port = 1040
port = 1041
port = 1042
port = 1043
port = 1044
port = 1045
port = 1046
Save this in file and process in main method
------------------------------------------------------------------------------------
**
* We will struggle in parsing java dates to required format.
* Please use this class run in your environment by changing package name you will get
* All the formats of the dates. THIS IS THE BEST EXAMPLE FOR PARSING DATES
*/
import java.io.Serializable;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Constructor which accepts a java.util.Date as input
* @param date
*/
public IforeRunnerDateExample(java.util.Date date) {
setTime(date.getTime());
}
/**
* Expects a string in MMddyyyyhhmmss format to parse into a IforeRunnerDateExample
* @param dateTimeString
* @throws ParseException
*/
public IforeRunnerDateExample(String dateTimeString) throws ParseException {
this.setTime(dateTime.parse(dateTimeString).getTime());
}
/**
*
*/
public IforeRunnerDateExample() {
super();
}
/**
* @param arg0
*/
public IforeRunnerDateExample(long arg0) {
super(arg0);
/**
*
* @return date string in MMddyyyy format
*/
public String getyyMMddString() {
return yyMMdd.format(this);
}
/**
*
* @return date string in hhmm format
*/
public String gethhmmString() {
return hhmm.format(this);
}
/**
*
* @return date string in MMddyyyy format
*/
public String getMMddyyyyString() {
return date.format(this);
}
/**
*
* @return date string in hhmmss format
*/
public String getHHmmssString() {
return time.format(this);
}
/*
* @return date String in yyyymmddhhMM format
*/
public String getyyyymmddhhMMString(){
return yyyymmddhhMM.format(this);
}
/*
* @return date String in yyyymmddhhMM format
*/
public String getyyMMddhhmmssString(){
return yyMMddhhmmss.format(this);
}
/**
* @return date String in mmyy format
*/
public String getMMyyString(){
return MMyy.format(this);
}
/**
*
* @return Date String in hhmm format
*/
public String getHHmmString(){
return hhmm.format(this);
}
/*
* @return date String in yyyymmdd format
*/
public String gethhmmssyyyyMMddString(){
return hhmmssyyyyMMdd.format(this);
}
/*
* @return date String in yyyymmdd format
*/
public String getMMddyyString(){
return MMddyy.format(this);
}
/**
*
* @param mmyy
* @return
* @throws ParseException
*/
public static IforeRunnerDateExample getMMyy(String MMyy)throws ParseException {
return new IforeRunnerDateExample(MMyy.parse(MMyy));
}
public static IforeRunnerDateExample getyyyymmdd(String yyyymmdd)throws ParseException {
return new IforeRunnerDateExample(yyyymmdd.parse(yyyymmdd));
}
} catch (Exception e) {
}
System.out.println( IforeRunnerDateExample.getdateFormatmmddyyyy());
}
}
public class WrapperDemo {
public static void main( String [] args ){
System.out.println( "--------------");
System.out.println( toDoubleValue );
System.out.println( toIntValue );
System.out.println( toFloatValue);
System.out.println( toByteValue );
System.out.println( "--------------");
//short shortValue()
short getShortValue = toInt.shortValue();
//int intValue()
int getIntValue = toInt.intValue();
//long longValue()
long getLong = toInt.longValue();
//float floatValue()
float getFloat = toDouble.floatValue();
//double doubleValue()
double getDouble = toDouble.doubleValue();
System.out.println( getDouble );
System.out.println( getIntValue );
}
OUT PUT
--------------
121212.3
1212
0.112
112
--------------
2.718281828459045
16
Java.util.LinkedHashMap
Java Collections -LinkedHashMap
LinkedHashMap implements Map Interface
Example
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashMap;
Output :
import java.util.Enumeration;
import java.util.Hashtable;
}
}
Output :
Name : Venugopal Darur
State : Andhra Pradesh
City : Hyderabad
College : Vasavi College Of Engineering
RollNo : 639
Country : India
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
}
}
---------------------------------------------------------------------------------------------------------------------------------
------
Output :
RollNo : 639
City : Hyderabad
Name : Venugopal Darur
College : Some University
Country : India
State : Andhra Pradesh
null : India
// HashMap can store one Null Value, use this example to show that HashMap can use one null
value as key.
// Hashtable cannot store one null value as key
Java.util.TreeMap
Java Collections -TreeMap
Example
import java.security.KeyStore.Entry;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
// Darur VenuGopal
public class TreeMapDemo {
/**
* Build a TREE MAP
* compatible to java1.5, but not suggested to use since this is not using java generics
*
* Put a String key and String value
*/
return treeMap;
}
/**
* Get the MAP key Values,
* Get the value assigned to a key
* print the key and value
* @param treeMap
*/
public void printTreeMap( TreeMap treeMap ){
Iterator iterator = treeMap.entrySet().iterator();
while( iterator.hasNext() ){
Map.Entry keyEntry = (Map.Entry ) iterator.next();
String key = ( String )keyEntry.getKey();
System.out.print( " KEY : " + key);
String value = (String) treeMap.get(key);
Output :
KEY : URL The Value for the key: HTTP://WWW.IFORERUNNER.COM
KEY : URL1 The Value for the key: HTTP://WWW.SUN.COM
KEY : URL2 The Value for the key: HTTP://WWW.JAVASOFT.COM
KEY : URL3 The Value for the key: HTTP://WWW.JAVA.COM
KEY : URL4 The Value for the key: HTTP://WWW.SERVERSIDE.COM
KEY : URL5 The Value for the key: HTTP://WWW.HIBERNATE.ORG
KEY : URL6 The Value for the key: HTTP://WWW.GOOGLE.COM
KEY : URL7 The Value for the key: HTTP://WWW.IFORERUNNER.COM
KEY : URL8 The Value for the key: HTTP://WWW.IFORERUNNER.COM
OOPs Concepts
Encapsulation
The ability to change the behavior of your code without changing your
implementation code is a key benefit of encapsulation. You want to hide
implementation details behind a public programming interface. By interface,
we mean the set of accessible methods your code makes available for other
code to call-in other words, your code's API. By hiding implementation details,
you can rework your method code without forcing a change in the code that
calls your changed method.
2. Make public accessor methods, and force calling code to use those
methods rather than directly accessing the instance variable.
3. For the methods, use the JavaBeans naming convention of set and get.
b.setSize(25);
System.out.println("Size:"+b.getsize());
}
c:/>javac Box.java
c:/>javac BoxMain.java
c:/>java BoxMain
Output:
Size:25
OOPs Concepts
Polymorphism
Polymorphism allows the software developer to reuse names as well as code. Polymorphism is
a term that describes a situation where one name may refer to different methods. Polymorphism
is the ability of a programming language to process object differently depending on their datatype
or class.
Polymorphism is the capability of method to do different things based on the object that it is acting
upon.
The meaning of the word polymorphism is one name, many forms, in java in the form of multiple
methods with the same name
Compile-time-Polymorphism
In compiletime polymorphism the compiler will identify which method to be invoked during
compile time itself and statically link it (Static linking or static binding). Method overloading is a
best example of compile time polimorphism. Method overloading occurs when several methods
have same names with different method signature.overloading of method is determined at the
compile time. Overloaded methods let you reuse the same method name in a class, but with
different arguments (and optionally, a different return type).
The rules are simple:
Legal Overloads
Example1
class Adder {
public int addThem(int x, int y) {
return x + y;
}
// Overload the addThem method to add doubles instead of ints
public double addThem(double x, double y) {
return x + y;
}
}
In the preceding TestAdder code, the first call to a.addThem(b,c) passes two ints to the method,
so the first version of addThem()-the overloaded version that takes two int arguments-is called.
The second call to a.addThem(22.5, 9.3) passes two doubles to the method, so the second
version of addThem()-the overloaded version that takes two double arguments-is called.
Runtime-Polymorphism
The runtime polymorphism is achieved through function overriding. Function overriding means
suppose you have two classes one is super class and another on is sub class. If both classes
have a method which has the same return type as well as same number and type of argument list
then the function is said to be overridden. This scenario is said to be runtime polymorphism
because JVM will decide at runtime that which version of the function either the one which is
super class or the one which is in sub class.
}
}
both the classes have details() method. But which version it displays will be decided based on the
object type. The Doctor class creator might have decided that for the purposes of polymorphism,
all Doctor subtypes should have a details() method defined in a unique, specific way.
Polymorphically, when someone has an Doctor reference that refers not to Doctor instance, but to
a Doctor subclass instance (here Dentist), the caller should be able to invoke details() on the
Doctor reference, but the actual runtime object (say, a Dentist instance) will run its own specific
details() method.
" The argument list must exactly match that of the overridden method. If they don't match, you
can end up with an overloaded
" The return type must be the same as, or a subtype of, the return type declared in the original
overridden method in the superclass.
" The access level can't be more restrictive than the overridden method's. That is the super class
method's access level should always either public or protected but it should not be private.
Because private methods cannot be inherited
" The access level can be less restrictive than that of the overridden method.
" Instance methods can be overridden only if they are inherited by the subclass.
" A subclass within the same package as the instance's superclass can override any superclass
method that is not marked private or final.
" You cannot override a method marked final.
" You cannot override a method marked static.
" If a method can't be inherited, you cannot override it. Remember that overriding implies that
you're reimplementing a method you inherited
Example
Base.java
}
}
Sub1.java
}
public void details()
{
System.out.println("This is subclass1");
}
}
Sub2.java
}
public void prnt()
{
System.out.println("This is another method of Sub2 class");
}
}
MainClass.java
{
String h ="Hello";
Base b= new Base(h);
b.display();// executes base class version of display() method
b=new Sub1();
b.display(h);// executes sub1 class display() method
//b.details(); compiler error since base class doest know about details() method so it will not
execute
b=new Sub2();
b.display(h);// executes sub2 class display() method
}
}
An EXCEPTION, is an abnormal event in a program, that means an Exception breaks the normal
flow of execution. There are several reasons which leads to exceptions including hardware
failures, resource exhaustion. When an exceptional event occurs in a Java program the normal
flow will be break down and then the control has to go into some other place, this is something
called as an Exception that is "thrown." The code that's responsible for doing something about the
exception is called an "Exception Handler," and it "catches" the thrown exception.
We use the try and catch keywords. The try is used to define a block of code in which exceptions
may occur. This block of code is called a guarded region (which means "risky code is there in this
block"). One or more catch clauses match a specific exception to a block of code that handles it.
In the above class the block which is enclosed by try keyword is guarded region. That is we are
explicitly saying to the JVM that here some abnormal event may occur and the block which are
enclosed with the catch keyword is called Exception handler block. Whenever an abnormal event
occurred then the control will go into this block. Notice that the catch blocks immediately follow
the try block. This is a requirement; if you have one or more catch blocks, they must immediately
follow the try block. Additionally, the catch blocks must all follow each other, without any other
statements or blocks in between and also, the order in which the catch blocks appear matters.
Suppose lets say the execution is started, the control is entered into try block an exception has
occurred at line one of try block then the control will immediately pass into one of the its catch
blocks and executes. Here the remaining lines of the try block will not execute. After executing a
catch block the control will never come again into the try block instead it just executes statements
after the catch blocks. Here when an exception occurred it checks its type and if a match is found
at one of the catch blocks, then that catch block will be executed. For example an exception has
occurred in try block which is of type MyExceptionOne then the control checks the matching catch
block here the matched catch block is first catch block itself. So it'll be executed. If the try block is
executed without any exceptions then the catch blocks will not be executed. The statements after
the catch blocks will be executed. Example
Program that generates Arithmetic Exception
class TestException
{
public static void main(String args[])
{
int i=15;
double d;
try
{
for(int j=0;j<=5;j++)
d=i/j;
}
catch(Exception e){
System.out.println("The generated Exception is: "+e);
}}}
We know that when 15 is divided by non zero value it'll give some result but when it is divided by
zero the result we may not predict. So we have kept that code in try block and handled in catch
block. If you execute above code the following out it gives.
Output:
package venu.darur.gopal.examples.java.IO.FileWriter;
import java.io.FileWriter;
import java.io.IOException;
Java Collections
Examples
/**
*
* @author Venugopal Darur
* Practical way to use String Buffer in Java is explained.
* It is always efficient to use StringBuffer when we append
* more than 5 strings.
* For example
* if we add 100 Strings concatenation it will tak more time to execute
* But if we use a Stringbuffer in comparitively very less.
* In interviews you need answer this, instead of saying briefly
* Mutable or Immutable no one understands.
*
* Please say the difference between String and StringBuffer is performance when
* concatenating more strings.
* Using StringBuffer saves us more time and in production environments
* recommend Stringbuffer to String.
*
*/
public class StringBufferDemo {
public static void main( String [] args ){
// Time taken for String concatenation.
String bufferString = "S";
double startTime = System.currentTimeMillis();
bufferString=stringAddition(bufferString);
double endTime = System.currentTimeMillis();
System.out.println( (endTime-startTime)/100);
// Add this String for 100 times using String addition
startTime = System.currentTimeMillis();
bufferString = "StringBuffer";
bufferString=stringBufferAddition(bufferString);
endTime = System.currentTimeMillis();
System.out.println( (endTime-startTime)/100);
bufferString = "StringBuilder";
bufferString=stringBuilderAddition(bufferString);
endTime = System.currentTimeMillis();
System.out.println( (endTime-startTime)/100);
// See the output time there is huge difference
}
/**
* StringConcatenation
* @param bufferString
* @return
*/
public static String stringAddition( String bufferString ){
for( int i =0; i<=25; i++ ){
bufferString = bufferString+""+bufferString;
}
return bufferString;
}
/**
* 1 Construct StringBuffer Example Method
* 2 Convert StringBuffer to String
* @param bufferString
* @return
*/
public static String stringBufferAddition( String bufferString ){
StringBuffer stringBuffer = new StringBuffer();
for( int i =0; i<=10000; i++ ){
//simpple append method is used
stringBuffer.append(bufferString);
}
//convert StringBuffer to String
bufferString=stringBuffer.toString();
return bufferString;
}
/**
* Difference between StringBuffer and StringBuilder is synchronization
* 1 Construct StringBuilder Example Method
* 2 Convert StringBuilder to String
* @param builderString
* @return
*/
public static String stringBuilderAddition( String builderString ){
StringBuilder stringBuilder = new StringBuilder();
for( int i =0; i<=10000; i++ ){
//simpple append method is used
stringBuilder.append(builderString);
}
//convert StringBuilder to String
builderString=stringBuilder.toString();
return builderString;
}
/**
* output of the program in our local machine
*
* 6.57 shows less performance
* 0.0 shows More performance
* 0.16 shows little more performance
*
*/
Serialization
Serialization is the process of saving an object onto a storage medium (such as a file, or a
memory buffer) or to transmit it across a network connection link, either in binary form, or in some
human-readable text format such as XML. The series of bytes or the format can be used to re-
create an object that is identical in its internal state to the original object (actually a clone).
This process of serializing an object is also called deflating or marshalling an object. The
opposite operation, extracting a data structure from a series of bytes, is deserialization (which is
also called inflating or unmarshalling).
The process of packaging and unpackaging data that must be moved between different parts of a
computer program or from one program to another. It is typically accomplished by serializing the
data to a shared memory area. Serialization is used for lightweight persistence and for
communication via sockets or Remote Method Invocation (RMI). The default encoding of objects
protects private and transient data, and supports the evolution of the classes.
Quite simply, object Serialization provides a program that has the ability to read or write a whole
object to and from a raw byte stream. It allows Java objects and primitives to be encoded into a
byte stream suitable for streaming to some type of network or to a file-system, or more generally,
to a transmission medium or storage facility.
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.
Serialization lets you save object and all its instance variables, unless you have explicitly marked
a variable transient, which means informing to the JVM that don't include the transient variable's
value as a part of the object serialization state..
The basic object Serialization happens with just two methods one to serialize objects and write
them to a stream, and a second to read the stream and deserialize objects.
ObjectOutputStream.writeObject()
ObjectOutputStream.readObject()
package jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
/**
* This interface has all the constants for making JDBC Connections
*
* @author Darur Venugopal
*
*/
public interface IJDBCConstants {
// In Interface all the variables are public , static and final
String host = "jdbc:oracle:thin:@localhost:1521:xe";
String username = "HR";
String password = "ORACLE";
String driverName = "oracle.jdbc.driver.OracleDriver";
// Declare methods , In interface just method signature are defined.
Connection makeConnection();
Statement makeStatement();
// ResultSet getresultSet();
void LoadDriver();
}
package jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
private static final String sqlQuery = "select email ,first_name, last_name from employees";
// valid instantiation
// step 1
jdbcImplementor.LoadDriver();
Statement statement;
try {
statement = connection.createStatement();
// step 3
ResultSet resultSet = statement.executeQuery(
sqlQuery); // step4
int i = 0;
//
while (resultSet.next()) {
catch (SQLException e) {
System.err.println("SQLEXCEPTION: " + e);
}
}
package jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SQLInsertion {
private static final String sqlQuery =
private static final String sqlQueryForsql ="select sino, name,place ,email from sqltable";
// insertion statement
private static final String insertQuery ="INSERT INTO SQLTABLE VALUES ( ? , ? , ?,? ) ";
// valid instantiation
// step 1
jdbcImplementor.LoadDriver();
Statement statement;
try {
statement = connection.createStatement();
// step 3
ResultSet resultSet = statement.executeQuery(sqlQuery); // step4
int i = 0;
// now that I got the result set i want to print the values from
// result set.
//
while (resultSet.next()) {
String name =resultSet.getString("first_name") +" " + resultSet.getString("last_name");
String email = resultSet.getString("email");
String place ="NIZAMABAD";
preparedStatement.setString(1, name);
preparedStatement.setString(2, place);
preparedStatement.setInt(3, ++i);
preparedStatement.setString(4, email);
preparedStatement.executeUpdate();
while (resultSetForsql.next()) {
System.out.println("11111");
String name =resultSetForsql.getString("name");
String email =resultSetForsql.getString("email");
String place =resultSetForsql.getString("place");
catch (SQLException e) {
System.err.println("SQLEXCEPTION: " + e);
}
}
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
// CHecked Exceptions
try {
Class.forName(driverName);
System.out.println("DRIVER LOADED SUCCESSFULLY");
}
catch (ClassNotFoundException classNotFound) {
System.out.println("CLASS NOT FOUND EXCEPTION " + classNotFound);
}
try {
return connection;
if (connection != null) {
try {
statement = connection.createStatement();
}
return statement;
SELECTION
package jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
/**
* This interface has all the constants for making JDBC Connections
*
* @author Darur Venugopal
*
*/
public interface IJDBCConstants {
// In Interface all the variables are public , static and final
String host = "jdbc:oracle:thin:@localhost:1521:xe";
String username = "HR";
String password = "ORACLE";
String driverName = "oracle.jdbc.driver.OracleDriver";
// Declare methods , In interface just method signature are defined.
Connection makeConnection();
Statement makeStatement();
// ResultSet getresultSet();
void LoadDriver();
}
package jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
private static final String sqlQuery = "select email ,first_name, last_name from employees";
// valid instantiation
// step 1
jdbcImplementor.LoadDriver();
Statement statement;
try {
statement = connection.createStatement();
// step 3
ResultSet resultSet = statement.executeQuery(
sqlQuery); // step4
int i = 0;
while (resultSet.next()) {
catch (SQLException e) {
System.err.println("SQLEXCEPTION: " + e);
}
}
package jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SQLInsertion {
private static final String sqlQuery =
private static final String sqlQueryForsql ="select sino, name,place ,email from sqltable";
// insertion statement
private static final String insertQuery ="INSERT INTO SQLTABLE VALUES ( ? , ? , ?,? ) ";
// valid instantiation
// step 1
jdbcImplementor.LoadDriver();
Statement statement;
try {
statement = connection.createStatement();
// step 3
ResultSet resultSet = statement.executeQuery(sqlQuery); // step4
int i = 0;
// now that I got the result set i want to print the values from
// result set.
//
while (resultSet.next()) {
String name =resultSet.getString("first_name") +" " + resultSet.getString("last_name");
String email = resultSet.getString("email");
String place ="NIZAMABAD";
preparedStatement.setString(1, name);
preparedStatement.setString(2, place);
preparedStatement.setInt(3, ++i);
preparedStatement.setString(4, email);
preparedStatement.executeUpdate();
while (resultSetForsql.next()) {
System.out.println("11111");
String name =resultSetForsql.getString("name");
String email =resultSetForsql.getString("email");
String place =resultSetForsql.getString("place");
catch (SQLException e) {
System.err.println("SQLEXCEPTION: " + e);
}
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
// CHecked Exceptions
try {
Class.forName(driverName);
System.out.println("DRIVER LOADED SUCCESSFULLY");
}
try {
return connection;
if (connection != null) {
try {
statement = connection.createStatement();
}
}
return statement;