1. Declaration A[ ] arr = new A[4]; 2. Initializing the Objects arr[0] = new A(); arr[1] = new A(); arr[2] = new A(); arr[3] = new A(); 3. Initializing via loop for( int i=0; i<4; i++ ) arr[i] = new A(); By java 8 A[] a = Stream.generate(() -> new A()).limit(4).toArray(A[]::new);
Step by step tutorial for java , java script ,collections API and important core java interview questions and programs for fresher and experienced developers.
Showing posts with label Core JAVA. Show all posts
Showing posts with label Core JAVA. Show all posts
Thursday, March 21, 2019
Creating an array of objects in Java
Thursday, July 21, 2016
JAVA Generics
Java Generics is similar to C++ Templates. You can write a code with Generics for methods, classes and interfaces. Let see one by one.
Generics Class
To create Generics class we have to use < >. The most commonly used type parameter names are:
E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types
To know more please visit here. Ok,
Example code:
// Use < > to specify Parameter type class JavaHit<T> { // An object of type T is declared T obj; JavaHit(T obj) { this.obj = obj; } // constructor part public T getObject() { return this.obj; } } //To test above I used this class class Main { public static void main (String[] args) { // For Integer type JavaHit <Integer> integerObj = new JavaHit<Integer>(37); System.out.println(integerObj.getObject()); // For String type JavaHit <String> stringObj = new JavaHit<String>("TestForString"); System.out.println(stringObj.getObject()); } }
Output:
37
TestForString
From the above code , you able to understand you can pass any wrapper like Integer , Float etc.,
Multiple Type Parameters
// Use < > to specify Parameter type class JavaHit<T, U> { T obj1; // An object of type T U obj2; // An object of type U // constructor JavaHit(T obj1, U obj2) { this.obj1 = obj1; this.obj2 = obj2; } // To print objects of T and U public void print() { System.out.println(obj1); System.out.println(obj2); } } // To test above I used this class class Main { public static void main (String[] args) { JavaHit <String, Integer> obj = new JavaHit<String, Integer>("TestForString", 37); obj.print(); } }
Output
TestForString
37
Generics Functions:
In nutshell, you can pass here, different types of arguments. Let see code below.
// Generic functions class Test { static <T> void genericParameterDisplay (T typeofelement) { System.out.println(typeofelement.getClass().getName() + " = " + typeofelement); } public static void main(String[] args) { // Calling generic method for Integer genericParameterDisplay(37); // Calling generic method for String genericParameterDisplay("TestForString"); // Calling generic method for double genericParameterDisplay(10.02); } }
Output:
37
TestForString
10.02
Generics Advantages :
1. Code Reuse.
2. Type safety
3. No need Type casting
Tuesday, July 19, 2016
How to create Immutable class in java?
Most of the interview, we can expect this question. In Nutshell, java have lot of immutable classes like String, Integer, Float etc.,
Please remember below points to make your class as immutable.
- Make your class as Final, So that other can not extends it, means cannot create sub class.
- Declare instance variable as Final with private modifier, so that it can not change once initiated.
- Don't implement setter methods.
- Finally, don't provide any method which will change the behavior of state of the object.
Example :
public final class JavaHit{ final String name; public JavaHit(String name){ this.name=name; } public String getName(){ return name; }
Benefits of Immutable class:
- It will be helpful in synchronization environments, since its thread-safe.
- Internal state of immutable class will be fine, even you get any exception.
- It will be good to work with Map Keys and set elements, since typically it will not change once its created.
Friday, June 17, 2016
Things to remember about Null Pointer Exception
Our day to day coding life, we are facing Null pointer exception in most cases. We can see some good points about this.
1. The instanceof operator
Code:
String str = null; if(str instanceof String) System.out.println("String is an instance here"); else System.out.println("String is not an instance here");
Output:
String is not an instance here
You can use instanceof operator , even if the object reference equals to null. It will not throw null pointer exception.
2. Null with contains , containsKey and containsValue methods
Code:
String value = map.get(key); System.out.println(value.toString());
We know map, which is working based on key and value concept. From the above code, suppose if value is null, then it will throw null pointer exception here.
To avoid Null pointer for above code :
if(map.containsKey(key)) { String value = map.get(key); System.out.println(value.toString()); // Now No exception }
3. Apache StringUtils class
if (StringUtils.isNotEmpty(str)) { System.out.println(str.toString()); }
We can use StringUtils.IsEmpty and StringUtils.equals also.
4. String comparison with equals
This is very useful, in most of our programs.
String str = null; if(str.equals("Test")) { // Exception will throw here }
To avoid above Code Error
String str = null; if("Test".equals(str)) { //No Exception now }
5. Ternary operator
String message = (str == null) ? "" : str.length();
From the above, if str is null, then assign empty for that, else calculate length.
6. valueOf() is better than toString()
String str = null; System.out.println(String.valueOf(str)); // it will prints null System.out.println(str.toString()); // it will throw NullPointer Exception
7. Working with Static method or Static members
Below code will not throw any error.
class Test { public static void testMessage() { System.out.println("Test Message"); } } public class TestStatic { public static void main(String[] args) { Test t = null; t.testMessage(); } }
However, as per rule, static method should be called through class name only. Calling static method by object reference is not advisable.
Friday, June 10, 2016
extends Thread vs Implements Runnable
There are two ways to create a thread in Java.
1. By extending Thread class
2. By implementing Runnable Interface
Lets see the difference now.
Now we can understand this with one example, which will clarify more.
Output :
If you will analyze the output, it says well like Runnable interface sharing one instance and increment values. But it is opposite in Thread class, since it creates separate instance every time.
1. By extending Thread class
2. By implementing Runnable Interface
Lets see the difference now.
- If you are extending Thread class , you can not extends another class again, since Java does not support multiple inheritance.
- If you are using implements Runnable interface , then there is a chance to extending another class.
- Very important difference is, your thread will create unique object and make an associates with it while extends Thread.
- But if you are using an implements Runnable Interface, It will share same object to multiple threads.
Now we can understand this with one example, which will clarify more.
class ImplementsRunnable implements Runnable { private int count = 0; public void run() { count++; System.out.println("ImplementsRunnable checking Test : " + count); } } class ExtendsThread extends Thread { private int count = 0; public void run() { count++; System.out.println("ExtendsThread checking Test : " + count); } } public class ThreadVsRunnable { public static void main(String args[]) throws Exception { ImplementsRunnable rc = new ImplementsRunnable(); Thread t1 = new Thread(rc); t1.start(); Thread.sleep(1000); Thread t2 = new Thread(rc); t2.start(); Thread.sleep(1000); Thread t3 = new Thread(rc); t3.start(); ExtendsThread tc1 = new ExtendsThread(); tc1.start(); Thread.sleep(1000); ExtendsThread tc2 = new ExtendsThread(); tc2.start(); Thread.sleep(1000); ExtendsThread tc3 = new ExtendsThread(); tc3.start(); } }
Output :
ImplementsRunnable checking Test : 1 ImplementsRunnable checking Test : 2 ImplementsRunnable checking Test : 3 ExtendsThread checking Test : 1 ExtendsThread checking Test : 1 ExtendsThread checking Test : 1
If you will analyze the output, it says well like Runnable interface sharing one instance and increment values. But it is opposite in Thread class, since it creates separate instance every time.
Monday, June 6, 2016
Difference between sleep and wait in java ?
Sleep and wait () method
sleep () is a method , which is used to hold the process for a particular time or How much time you wanted to hold.
wait () method goes to waiting stage and it wont come back to normal until notify() or notifyAll() method should be called.
Important points about sleep() method
1. Sleep is a static method on Thread class.
2. It will makes your current thread into Not Runnable state for the specified amount of time.
Thread keeps the lock, during this time.
3. It will be waked by interrupt or time expires.
4. It throws interrupted exception if another thread interrupts a sleeping thread.
Important points about wait() method
1. wait is an object class method.
2. It will makes your current thread into Not Runnable state.
3. Remember, wait is called on an object not on thread.
4. wait() should be used inside synchronized block or synchronized method.
5. It will release the lock and gives the chance to others.
6. It will be awake by calling on notify() or notifyAll() methods.
Wednesday, May 4, 2016
Deep copy and Shallow copy in java
Shallow Copy:
A new object will be created that has an exact copy values of its original object. Means, it will copy all of the fields , suppose if any of the fields are object reference then reference address only will be copied. That is, reference address means, memory address.
![]() |
| Before shallow copy picture 1 |
![]() |
| After Shallow copy picture 2 |
We have added here two pics, and first picture mentioning before shallow copy and second picture is after doing shallow copy. Now lets see points,
1. Initially Main object 1 have filed 1 and contain object 1.
2. After doing shallow copy Main Object 2 is created with filed 2.
3. But still contain object 2 is not created and Main object 2 is pointing contain object 1. Means, memory address copied. (reference address).
4. So if you will do any changes in Contain object 1 of Main object 1, it will reflect in Main object 2 also.
Deep copy
It will copy all of the fields and all the dynamically allocated memory address pointed by that object are also copied. Below picture will say clearly.![]() | |||||
| Before Deep Copy |
![]() |
| After Deep copy |
1. Initially Main object 1 have filed 1 and contain object 1.
2. After doing deep copy Main Object 2 is created with filed 2 and contain object 2.
3. Remember here, contain object 2 was not created in shallow, but in deep contain object 2 is created.
4. So if you will do any changes in Contain object 1 of Main object 1, it will not reflect in Main object 2 .
Shallow copy with example code
public class Subject {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Subject(String name) {
this.name = name;
}
}
Create another one class called Student and code is belowpublic class Student implements Cloneable {
// Contained object
private Subject subj;
private String name;
public Subject getSubj() {
return subj;
}
public void setSubj(Subject subj) {
this.subj = subj;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student(String name, String sub) {
this.name = name;
this.subj = new Subject(sub);
}
public Object clone() {
// Create shallow copy
try {
return super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
}
Below class is to test shallow copypublic class ShallowTest {
public static void main(String[] args) {
// Original Object
Student stud = new Student("RAJA", "MATHS");
System.out.println("Original Object : " + stud.getName() + " ---- "
+ stud.getSubj().getName());
// Create Clone Object
Student clonedStud = (Student) stud.clone();
System.out.println("After Cloned Object: " + clonedStud.getName() + " ---- "
+ clonedStud.getSubj().getName());
//Again setting new data
stud.setName("Kumar");
stud.getSubj().setName("CHEMISTRY");
System.out.println("Original Object after updating: "
+ stud.getName() + " ---- " + stud.getSubj().getName());
System.out.println("Cloned Object after updating original object: "
+ clonedStud.getName() + " ---- "
+ clonedStud.getSubj().getName());
}
}
OutputOriginal Object : RAJA ---- MATHS
After Cloned Object: RAJA ---- MATHS
Original Object after updating : Kumar ---- CHEMISTRY
Cloned Object after updating original object: RAJA - CHEMISTRY
Deep copy with example code
You can use the above shallow example and do a Little bit change like below and execute it.
public class Student implements Cloneable {
// Contained object
private Subject subj;
private String name;
public Subject getSubj() {
return subj;
}
public void setSubj(Subject subj) {
this.subj = subj;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student(String name, String sub) {
this.name = name;
this.subj = new Subject(sub);
}
public Object clone() {
// For deep copy
Student student = new Student(name, subj.getName());
return student;
}
}
The only difference here, we are creating new object inside clone method and returning. Wednesday, April 13, 2016
Static Binding vs Dynamic Binding
In java two types of binding is available.
1. Static Binding
2. Dynamic Binding
Before seeing the code example remembering below points may help you to understand easily.
1. Static binding in java will occur at compile time only. It also known as early binding.
2. Dynamic binding in java will occur at run time only. It also known late binding.
3. Static binding will happen through method overloading only.
4. Dynamic binding will happen through method overriding only. So obviously class needs to be extended.
Example of Static Binding
public class StaticBindingTest {
public static void main(String args[]) {
List myList = new ArrayList();
StaticBindingTest obj = new StaticBindingTest();
obj.test(myList);
}
public Collection test(List c){
System.out.println("Inside List test method");
return c;
}
public Collection test(ArrayList as){
System.out.println("Inside ArrayList test method");
return as;
}
}
Output:
Inside List test method
The compiler will decide which method needs to be executed at compile time itself. See below image
As we discussed earlier its happening through overloading. Compiler decided List myList to be passed to test method. So its printing above output. Its not listening new Arraylist. Hope you understand.
After seeing the example Dynamic binding you will understand 100% clearly about both static and dynamic.
Example of Dynamic Binding
public class DynamicBindingTest
{
public static void main(String args[])
{
Vehicle vehicle = new Car(); //Vehicle is super class and Car is a sub class
vehicle.test();
}
}
class Vehicle
{
public void test()
{
System.out.println("Inside test method of Vehicle");
}
}
class Car extends Vehicle
{
@Override
public void test()
{
System.out.println("Inside test method of Car");
}
}
Output: Inside test method of Car
Vehicle is a super class and car is a sub class. As per rule, super class can hold sub class. So that added code like Vehicle vehicle = new Car(); See, we used here overriding. So dynamic binding.
below image will tell more,
Run time it will check sub class of Car and calling test method of Car class. Still confusing, simply remember compile time left side and run time right side.
Monday, April 11, 2016
Transient Keyword in java with Example
Before going to examine the Transient keyword, we should know what is serialization and de-serialization.
What is Serialization ?
Serialization is the process of converting your object into stream of bytes and stored in a file. These process will be handled by JVM and mostly it will be involved in networking side.If any class want to be involved in serialization then it must implements serializable interface.
What is De-Serialization ?
The same process again bring back your object states to bytes called de-serialization.
What is transient Keyword in java?
If any variables declared transient keyword in java which will not be participated in serialization. Means, It indicates to JVM the transient varibale is not part of the persistence state of an object.
Lets see one simple example to understand further.
Person.java
import java.io.Serializable;
public class Person implements Serializable {
private String name;
private int id;
private transient String characterType;
public Student(String name, int id, String characterType) {
this.name = name;
this.id = id;
this.characterType = characterType;
}
@Override
public String toString() {
return "Name: " + name +
", id: " + id +
", characterType : " + characterType;
}
}
MainTest.javaimport java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class MainTest {
public static void main(String[] args) throws ClassNotFoundException {
Person p = new Person("TestName", 1, "Good");
System.out.println("Before serialization:" + p.toString());
// Below is the way to Serialize of the object
try {
FileOutputStream file = new FileOutputStream("p.ser");
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(p);
System.out.println("Object P was serialized");
out.close();
file.close();
} catch(IOException e) {
e.printStackTrace();
}
// Deserialization of the object.
try {
FileInputStream file = new FileInputStream("p.ser");
ObjectInputStream in = new ObjectInputStream(file);
Person p1 = (Person) in.readObject();
System.out.println("After de-serialization :" + p1.toString());
in.close();
file.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
In the person java class we have used toString() to identify how the variables will be printed.Lets execute the program and check the output.
Before serialization: Name: TestName, id: 1, characterType: Good Object P was serialized After de-serialization : Name: TestName, id: 1, characterType: null
From the above output we able to see charaterType is null, since it used transient keyword and its not participated serialization. Remember static variables also will not participate in serialization process. Since its not belongs to any individual instance.
Lets go somewhat deep into this.
Transient with final Keyword
Just consider you have below code with final declaration.
private String name; public final transient String userName = "TestUserName"; public final transient Logger logger = Logger.getLogger(Test.class);
Once we execute this above code, output will be too much different. Output is below.
Name
TestUserName
null
As per serialization concept the TestUserName should be display value as null. But logger was displaying null perfectly. The reason is, String userName is mentioning constant Expression. logger mentioning reference. So logger returning null.
If we remove transient from both logger and userName , userName will be involved in serialization and logger will not be involved and will throw NotSerializableException.
See below String API. Its implementing Serializable interface and logger not implementing.
public final class String extends Object implements Serializable, Comparable<String>, CharSequence
Thursday, April 7, 2016
Java Heap and Stack Memory
Heap and Stack
Heap and Stack memory will be used to execute all java programs.
1.Heap Memory
Heap memory will be used for the purpose of storing java objects. It will allocates some memory to your java objects.
We know about Garbage collector, its running on Heap memory and clean unwanted object reference.
Whatever object is created in Heap memory, it will become Global access.
We can set the heap memory size by the command -Xms and -Xmx with JVM. Means, start up and maximum size of heap memory.
Most of the time , we are getting java.lang.outOfMemoryError, (Heap space error) due to heap memory size full.
2. Stack Memory
Stack memory will be used mainly while execution of thread.
Stack memory is working with LIFO(Last-In-First-Out) concept.
All variables and methods will be created in stack memory and deallocate will happen automatically.
Its faster than Heap memory while allocation
Stack memory size is less compared to Heap memory
Once method execution was done, it will become unused and next method will be ready for execution
When stack memory is full, it will throw java.lang.stackOverFlow Error
Both Heap and Stack are stored in computer RAM.
Thursday, March 24, 2016
Comparator and Comparable Interface in java
Comparable Interface:
It’s an interface under the package of java.lang.comparable, which having one method int compareTo(T o). We can use this method ordering(sort logic only) the object. It will compare this object with your specified object for ordering purpose.
Key points to remember in comparable interface:
- You must write the sort logic in the same class whose objects to be sorted. So people will call this in the name of Natural Ordering.
- The class must implements Comparable interface. So that, compareTo overriding is possible. Good thing here is, Generics possible.
- Collections.sort(List) should be called for sorting.
Return type of compareTo method is int. So three possible returning values.
int compareTo(Object obj)
1. Positive – this object is greater than obj.
2. Zero – this object is equals to obj.
3. negative – this object is less than obj.
Below I have written code for explaining comparable interface with simple Fruits class.
package com.test.javahit;
public class Fruits implements Comparable{
private int fruitId;
private String fruitName;
public Fruits(int id,String name){
this.fruitId = id;
this.fruitName = name;
}
public int getFruitId() {
return fruitId;
}
public void setFruitId(int fruitId) {
this.fruitId = fruitId;
}
public String getFruitName() {
return fruitName;
}
public void setFruitName(String fruitName) {
this.fruitName = fruitName;
}
// Comparing logic by fruits Id
@Override
public int compareTo(Object obj) {
Fruits fruits = (Fruits) obj;
//Compare logic with Ternary operator
return (this.fruitId < fruits.fruitId) ? -1 : (this.fruitId > fruits.fruitId) ? 1 : 0;
//Use below If above logic is confuse
/*if (this.fruitId > fruits.getFruitId())
return 1;
else if (this.fruitId < fruits.getFruitId())
return -1;
else
return 0;*/
}
}
Next below is our main method class MainTest.
package com.test.javahit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MainTest {
/**
* @param args
*/
public static void main(String[] args) {
//Add fruit id and name for all fruits
Fruits fruit1 = new Fruits(3, "Banana");
Fruits fruit2= new Fruits(1, "Orange");
Fruits fruit3 = new Fruits(2, "Apple");
Fruits fruit4 = new Fruits(4, "Cherry");
//Create a list for fruits
List listOfFruits = new ArrayList();
listOfFruits.add(fruit1);
listOfFruits.add(fruit2);
listOfFruits.add(fruit3);
listOfFruits.add(fruit4);
System.out.println("Before using compareTo method in Fruits class");
for (int i=0; i< listOfFruits.size(); i++) {
Fruits fruitName = (Fruits)listOfFruits.get(i);
System.out.println("Fruit Id :" + fruitName.getFruitId() + " Fruit Name :" + fruitName.getFruitName());
}
Collections.sort(listOfFruits);
System.out.println("After using Collections.sort() for Fruit Id");
for (int i=0; i< listOfFruits.size();i++) {
Fruits fruitSortedList = (Fruits) listOfFruits.get(i);
System.out.println("Fruit Id :" + fruitSortedList.getFruitId() + " Fruit Name :" + fruitSortedList.getFruitName());
}
}
}
The Fruits class is implementing Comparable interface for overriding compareTo method. This method have the logic id. Please see Fruits class comapreTo method . I used ternary operator(conditional) for comparing objects. We can use simple if else condition also to compare the objects.
Once you execute MainTest class, you will find below output:
Before using compareTo method in Fruits class Fruit Id :3 Fruit Name :Banana Fruit Id :1 Fruit Name :Orange Fruit Id :2 Fruit Name :Apple Fruit Id :4 Fruit Name :Cherry After using Collections.sort() for Fruit Id Fruit Id :1 Fruit Name :Orange Fruit Id :2 Fruit Name :Apple Fruit Id :3 Fruit Name :Banana Fruit Id :4 Fruit Name :Cherry
Comparator Interface:
It’s an interface under the package of java.util.comparator, which having one method int compare(Object o1 , Object o2).
Key points to remember in comparable interface :
- Sorting logic should be placed in separate class, so that we can write sort based on different attributes of objects. It means, you can sort fruitId, fruitName etc.,
- Some other class needs to implement comparator Interface for sorting logic, here the case is FruitsIdSortingComparator.
- Collections.sort(List, Comparator) should be called for sorting.
- Return type of compare method is int. So three possible returning values.int compare(Object o1,Object o2). It will compare thwo object o1 and o2 and will return an integer.
1. positive – o1 is greater than o2
2. zero – o1 equals to o2
3. negative – o1 is less than o1
import java.util.Comparator; public class FruitsIdSortingComparator implements Comparator{ @Override public int compare(Fruits fruits1, Fruits fruits2) { Fruits fruits = (Fruits) obj; //Compare logic with Ternary operator return (fruits1.getFruitId() < fruits2.getFruitId()) ? -1 : (fruits1.getFruitId() > fruits2.getFruitId()) ? 1 : 0; }
Below I have added below code, comparator interface logic for sorting with MainTest class.
//By using comparator interface //For Fruit ID Collections.sort(listOfFruits,new FruitsIdSortingComparator()); //For Fruit Name Collections.sort(listOfFruits, new Comparator() { @Override public int compare(Fruits o1, Fruits o2) { return o1.getFruitName().compareTo(o2.getFruitName()); } }); System.out.println("\nAfter sort by Fruit Name : \n"); for (int i=0;i<listOfFruits.size();i++) { Fruits fruitname = (Fruits) listOfFruits.get(i); System.out.println(" Fruit Name : " + fruitname.getFruitName()); }
Now just run MainTest class, you able to find the below output.
After sort by Fruit Name :
Fruit Name : Apple
Fruit Name : Banana
Fruit Name : Cherry
Fruit Name : Orange
Tuesday, March 15, 2016
JDK and Maven PATH Settings
JDK and Maven Path settings are very easy to configure in environment variables. The below process will explain.
1.Goto your environment variable and click on that button.
2. Under System variables, click on New button. It will give you an option to add the below two fileds.
Variable Name: JAVA_HOME
Variable Value: C:\Program Files\Java\jdk1.6.0_31
3. If you need you can configure maven , else leave maven configuration step.
For maven configuration, again click New button, it will ask you to enter variable name and variable value like step 2.
Variable name : MAVEN_HOME
Variable value : C:\Softwares\apache-maven-3.0.4-bin\apache-maven-3.0.4
Once you finished both JAVA_HOME and MAVEN_HOME, we should add it in User variable like below. Please carefully place ; and \bin; (copy and paste it).
Variable name : PATH
Variable value : %JAVA_HOME%;%MAVEN_HOME%\bin;
Once you finish click Ok. Thats all.
1.Goto your environment variable and click on that button.
2. Under System variables, click on New button. It will give you an option to add the below two fileds.
Variable Name: JAVA_HOME
Variable Value: C:\Program Files\Java\jdk1.6.0_31
![]() |
| Java Path Setting |
For maven configuration, again click New button, it will ask you to enter variable name and variable value like step 2.
Variable name : MAVEN_HOME
Variable value : C:\Softwares\apache-maven-3.0.4-bin\apache-maven-3.0.4
![]() |
| Maven Path settings |
Variable name : PATH
Variable value : %JAVA_HOME%;%MAVEN_HOME%\bin;
![]() |
| Java and Maven path settings |
Tuesday, March 8, 2016
Create Singleton with Thread-Safe
Many blog could teach you how to write singleton but somebody may interest to face singelton with thread safe. We can see the below example for create the singleton instance with thread safe.
The below code will also explain What is volatile keyword and its responsibilty.
From the above, We know static will execute at first as per java rules. Here we able to see volatile keyword, which will create that instance in Main memory. The reason behind for adding volatile here is, we need multi threading task should be happened with the help of that instance. A lot of parallel threads will load simultaneously and if they want to access the instance, which should be in Main memory. The below picture will represent clearly.
The below code will also explain What is volatile keyword and its responsibilty.
private static volatile Test instance;
public static Test getInstance () {
if (instance == null) {
synchronized (Test.class) {
instance = new Test();
}
}
return instance;
}
}
From the above, We know static will execute at first as per java rules. Here we able to see volatile keyword, which will create that instance in Main memory. The reason behind for adding volatile here is, we need multi threading task should be happened with the help of that instance. A lot of parallel threads will load simultaneously and if they want to access the instance, which should be in Main memory. The below picture will represent clearly.
![]() |
| Volatile with Thread Safe Explanation |
Hope you understand volatile purpose here. Suppose if volatile is not used. some thread could access instance as NULL.
Friday, February 7, 2014
Abstract Class
An abstract class can contain zero or more abstract methods. The abstract keyword must be used here.
For Example,
Points to Remember:
1.You can have instance variables and concrete methods.
2.You cannot create object to abstract class.
3.While you are extending the abstract class, all the abstract methods should be implemented in its sub class.
4.If the abstract method is not implemented in its sub class, then that sub class should also use abstract keyword.
For Example,
abstract class JavaHit
{
//abstract method
abstract void test(int n, int m);
}
class First extends JavaHit
{
//Add two values
void test(int j, int k)
{
int p = j+k;
System.out.println(“Added value is ” + p );
}
}
class Second extends JavaHit
{
//Subtract two values
void test(int j, int k)
{
int p = j-k;
System.out.println(“Added value is ” + p );
}
}
class LastOne
{
public static void main(String args[])
{
First first = new First();
Second second = new Second();
first.test(1,3);
second.test(2,4);
}
}
Points to Remember:
1.You can have instance variables and concrete methods.
2.You cannot create object to abstract class.
3.While you are extending the abstract class, all the abstract methods should be implemented in its sub class.
4.If the abstract method is not implemented in its sub class, then that sub class should also use abstract keyword.
Monday, February 3, 2014
JDBC Database Connections
What
is JDBC ad Why do we need it?
·
It is an API Java DataBase Connectivity
·
Connect to the DataBase.
·
Retrieve Data from DataBase
·
Insert data into DataBase.
Steps for JDBC
Program
o
Register a Driver
o
Connect to the DataBase
o
SQL Statements
o
Executing SQL Statements
o
Retrieving Results
o
Closing Connection
How
to Register a Driver?
Option
1:
You
can register a driver with the help of registerDriver() method.
For
example,
DriverManger.registerDriver(
new sun.jdbc.odbc.jdbcodbcDriver());
Option
2:
You
can register a driver with the help of forName() method.
For
example,
Class.forName(sun.jdbc.odbc.jdbcodbcDriver);
How To Connect To DataBase?
1.You should pass
the URL of the DataBase.
2.You should give
DataBase UserName.
3. You should give
DataBase Password.
Please see the below code.
DriverManager.getConection(“jdbc:odbc:oradsn”, “scott”,
“sa”);
How To Prepare SQL Statements?
Here you can use two ways.
1.Statement
2.Prepared Statement
For executing query we can use both, But the difference
is Perpared Statement is Fast and It is Pre Compile.
Please look the below code.
Statement stmt = con.createStatement();
Now we have to execute the query with the help of
executeQuery() method.
ResultSet rs = stmt.executeQuery(“select * from vendor”);
Now the query will be executed and result will be
stored into ResultSet.
ResultSet have some methods. You can use this for retrieving
datas.
The methods are,
String getString()
int getInt()
float getFloat()
etc.,.
How to use these methods, can see later in example.
Example Program for JDBC Connection:
import java.sql.*;
class TestJdbc {
public
static void main(String args[]) {
//Driver
Register
DriverManger.registerDriver( new
sun.jdbc.odbc.jdbcodbcDriver());
//Connection with database
Connection
con = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521: xe”,
“test” , “sa”);
//
for creating sql statement
Statemet
stmt = con.createStatement();
//Executing
statement
ResultSet
rs = stmt.executeQuery(“Select * form vendor”);
//
Retreiving results
While(rs.next())
{
System.out.pritln(“The
vendor ID is ” + rs.getInt(1));
System.out.pritln(“Vendor
Name ” + rs.getString());
System.out.pritln(“Vendor
Fund Percent” + rs.getFloat());
}
con.close();
}
}
Subscribe to:
Posts (Atom)









