Tuesday, 6 September 2016

Java Code to Avoid Dead Lock ?

There would not be any deadlock because both methods are accessing lock on Integer and String class literal in same order. So, if thread A acquires lock on Integer object , thread B will not proceed until thread A releases Integer lock, same way thread A will not be  blocked even if thread B holds String lock because now thread B will not expect thread A to release Integer lock to proceed further.

public class DeadLockAvoid {
public void method1(){
synchronized(String.class){
System.out.println("Aquired lock on String.class object");
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");
}
}
}
public void method2(){
synchronized(String.class){
System.out.println("Aquired lock on String.class object");
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");
}
}
}
}


Saturday, 3 September 2016

JavaScript And Jquery Function.

JavaScript And Jquery Function are comming Soon ...

Java Program to find First And Second Maximum Number From int type Array ?

Below example show how to find first and second largest Number From int type Array.

public class TwoMaximumNumberFromList {

public static void method(int[] num){
int firstMax = 0;
int secondMax = 0;
for(int n : num){
if(n > firstMax){
secondMax = firstMax;
firstMax = n;
}
else if(secondMax < n){
secondMax = n;
}
}
System.out.println("FIRST MAXIMUM NUMBER : "+firstMax);
System.out.println("SECOND MAXIMUM NUMBER : "+secondMax);
}
public static void main(String[] args) {
int[] num={5,6,9,3};
TwoMaximumNumberFromList.method(num);
}

}

Program Output :-
FIRST MAXIMUM NUMBER : 9

SECOND MAXIMUM NUMBER : 6




Java Program to find Duplicate Character In String ?

Below example show how to count repeated characters from String.

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class DuplicateCharacterFromString {

public static void method(String str){
Map<Character, Integer> map = new HashMap<>();
for(int i=0;i<str.length();i++){
if(map.containsKey(str.charAt(i))){
map.put(str.charAt(i), map.get(str.charAt(i))+1);
}
else{
map.put(str.charAt(i), 1);
}
}
Set<Character> set = map.keySet();
for(Character c : set){
if(map.get(c) > 1){
System.out.println(c+":"+map.get(c));
}
}
}
public static void main(String[] args) {
DuplicateCharacterFromString.method("abca");
}


}
Program Output :-

a:2




Java Programs to Reverse a Numbers ?

Below example shows how to reverse a number using numeric operations. 

public class ReverseNumbers {

public static void reverse(int num){
int reverse = 0;
while(num != 0){
reverse = (reverse*10)+(num%10);
num = num/10;
}
System.out.println("REVERSE : "+reverse);
}
public static void main(String[] args) {
ReverseNumbers.reverse(123);
ReverseNumbers.reverse(1425);
}

}
Program Output :-
REVERSE : 321
REVERSE : 5241


Friday, 2 September 2016

Different Ways to Print Exception Message in Java.

There are 3 Ways to print Exception Message :-
1 > Using Object of java.lang.Exception. This Only Prints the Exception Name.

2 > Using printStackTrace() Method. This is the method which is defined in java.lang.Throwable class and it is inherited from java.lang.Error class and java.lang.Exception class.This method display the name of the Exception and Line where the Exception has Occurred in the Program.

3 > Using getMessage() Method. This method only display the Exception Message.

public class WaysToPrintExceptionMsg {

public static void method_1(){
String s1=null;
try {
s1.length();
} catch (Exception e) {
System.out.println(e);

}
}
public static void method_2(){
String s1=null;
try {
s1.length();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void method_3(){
try {
int x=1/0;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
System.out.println("METHOD 1 OUTPUT :- ");
WaysToPrintExceptionMsg.method_1();
System.out.println("\n\nMETHOD 2 OUTPUT :- ");
WaysToPrintExceptionMsg.method_2();
System.out.println("\n\nMETHOD 3 OUTPUT :- ");
WaysToPrintExceptionMsg.method_3();
}

}
Program Output :-
METHOD 1 OUTPUT :- 
java.lang.NullPointerException


METHOD 2 OUTPUT :- 
java.lang.NullPointerException
at exceptions.programs.WaysToPrintExceptionMsg.method_2(WaysToPrintExceptionMsg.java:23)
at exceptions.programs.WaysToPrintExceptionMsg.main(WaysToPrintExceptionMsg.java:39)


METHOD 3 OUTPUT :- 
/ by zero




Saturday, 27 August 2016

Java Program Showing Serializable Interface Example ?

Serialization in java is a mechanism of writing the state of an object into a byte stream. 
Serializable is a marker interface (has no body). It is just used to "mark" java classes which support a certain capability. 
It must be implemented by the class whose object you want to persist. 
The reverse operation of serialization is called deserialization. 
The String class and all the wrapper classes implements java.io.Serializable interface by default.

Let's see the example given below :-

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Employee implements Serializable{
private static final long serialVersionUID = -7343212483392987741L;
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
public class SerialiazableExample {
static void storeObject(Employee emp,String filePath) throws IOException { //Java Serialization Method
FileOutputStream os = new FileOutputStream(filePath);
ObjectOutputStream ob = new ObjectOutputStream(os);
ob.writeObject(emp);
ob.flush();
ob.close();
System.out.println("Object Written In File Successfully.."+filePath);
}
static void displayObject(String filePath) throws IOException, ClassNotFoundException{ // Java Deserialization Method
System.out.println("READING DATA FROM FILE:::");
FileInputStream is = new FileInputStream(filePath);
ObjectInputStream ob = new ObjectInputStream(is);
Employee emp = (Employee)ob.readObject();
System.out.println("NAME\tID");
System.out.println("----\t--");
System.out.println(emp.getId()+"\t"+emp.getName());
ob.close();
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
String filePath = "D:/serializable_file.txt";
Employee e = new Employee();
e.setName("Pushkar Khosla");
e.setId(101);
storeObject(e,filePath);
displayObject(filePath);
}
}
Programs Output:-
Object Written In File Successfully..D:/serializable_file.txt
READING DATA FROM FILE:::
NAME ID
---- --
101 Pushkar Khosla


Thursday, 25 August 2016

Java Program to find First Non Repeated Character In A String ?

If the word "stress" is input  then it should print  't'   as output .
If the word "teeter" is input  then it should print  'r'   as output .

import java.util.HashMap;
import java.util.Map;

public class FirstNonRepeatedCharacter {
    
public static Character getFirstCha(String str){
Map<Character, Integer> map = new HashMap<>();
for(int i=0;i<str.length();i++){
if(map.containsKey(str.charAt(i))){
map.put(str.charAt(i), map.get(str.charAt(i))+1);
}
else{
map.put(str.charAt(i), 1);
}
}
for(int i=0;i<str.length();i++){
if(map.get(str.charAt(i)) == 1){
return str.charAt(i);
}
}
return null;
}
public static void main(String[] args) {
System.out.println("FIRST NON REPEATED CHARACTER : "+FirstNonRepeatedCharacter.getFirstCha("teeter"));
System.out.println("FIRST NON REPEATED CHARACTER : "+FirstNonRepeatedCharacter.getFirstCha("stress"));
}
} 

Program Output :-
FIRST NON REPEATED CHARACTER : r

FIRST NON REPEATED CHARACTER : t



Monday, 22 August 2016

Java Program to Create Custom Exception ?

For Creating Custom Exception we have to extends the Exception Class. And we can throw that exception if conditions not matches.
Here we are Creating InvalidAgeException , if age is less than 18 it will throw InvalidAgeException exception otherwise it will print valid age.

package exceptions.programs;
class InvalidAgeException extends Exception {

}
public class CustomExceptionExample {

public static void validateAge(int age){
try {
if(age < 18){
throw new InvalidAgeException();
}
else{
System.out.println("Valid Age");
}
} catch (InvalidAgeException e) {
e.printStackTrace();
}
}
public static void main(String[] args)  {
CustomExceptionExample.validateAge(5);
}
}
Program Output :-
exceptions.programs.InvalidAgeException
at exceptions.programs.CustomExceptionExample.validateAge(CustomExceptionExample.java:11)

at exceptions.programs.CustomExceptionExample.main(CustomExceptionExample.java:21)



Java Program to find Minimum & Maximum From Arraylist Or Collection ?

Collection have Predefined method min(Object o) to find minimum value from list and max(Object o) to find maximum value from list. 

public class MinAndMax {

public static void main(String[] args)  {
ArrayList al=new ArrayList();
al.add(2);
al.add(0);
al.add(5);
al.add(8);
al.add(6);
al.add(3);
System.out.println("given array is :" + al);
int n=(int) Collections.min(al);
System.out.println("Minimum value in array is:"+ n);

int m=(int) Collections.max(al);
System.out.println("Maximum value in array is:"+ m);
}
}
Program Output :-
given array is :[2, 0, 5, 8, 6, 3]
Minimum value in array is:0
Maximum value in array is:8

In Java Which run first Static Block,Block,Constructor or Method() ?

First Run Static Block.
Second Run Block.
Third Run Constructor.
Fourth Run Method.

public class Test{

public Test() {
System.out.println("constructor");
}
{
System.out.println("block");
}
static{
System.out.println("static block");
}
void go(){
System.out.println("method");
}

public static void main(String[] args)  {
Test a =new Test();
a.go();
}
}
Program Output :-
static block
block
constructor
method


Friday, 19 August 2016

Java Functional Interface Example

It belongs to java.util.function; package functional interface is defined as an interface with exactly one abstract method, some functional interfaces are :-

Function<T,R> - takes an object of type T and returns R.
Supplier<T> - just returns an object of type T.
Predicate<T> - returns a boolean value based on input of type T.
Consumer<T> - performs an action with given object of type T.
BiFunction - like Function but with two parameters.
BiConsumer - like Consumer but with two parameters. 

it also have some  interfaces for primitive data type :-

IntConsumer
IntFunction<R>
IntPredicate
IntSupplier 

public class FunctionalInterfaces {

public static void main(String[] args) {
List<Integer> list = Arrays.asList(1,2,5,8,3,6,9);
System.out.println("USE OF CUNSUMER INTERFACE TO TRAVERSE LIST");
list.forEach(new Consumer<Integer>() {
@Override
public void accept(Integer t) {
System.out.println(t);
}
});
System.out.println("\nEVEN NUMBERS FROM LIST");
Predicate<Integer> predicate = n-> n%2 == 0;
list.forEach(new Consumer<Integer>() {
@Override
public void accept(Integer t) {
if(predicate.test(t)){
System.out.println(t);
}
}
});
System.out.println("\nODD NUMBERS FROM LIST");
Predicate<Integer> oddPre = n-> n%2 != 0;
list.forEach(new Consumer<Integer>() {
@Override
public void accept(Integer t) {
if(oddPre.test(t)){
System.out.println(t);
}
}
});
System.out.println("\nNUMBERS GREATER THAN 3 IN LIST");
Predicate<Integer> pre1 = n -> n>3;
list.forEach(new Consumer<Integer>() {
@Override
public void accept(Integer t) {
if(pre1.test(t)){
System.out.println(t);
}
}
});
}
}