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

}


Java Static Import Example

Static Import help to access any static member of class directly.Advantage of using this is that programmers require less code.

import static java.lang.System.*;
public class StaticImport {

public static void main(String[] args) {
out.println("Hello Static Import Example");  // STATIC IMPORT
}

}

Tuesday, 2 August 2016

Java Variable Argument Example


Variable Argument (Varargs)  allows the method to accept zero or multiple arguments.This is a better approach If, we don't know how many parameters we will have to pass in method.
Syntax for variable args 
method_return_type method_name(datatype... variable_name){}
Rules of variable arguments :
** There can be only one variable argument in method signature.
** If providing multiple arguments in method signature then varargs will always be last argument.

public class VariableArgument {
static void show(String... str){
for(String s:str){
System.out.println(s);
}
}
static void show(String str,int... num){
for(int i : num){
System.out.println(i);
}
}
public static void main(String[] args) {
System.out.println("Method With Variable Args\n");
show();  // Method with no argument
show("a","b","c","d");  // Method with argument
System.out.println("Method With Variable Args And Other arguments\n");
show("pushkar",4,5,5);
}
}

Java Enums Example


Enum in java is a data type that contains fixed set of constants.
Enum can be introduce inside or outside the class.
For calling enums use this syntx enum_name.variable_name.
Enum can used with switch statement.
Enum have constructor ,methods and data members.
Enum may implement many interfaces but cannot extend any     class because it internally extends Enum class.


enum week {
sun,mon,tue,wed,thu,fri,sat;
week(){
System.out.println("ENUM CONSTRUCTOR");
}
public void show(){
System.out.println("ENUM METHOD");
}
};

public class EnumExample {

public static void main(String[] args) {

System.out.println("CALLING SINGLE VARIABLE FROM ENUM : "+week.mon);
System.out.println("ENUM LENGTH  : "+week.values().length);

week.sun.show();

System.out.println("CALLING ALL VARIABLE FROM ENUM : ");
for(week w : week.values()){
System.out.println(w);
}
}
}