Saturday, 3 September 2016

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);
}
}
});
}
}

Thursday, 11 August 2016

What is memory leak ?

Memory leaks problem occur When unused objects still have their memory and these objects will never used again and doesn't get Garbage Collected.



Different ways to call Garbage Collection

* Garbage Collection help us to free memory from unused objects.

* Garbage Collection  is a Deamon Thread which run behind the application , and this thread is started by JVM itself.

* The Garbage Collection can not be forced, though there are few ways by which it can be requested there is no guarantee that these requests will be taken care by JVM.

* In Java There are Two ways to call Garbage Collection , gc() method of Garbage Collection belongs to java.lang package.

1 ) System.gc();
2 ) Runtime.getRuntime().gc();


Wednesday, 10 August 2016

If Super class implements Serializable interface, Then sub classes can be Serializable or not ?

Implementing Serializable interface in super class make all sub class Serializable by default.
Static data member are not serialized because static is the part of class not object.

class X implements Serializable{
}
class Y extends X {
}
class Z extends Y {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class SeriazableExample extends Z{
String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public static void main(String[] args) throws FileNotFoundException, IOException,                                     ClassNotFoundException {

Z z= new Z();
z.setName("Pushkar Khosla");
SeriazableExample t = new SeriazableExample();
t.setAddress("Uttam Nagar");
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new                                 File("D:/zzz.txt")));
out.writeObject(z);
out.writeObject(t);
out.flush();
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream(new                                           File("D:/zzz.txt")));

Z z1 = (Z)in.readObject();
System.out.println("::"+z1.getName());
SeriazableExample t1 =(SeriazableExample)in.readObject();
System.out.println("::"+t1.getAddress());
}
}

Thursday, 4 August 2016

Java Autoboxing and Unboxing Example

The automatic conversion of primitive data types into its equivalent Wrapper type is known as boxing and opposite operation is known as unboxing. This is the new feature of Java 5.  So java programmer doesn't need to write the conversion code.


public class AutoboxingAndUnboxing {

public static void main(String[] args) {
int a=100;
Integer n=new Integer(a);  // Boxing

System.out.println("BOXING : "+n);

int x = n;  // Un boxing

System.out.println("UNBOXING : "+x);
}

}