Showing posts with label Core Java. Show all posts
Showing posts with label Core Java. Show all posts

Wednesday, August 22, 2012

Reading file using FileReader

package com.jsl.core.io;
import java.io.BufferedReader;
import java.io.FileReader;
public class ReadingFile {
  public static void main(String[] args) {
   try{
    FileReader fr=new FileReader("info.txt");
    BufferedReader br=new BufferedReader(fr);
    String data=null;
    while((data=br.readLine())!=null){
     System.out.println(data);
    }
    br.close();
    fr.close();
   }catch(Exception e){
    e.printStackTrace();
   }
   
  }
}

Program to count the occurrence of word in the given file 


package com.jsl.core.io;

import java.io.BufferedReader;
import java.io.FileReader;

public class ReadingFile {
  public static void main(String[] args) {
   try{
    FileReader fr=new FileReader("info.txt");
    BufferedReader br=new BufferedReader(fr);
    String data=null;
    int count=0;
    while((data=br.readLine())!=null){
     String words[]=data.split(" ");
     for(String word:words){
      if(word.toLowerCase().contains("java"))
       count++;
     }
    }
    System.out.println("The count is :"+count);
    br.close();
    fr.close();
   }catch(Exception e){
    e.printStackTrace();
   }
   
  }
}

Creating and writing content into the file java 1.7 example 


package com.jsl.core.io;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class CreatingFileByWriter {

  public static void main(String[] args)  {
   String message="Welcome to core java world";
   try(FileWriter writer=new FileWriter("myfile.txt")){
     BufferedWriter bf=new BufferedWriter(writer); 
     bf.write(message);
     bf.close();
     System.out.println("DONE");
   } catch(IOException  e){
    System.out.println(e);
   }
  }
}

Serialization example


package com.jsl.core.io;

import java.io.Serializable;

public class Product implements Serializable {
  private int id;
  private String name;
  private double price;
  public Product(int id, String name, double price) {
   super();
   this.id = id;
   this.name = name;
   this.price = price;
  }
  @Override
  public String toString() {
   return id+" "+name+" "+price;
  }
}



package com.jsl.core.io;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;

public class Manager {
  public static void main(String[] args) {
   FileOutputStream fis=null;
   ObjectOutputStream ois=null;
   
   try{
    fis=new FileOutputStream("product.txt");
    ois=new ObjectOutputStream(fis);
    for(;;){
     Scanner sc=new Scanner(System.in);
     System.out.println("Enter the pid");
     int id=sc.nextInt();
     System.out.println("Enter the price");
     double price=sc.nextDouble();
     System.out.println("Enter the name ");
     String name=sc.next();
     
     Product p=new Product(id, name, price);
     ois.writeObject(p);
     
     System.out.println("Do u want to continue.... yes /no");
     String ch=sc.next();
     if(ch.equals("no"))
      break;
    }
    
   }catch(Exception e){
    e.printStackTrace();
   }finally{
    try{
     ois.close();
     fis.close();
    }catch(Exception e){
     System.out.println("While closing :"+e);
    }
    
   }
   
  }
}


Reading the object from the file:



package com.jsl.core.io;

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class ReadingObjects {
  public static void main(String[] args) {
   FileInputStream fis=null;
   ObjectInputStream ois=null;
   try{
    fis=new FileInputStream("product.txt");
    ois=new ObjectInputStream(fis);
    Product p;
    while((p=(Product)ois.readObject())!=null){
     System.out.println(p);
    }
   }catch(Exception e){
    System.out.println("End of File");
   }
   
  }
}

Emplouyee.java

package com.jsl.core.io;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class Employee implements Externalizable {
 private int empno;
 private String email;
 private String password;
 public Employee() {
  // TODO Auto-generated constructor stub
 }
 @Override
 public void writeExternal(ObjectOutput out) throws IOException {
  out.writeInt(empno);
  out.writeObject(email);
 }

 @Override
 public void readExternal(ObjectInput in) throws IOException,
   ClassNotFoundException {
   this.empno=(in.readInt());
   this.email=((String)in.readObject());
  
 }

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public int getEmpno() {
  return empno;
 }

 public void setEmpno(int empno) {
  this.empno = empno;
 }
  
}


package com.jsl.core.io;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class EmpManager {
  public static void main(String[] args) {
   FileOutputStream fis=null;
   ObjectOutputStream ois=null;
   
   try{
    fis=new FileOutputStream("employee.txt");
    ois=new ObjectOutputStream(fis);
    Employee e=new Employee();
    e.setEmpno(1001);
    e.setEmail("lakshman@jsltech.com");
    e.setPassword("xyxabc");
    
    Employee e1=new Employee();
    e1.setEmpno(1002);
    e1.setEmail("hari@jsltech.com");
    e1.setPassword("abcxyz");
    
    ois.writeObject(e1);
    ois.writeObject(e);
    
    
   }catch(Exception e){
    e.printStackTrace();
   }finally{
    try{
     ois.close();
     fis.close();
    }catch(Exception e){
     System.out.println("While closing :"+e);
    }
    
   }
   
  }
}


package com.jsl.core.io;

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class ReadingObjects {
  public static void main(String[] args) {
   FileInputStream fis=null;
   ObjectInputStream ois=null;
   try{
    fis=new FileInputStream("employee.txt");
    ois=new ObjectInputStream(fis);
    Employee emp;
    while((emp=(Employee)ois.readObject())!=null){
     System.out.println(emp.getEmpno());
     System.out.println(emp.getEmail());
     System.out.println(emp.getPassword());
    }
   }catch(Exception e){
     System.out.println("End of File");
   }
   
  }
}

Files and I/O Examples


  1. Creating the file using FileOutputStream
  2. Reading the file
  3. Reading and Writing file
  4. Reading Multiple files data using SequenceInputStream 
  5. Reading file using FileReader

     

           

          The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, Object, localized characters etc.

           A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.

Questions

What is the output?

package com.jsl.core.basic;
public class Welcome{
  static int a=printMessage();
  static{
   System.out.println("Static block :" +a);
  }
  public static void main(String miani[]) {
   System.out.println("Main Method");
  }
  private static int printMessage() {
    System.out.println("The print message method :"+a);
    return 100;
  }
}
What is output?

package com.jsl.core.basic;
public class Welcome{
  static{
   System.out.println("Static block 2" );
  }
  public static void main(String miani[]) {
   System.out.println("Main Method");
  }
  static{
   System.out.println("Static block 1");
  }
}
What happens when you compile and execute the program ?

package com.jsl.core.basic;

public class Welcome{
  int a=100;
  static{
    a=a++ + a++;
  }
  public static void main(String miani[]) {
    System.out.println("Main Method "+a++);
  }
  static{
   System.out.println("Static block "+a);
  }
}

What happens when you compile and execute the program?

package com.jsl.core.basic;
 public class Welcome{
    int a=100;
    static{
     int a;
     a=a++ + a++;
     System.out.println("The value of a is : "+a);
    }
    public static void main(String miani[]) {
     System.out.println("Main Method ");
    }
    static{
     System.out.println("Static block ");
    }
 }
What happens when you compile and execute the program?

package com.jsl.core.basic;
public class Welcome{
    int a=100;
    static{
      int a;
      a=a++ + a++;
      System.out.println("The value of a is : "+a);
    }
    public static void main(String miani[]) {
     System.out.println("Main Method ");
    }
    static{
     System.out.println("Static block ");
    }
}

Tuesday, August 21, 2012

Reading Multiple files data using SequenceInputStream Object


package com.jsl.io;

import java.io.FileInputStream;
import java.io.SequenceInputStream;
import java.util.Vector;

public class ReadingData {
 public static void main(String[] args) {
  FileInputStream fis1 = null;
  FileInputStream fis2 = null;
  SequenceInputStream seq = null;
  try {
   fis1 = new FileInputStream("One.txt");
   fis2 = new FileInputStream("one.txt");
   Vector vector = new Vector();
   vector.add(fis1);
   vector.add(fis2);
   seq = new SequenceInputStream(vector.elements());
   int ch;
   while ((ch = seq.read()) != -1) {
    System.out.print((char) ch);
   }
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    seq.close();
    fis1.close();
    fis2.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
 }
}

Reading file and writing into another file


package com.jsl.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ReadingFileContent {
  public static void main(String[] args) {
    FileInputStream fis=null;
    BufferedInputStream bis=null;
    FileOutputStream fos=null;
    BufferedOutputStream bos=null;

    try {
       fis=new FileInputStream("One.txt");
       bis=new BufferedInputStream(fis);
       try{
         fos=new FileOutputStream("Two.txt");
         bos=new BufferedOutputStream(fos);
         int ch;
         while((ch=bis.read())!=-1){
           fos.write((char)ch);
         }
       }catch(Exception e){
          System.out.println("While opening new file :"+e);
       }
    } catch (Exception e) {
        System.out.println("While reading the file");
    }finally{
         try {
           bis.close();
           fis.close();
           bos.close();
           fos.close();
         } catch (IOException e) {
           e.printStackTrace();
         }
    }
  }
}

Reading the file content




package com.jsl.io;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class ReadingFileContent {
  public static void main(String[] args) {
    FileInputStream fis=null;
    BufferedInputStream bis=null;

    try {
      fis=new FileInputStream("One.txt");
      bis=new BufferedInputStream(fis);
      int ch;

      while((ch=bis.read())!=-1){
         System.out.print((char)ch);
      }
    } catch (Exception e) { 
       e.printStackTrace();
    }finally{
         try {
            bis.close();
            fis.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
    }
  }
}

Creating the file using FileOutputStream



package com.jsl.io;

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.FileOutputStream;

public class FileCreation {
  public static void main(String[] args) {
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    
    try {
      fos = new FileOutputStream("One.txt", true);
      System.out.println("Enter the text");
      bos = new BufferedOutputStream(fos, 512);
      DataInputStream dis = new DataInputStream(System.in);
      char ch;
      while ((ch = (char) dis.read()) != '@') {
        int a = 1 / 0;
        bos.write(ch);
      }
   } catch (Exception e) {
      e.printStackTrace();
   } finally {
          try {
             bos.close();
             fos.close();
          } catch (Exception e) {
             System.out.println("While closing the file :" + e);
          }
   }
   System.out.println("End of main method");
 }
}



Inner classes in Java

A class inside another class inner or nested class
1. Nested class
2. Method local inner class
3. static inner class
4. Anonymous inner class


Nested Class


public class Outer {
  private String message="welcome to java inner classes";
  private class Inner{
    private String greetings="Hi! how are you?";
    public void display(){
      System.out.println(message);
    }
  }
  public void show(){
    System.out.println(message);
    System.out.println(new Inner().greetings);
  }
}
 
public class Outer {
  private String message="welcome to java inner classes";
  public class Inner{
    private String greetings="Hi! how are you?";
    public void display(){
      System.out.println(message);
    }
  }
  public void show(){
    System.out.println(message);
    System.out.println(new Inner().greetings);
  }
}
 
public class Manager {
  public static void main(String[] args) {
    Outer obj=new Outer();
    obj.show();
    /* Creation of the inner class object */
    Outer.Inner inner=obj.new Inner();
    /* Another way of creation of the inner class */
    Outer.Inner inn=new Outer().new Inner();
    inn.display();
  }
}
 
public interface Game {
  void play();
}
 
public class Car {
  public Game getGame(){
  return new MyGame();
  }

  private class MyGame implements Game{
    @Override
    public void play() {
      System.out.println("The Game is started");
    }
  }
}
 
public class GameMain {
  public static void main(String[] args) {
    Car c=new Car();
    Game g=c.getGame();
    g.play();
  }
}

 

Method local inner classes

class Example{
  public void printMessage(){
    final String greetings="Hi! how are you?";
    class User{
      private String message="Welcome to method local inner class";
      void print(){
        System.out.println(message+" "+greetings);
      }
    }
    User obj=new User();
    obj.print();
  }
}


public class MethodLocalInner {
  public static void main(String[] args) {
    Example obj=new Example();
    obj.printMessage();
  }
}

Static inner classes


class StOuter{
  static class StInner{
    void print(){
      System.out.println("Hello");
    }
  }
}

public class StaticInnerDemo {
  public static void main(String[] args) {
    StOuter.StInner obj=new StOuter.StInner();
    obj.print();
  }
}

Anonymous Inner Classes

interface One{
  void show();
}

public class AnonymousDemo {
  public static void main(String[] args) {
    
    One obj=new One() {
        @Override
        public void show() {
          System.out.println("Welcom to Bangalore");
        }
    };
    obj.show();
  }
}

Wednesday, August 15, 2012

Factory Method Design pattern

A factory method pattern is a creational pattern. It is used to instantiate an object from one among a set of classes based on a logic.






package com.jsl.core;
interface Instrument{
  public void play();
}

class Guitor implements Instrument{
  @Override
  public void play() {
   System.out.println("TIN TIN TIN TIN TIN TIN ......");
  }
}

class Piano implements Instrument{
  @Override
  public void play() {
   System.out.println("PPPPPPPEEE PEEEE PEEE .....");                  
  }
}

class InstrumentFacoty{
 public Instrument getInstrument(String name){
     Instrument obj=null;
     if(name.equalsIgnoreCase("Guitor"))
      obj=new Guitor();
     else if(name.equalsIgnoreCase("Piano"))
      obj=new Piano();
     return obj;
   }
}

public class FactoryMethod {
  public static void main(String[] args) {
   InstrumentFacoty obj=new InstrumentFacoty();
   Instrument ins=obj.getInstrument("piano");
   ins.play();
  }
}

Singleton Design Pattern

Singleton Design Pattern:

The singleton pattern is one of the simplest design patterns. it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance. in this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.


Example:

package com.jsl.core;
import java.io.Serializable;
 
public class Singleton implements Serializable{
 
   private static final long serialVersionUID = 1L;
   private static Singleton obj;
 
   private Singleton() {
   }
 
   public static Singleton getObject() {
      if (obj == null) {
        synchronized (Singleton.class) {
          if (obj == null)
              obj = new Singleton();
        }
      }
      return obj;
   }
   @Override
   protected Object clone() throws CloneNotSupportedException {
    
     throw new CloneNotSupportedException("Object can't be created by using clone method");
                        
   }
}

Creating immutable object



Creating immutable object:


             String object are immutable objects, We can also create  immutable object in the following way...

package com.jsl.core;

final class Example{
 private final int count;
 
 public Example() {
  count=5;
 }

 public Example(int count){
  this.count=count;
 }

 public Example increment(int incrementVal){
  return new Example(this.count+incrementVal);
 }

 @Override
 public String toString() {
  return " "+count;
 }

}
public class ImmutableDemo {

  public static void main(String[] args) {

   Example e=new Example();
   System.out.println(e);
   System.out.println(e.increment(10));
   System.out.println(e);
  }
}

output:

5
15
5

Monday, July 2, 2012

Properties file in java

Properties file

1.  The properties file is a simple text file
2.  Properties file contains keys and values
3.  All the properties file are saved with the ".properties"   extension
4.  properties file is always used to store the configuration data or settings

Write Properties into properties file


package com.jsl.examples;
import java.io.FileOutputStream;
import java.util.Properties;
public class WritingProperties {

       public static void main(String[] args) {

             Properties properties=new Properties();
             FileOutputStream fos=null;
             try {
                     System.out.println("Hello");
                     fos=new FileOutputStream("connconfig.properties");
                     properties.setProperty("username", "Lakshman");
                     properties.setProperty("password", "Lakshman");
                     properties.store(fos,"User information example");
                     fos.close();

             } catch (Exception e) {
                    e.printStackTrace();
             }
       }
}

Reading properties


package com.jsl.examples;
import java.io.FileInputStream;
import java.util.Properties;
public class ReadingProperties {

   public static void main(String[] args) {
       FileInputStream fis=null;
       Properties properties=null;
       try{
              fis=new FileInputStream("connconfig.properties");
              properties=new Properties();
              properties.load(fis);
              System.out.println("User name :"+properties.getProperty("username"));
             System.out.println("Password :"+properties.getProperty("password"));
             fis.close();
       }catch (Exception e) {
              e.printStackTrace();
       }
   }
}

Spring Framework


Reading Properties file values and setting bean properties in spring framework

userinfo.properties

user.email=lakshman@gmail.com
user.password=lakshman

User.java


package com.cg.example;

public class User {
             private String email;
             private String password;
             public String getEmail() {
                    return email;
             }
             public void setEmail(String email) {
                    this.email = email;
             }
             public String getPassword() {
                    return password;
             }
             public void setPassword(String password) {
                    this.password = password;
             }
}

User.xml






             
                    user.properties
             

      

                    
                    
       


Manager.java


package com.cg.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {

       public static void main(String[] args) {
       ApplicationContext context=new ClassPathXmlApplicationContext("user.xml");
      
                    User user=(User) context.getBean("user");
                    System.out.println(user.getEmail());
                    System.out.println(user.getPassword());
            
  }
}

Output :

lakshman@gmail.com
lakshman

Wednesday, May 30, 2012

Reflection API in java

Java Reflection API

Reflection is a feature in the Java programming language. Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.



Example.java

package com.jsl.core;
import java.lang.reflect.Method;
class Example{
 public void display(){
  System.out.println("The Display Method");
 }
 public void show(){
  System.out.println("The Show Method");
 }
 private void print(){
  System.out.println("The Print Method");
 }
}

GetMethods.java

public class GetMethods {
 public static void main(String[] args) {
  try{
       Class c=Class.forName("com.jsl.core.Example");
       Method method[]=c.getDeclaredMethods();
       for(Method name:method)
        System.out.println(name);
     }catch (Exception e) {
       System.out.println(e);
     }
 }
}

output

private void com.jsl.core.Example.print()
public void com.jsl.core.Example.display()
public void com.jsl.core.Example.show()
getDeclaredClasses()

Returns an array of Class objects reflecting all the classes and interfaces declared as members of the class represented by this Class object. This includes public, protected, default access, and private classes and interfaces declared by the class, but excludes inherited classes and interfaces. This method returns an array of length 0 if the class declares no classes or interfaces as members, or if this Class object represents a primitive type, an array class, or void.


try{
    Class c=Class.forName("com.jsl.core.Example");
    Method method[]=c.getMethods();
    for(Method name:method)
      System.out.println(name);
}catch (Exception e) {
     System.out.println(e);
}
Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and and those inherited from superclasses and superinterfaces. The elements in the array returned are not sorted and are not in any particular order. This method returns an array of length 0 if this Class object represents a class or interface that has no public member methods, or if this Class object represents an array class, primitive type, or void.


isInstance( )

Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.

public class GetMethods {
  public static void main(String[] args) {
   try{
       Class c=Class.forName("com.jsl.core.Example");
       boolean b1=c.isInstance(new Example());
       System.out.println(b1);
       boolean b2=c.isInstance(new String());
       System.out.println(b2);
  }catch (Exception e) {
    System.out.println(e);
  }
 }
}

output:

true
false

Program to find the methods of the class.

package com.jsl.core;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

class Example{
 public void display(){
  System.out.println("The Display Method");
 }
 public void show(int a,int b){
  System.out.println("The Show Method");
 }
 private void print(Object object){
  System.out.println("The Print Method");
 }
}

public class GetMethods {
 public static void main(String[] args) {
  try{
     Class c=Class.forName("com.jsl.core.Example");
     Method methods[]=c.getDeclaredMethods();
     for(Method method:methods){
      System.out.println("***********************************************"); 
      System.out.println("Method modifier :" + Modifier.toString(method.getModifiers()));
      System.out.println("Method name : "+method.getName());
      System.out.println("Metho return type: "+method.getReturnType());
      Class params[]=method.getParameterTypes();
      for(int i=0;i < params.length;i++){
        System.out.println("Param [i] "+" = "+params[i]);
      }
    }
  }catch (Exception e) {
    System.out.println(e);
  }
 }
}

output:

******************************************************
Method modifier :private
Method name : print
Metho return type: void
Param 0 = class java.lang.Object
******************************************************
Method modifier :public
Method name : display
Metho return type: void
******************************************************
Method modifier :public
Method name : show
Metho return type: void
Param 0 = int
Param 1 = int

Obtaining Information About Constructors
A similar approach is used to find out about the constructors of a class.
package com.jsl.core;
import java.lang.reflect.Constructor;
class Example{
  private Example(){
  }
  private Example(int a,int b){
  }
  private Example(String name,String email){
  }
}
public class GetMethods {
 public static void main(String[] args) {
  try{
    Class c=Class.forName("com.jsl.core.Example");
    Constructor constructors[]=c.getDeclaredConstructors();
    for(Constructor constructor:constructors)
     System.out.println(constructor);
  }catch (Exception e) {
    System.out.println(e);
  }
 }
}

output:

private com.jsl.core.Example()
private com.jsl.core.Example(int,int)
private com.jsl.core.Example(java.lang.String,java.lang.String)


Finding Out About Class Fields
It's also possible to find out which data fields are defined in a class.
package com.jsl.core;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
class Example{
 private int val=23;
 final String name="jsltech";
 private final int id=1001;
 private static int count=9999;
 }
 public class GetMethods {
  public static void main(String[] args) {
   try{
      Class c=Class.forName("com.jsl.core.Example");
      Field fields[]=c.getDeclaredFields();
      for(int i=0;i < fields.length;i++){
        Field field=fields[i];
        System.out.println("Field Name : "+field.getName());
        System.out.println("Field Modifier: "+Modifier. toString(field.getModifiers()));
        System.out.println("Filed Type :"+field.getType());
        System.out.println("************************************");
      }
   }catch (Exception e) {
    System.out.println(e);
   }
 }
}

Output:

Field Name : val
Field Modifier: private
Filed Type :int
************************************
Field Name : name
Field Modifier: final
Filed Type :class java.lang.String
************************************
Field Name : id
Field Modifier: private final
Filed Type :int
************************************
Field Name : count
Field Modifier: private static
Filed Type :int
************************************


To know about the super class and implemented interfaces
package com.jsl.core;
class One{
}

interface InterfaceTwo{
}

interface InterfaceOne{
}

class Two extends One implements InterfaceOne{
}

public class GetMethods {
 public static void main(String[] args) {
  try{
     Class c=Class.forName("com.jsl.core.Two");
     System.out.println("The super class is : "+c.getSuperclass());
     Class cls[]=c.getInterfaces();
     System.out.println("The Implemented interface are :");
     for(Class cl:cls){
       System.out.println(cl);
     }
  }catch (Exception e) {
    System.out.println(e);
  }
 }
}

output:

The super class is : class com.jsl.core.One
The Implemented interface are :
interface com.jsl.core.InterfaceOne
interface com.jsl.core.InterfaceTwo

Invoking the method by Name
so far the method can be called by using object name or classes name, we can invoke the method by using reflection api, here is simple example to invoke the method
package com.jsl.core;
import java.lang.reflect.Method;
class One{
 public String fullName(String fname,String lname){
  return fname.concat(" ").concat(lname);
 }
}
public class GetMethods {
 public static void main(String[] args) {
  try{
    Class c=Class.forName("com.jsl.core.One");
    Method method=c.getMethod("fullName",new Class[] {String.class,String.class});
    String fullName=(String)method.invoke(new One(),new Object[]{"JSL","Tech"});
    System.out.println("The full name is :"+fullName);
  }catch (Exception e) {
    System.out.println(e);
  }
 }
}
Output:
The full name is : JSL Tech
Creating New Objects
There is no equivalent to method invocation for constructors, because invoking a constructor is equivalent to creating a new object (to be the most precise, creating a new object involves both memory allocation and object construction).
package com.jsl.core;
import java.lang.reflect.Constructor;
class One{
  public One(){
   System.out.println(" The constructor is invoked ");
  }
  public String fullName(String fname,String lname){
   return fname.concat(" ").concat(lname);
  }
}
public class GetMethods {
 public static void main(String[] args) {
  try{
     Class c=Class.forName("com.jsl.core.One");
     Constructor constructor=c.getDeclaredConstructor();
     One obj=(One) c.newInstance();
     System.out.println(obj.fullName("JSL", "Tech"));
  }catch (Exception e) {
    System.out.println(e);
  }
 }
}

Output:

The constructor is invoked
JSL Tech
Changing the values of field by using refilection api
package com.jsl.core;
import java.lang.reflect.Field;
class One{
  public String name="miani";
}
public class GetMethods {
 public static void main(String args[]){
  try {
      Class c=Class.forName("com.jsl.core.One");
      Field filed=c.getField("name");
      One obj=new One();
      System.out.println("The name is :"+obj.name);
      filed.set(obj, "Jsl Tech");
      System.out.println("The name after modification :"+obj.name);
  }catch (Throwable e) {
    System.err.println(e);
  }
 }
}

output:

The name is :miani
The name after modification :Jsl Tech

Monday, May 21, 2012

Exception handling in java

Exceptions

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

Checked Exceptions

Checked exceptions are subclass’s of Exception excluding class RuntimeException and its subclasses. Checked Exceptions forces programmers to deal with the exception or that may be thrown by using throws clause.

Unchecked exceptions

Unchecked exceptions are RuntimeException and any of its subclasses. however, the compiler doesn’t force the programmers to either catch the exception or declare it in a throws clause. In fact, the programmers may not even know that the exception could be thrown.

Exceptions Hierarchy













In java exception handling can be done by using following keywords

try             catch               finally                      throw              throws


try block

The try block encloses the statements that might raise an exception within it and defines the scope of the exception handlers associated with it. A try block must be accompanied by at least one catch block or one finally block.

catch block

The catch block is used as an exception-handler. You enclose the code that you want to monitor inside a try block to handle a run-time error. catch block is an exception handler and handles the type of exception indicated by its argument. The catch block contains code that is executed if and when the exception handler is invoked.

throw

The “throw” keyword is used to manually throw user define exception or custom exception.

throws

When a method is capable of throwing an exception that it does not handle by itself it must declare so with the help of the throws clause.

finally

The finally block also known as resource handler, a try can have only one finally, the finally must be written after the catch block.


ExceptionDemo.java

package com.jsl.core;
import java.util.Scanner;
public class ExceptionDemo {
  public static void main(String[] args) {
    System.out.println("Main method begans");
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter the a value : ");
    int a=sc.nextInt();
    System.out.println("Enter the b value :");
    int b=sc.nextInt();
    int res=a/b;
    System.out.println("The a / b is : "+res);
    System.out.println("Main method ends");
  }
}

output:
Main method begans
Enter the a value : 
101
Enter the b value :
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
             at com.jsl.core.ExceptionDemo.main(ExceptionDemo.java:11)

When 101/0 which leads to ArithmeticException, programmer didn't handle the exception then JVM handles exception and program will be terminated.


ExceptionDemo.java

package com.jsl.core;
import java.util.Scanner;
public class ExceptionDemo {
  public static void main(String[] args) {
    
    System.out.println("Main method begans");
    
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter the a value : ");
    int a=sc.nextInt();
    System.out.println("Enter the b value :");
    int b=sc.nextInt();
    
    try{
       int res=a/b;
        System.out.println("The a / b is : "+res);
    }catch (Exception e) {
        System.out.println(e);
    }
    System.out.println("Main method ends");
  }
}

output
Main method begans
Enter the a value : 
101
Enter the b value :
0
java.lang.ArithmeticException: / by zero
Main method ends
When 101/0 which leads to ArithmeticException in try block that exception will be thrown to the catch block and handled. Then prints “Main method end” and programm will be terminated.


try with finally:
package com.jsl.core;
import java.util.Scanner;
public class TrywithFinally {
  public static void main(String[] args) { 
    System.out.println("Main method begans");
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter the a value : ");
    int a=sc.nextInt();
    System.out.println("Enter the b value :");
    int b=sc.nextInt();
    
    try{
       int res=a/b;
       System.out.println("The a / b is : "+res);
    }finally{
       System.out.println("Finally block");
    }
    System.out.println("Main method ends");
  }
}
OutPut:
Main method begans
Enter the a value : 
101
Enter the b value :
0
Finally block
Exception in thread "main" java.lang.ArithmeticException: / by zero
             at com.jsl.core.TrywithFinally.main(TrywithFinally.java:14)
When 101 / 0 then its leads to ArithmaticException there is no catch block to handle then JVM handles that exception before termination it exectues finally block then terminates the program.

try inside return statement and with finally
package com.jsl.core;
import java.util.Scanner;
public class TrywithFinally {
  public static void main(String[] args) {
    System.out.println("Main method begans");
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter the a value : ");
    int a=sc.nextInt();
    System.out.println("Enter the b value :");
    int b=sc.nextInt();
   
    try{
       int res=a/b;
       System.out.println("The a / b is : "+res);
       return;
    }catch (Exception e) {
       System.out.println(e);
    }
    finally{
       System.out.println("Finally block");
    }
    System.out.println("End of Main method");
  } 
}

Output
Main method begans
Enter the a value : 
100
Enter the b value :
10
The a / b is : 10
Finally block
Here try block contains return statement before execution of the return statement JVM exectues the finally block then return statement will be executed.


try with the multiple catch blocks


package com.jsl.core;

import java.util.Scanner;

public class TryWithMultipleCatch {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int regno=0;
    String name=null;
    float average=0.0f;
    int total=0;
    try {
      System.out.println("Enter the regno ");
      regno= sc.nextInt();
      System.out.println("Enter the Name ");
      name= sc.next();
      name=name.substring(0,4);
      System.out.println("Enter the no subjects ");
      int no=sc.nextInt();
      int marks[] = new int[no];
      for (int i = 0; i < marks.length; i++) {   
        System.out.println("Enter " + (i + 1) + " Marks"); 
        marks[i] = sc.nextInt();  
      }   
      for(int mark:marks) 
        total=total+mark;     
        average=total/no;      
    } catch (ArrayIndexOutOfBoundsException e) { 
        System.out.println("Please check the array size " + e); 
    }catch (StringIndexOutOfBoundsException e) {  
        System.out.println("Please check the name " + e);   
    } catch (ArithmeticException e) {  
        System.out.println("Please check the total subjects" + e);  
    } catch (Exception e) {  
        System.out.println(e); 
    }   
    System.out.println("The regno is :"+regno);   
    System.out.println("The name "+name); 
    System.out.println("The total marks"+total); 
    System.out.println("The average is :"+average);
  } 
}  

When you write try with multiple exceptions, the super class exception must be last catch block, other wise compilation error.

catch (Exception e) {    
  System.out.println(e);   
}catch (ArrayIndexOutOfBoundsException e) {    
  System.out.println("Please check the array size " + e);   
}catch (StringIndexOutOfBoundsException e) {    
  System.out.println("Please check the name " + e);   
} catch (ArithmeticException e) {    
  System.out.println("Please check the total subjects" + e);   
}   

from java 1.7

try{  -----  ----- 
}catch (ArrayIndexOutOfBoundsException e |StringIndexOutOfBoundsException e) {     System.out.println(e); 
}      


try inside try catch


package com.jsl.core;  
import java.util.Scanner;  
public class TryInsideTry {   
  public static void main(String[] args) {    
    try{     
      System.out.println("Enter the salary ");     
      Scanner sc=new Scanner(System.in);     
      int salary=sc.nextInt();     
      System.out.println("Enter the exp ");     
      int exp=sc.nextInt();     
      int bonus=0;            
      try{       
         int per;        
         if(exp>10){
           System.out.println("Enter percentage");
           per=sc.nextInt();
           bonus=salary*per/100;
         }else{
           System.out.println("Enter percentage");
           per=sc.nextInt();
           bonus=salary*per/0;
         }
      }catch (StringIndexOutOfBoundsException e) {
        System.out.println(e);
      }
      System.out.println("The salary is :"+salary);
      System.out.println("The Total salary is :"+(salary+bonus));
   }catch (Exception e) {
   System.out.println(e);
  }
 }
}


catch inside try catch


package com.jsl.core;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class CatchInsideTryCatch {
 public static void main(String[] args) {
  System.out.println("The main method Starts");
  FileOutputStream fis = null;
  try {
   int a = 100 / 0;
  } catch (Exception e) {
   try {
    fis = new FileOutputStream("lakshman.txt");
    ObjectOutputStream obs = new ObjectOutputStream(fis);
    obs.writeObject(e);
   } catch (Exception e1) {
    System.out.println(e1);
   }

   System.out.println(e);
  }
  System.out.println("The main method ends ");
 }
}


finally with try catch


package com.jsl.core;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DbConnection {
 public static void main(String[] args) {
  System.out.println("Main method starts");
  Connection con = null;
  Statement st = null;
  ResultSet rs = null;
  try {
   Class.forName("oracle.jdbc.driver.OracleDriver");
   con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "java", "java");
   st = con.createStatement();
   rs = st.executeQuery("select empno,ename,sal from emp");
   while (rs.next()) {
    System.out.println(rs.getInt("empno"));
    System.out.println(rs.getString("ename"));
    System.out.println(rs.getDouble("sal"));
   }
  } catch (Exception e) {
   System.out.println("While connecting with database :" + e);
  }
  finally {
   try {
    rs.close();
    st.close();
    con.close();
   } catch (Exception e) {
    System.out.println("While closing : " + e);
   }
  }
  System.out.println("End of the main method");
 }
}

package com.jsl.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ThrowsDemo {
 public static void main(String[] args) throws IOException, NumberFormatException {
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter the item namedd ");
  String item = br.readLine();
  System.out.println("Enter the price");
  double price = Double.parseDouble(br.readLine());

  System.out.println("The message is :" + item);
  System.out.println("The price is :" + price);

 }
}


throw


package com.jsl.core;
public class Product {
 private int pid;
 private String pname;
 private double price;
 public Product(int pid, String pname, double price) {
  if (price & lt; 0)
   throw new IllegalArgumentException("please check the price once it should be - value");
  this.pid = pid;
  this.pname = pname;
  this.price = price;
 }
 @ Override public String toString() {
  return pid + " " + pname + " " + price;
 }
}

package com.jsl.core;
public class Product {
 private int pid;
 private String pname;
 private double price;
 public Product(int pid, String pname, double price) {
  if (price & lt; 0)
   throw new IllegalArgumentException("please check the price once it should be - value");
  this.pid = pid;
  this.pname = pname;
  this.price = price;
 }
 @ Override public String toString() {
  return pid + " " + pname + " " + price;
 }
}

User defined Exceptions:


Though Java provides an extensive set of in-built exceptions, there are cases in which we may need to define our own exceptions.


  1. User defined exceptions can be created by extending Excetion class or RuntimeException
  2. User defined Excetion extends Exception then it become checked exception.
  3. User defined Excetion extends RuntimeExcetion it become Unchecked Excetions


Let us see a simple example to learn how to define and make use of user defined exceptions.


InsufficientFundException.java

package com.jsl.excetion.demo;

public class InsufficientFundException extends RuntimeException {

        String message;

        public InsufficientFundException(String message) {

           this.message=message;

        }

public String toString() {

        return "Exception occurred.. " + message;

        }

}

MaxCount.java

package com.jsl.demo;
public class MaxCount extends RuntimeException {

    int count;

    public MaxCount(int count) {

       this.count=count;

    }

    @Override
    public String toString() {

        return " Maximum count reached "+count;

    }

}

BankAccount.java

package com.jsl.demo;

import java.util.Scanner;

import com.jsl.excetion.demo.InsufficientFundException;

public class BankAccount {

          private int balance = 3000;

         volatile int count = 0;

 

         public void withDraw() {

             if (count > 2)

              throw new MaxCount(count);

              System.out.println("Enter the amount to with draw");

              Scanner sc = new Scanner(System.in);


                 int amount = sc.nextInt();

                   if (amount > balance)

                     throw new InsufficientFundException("Sorry you don't sufficient balance ");

                   else {

                     balance = balance - amount;

                     System.out.println("Thank for using your balance is : " + balance);

                       }

                   count++;

             }

}

Main.java

package com.jsl.demo;

import java.util.Scanner;

import com.jsl.excetion.demo.InsufficientFundException;

public class Main {

             public static void main(String[] args) {

                    BankAccount account = new BankAccount();

             for (;;) {

                try {

                  System.out.println("1.Withdraw 2. exit");

                  System.out.println("Enter the choice");

                  int ch = new Scanner(System.in).nextInt();

                  if (ch == 1)

                     account.withDraw();

                     if (ch == 2)

                        System.exit(0);

                   } catch (InsufficientFundException e) {

                        System.out.println(e);

                   } catch (MaxCount e) {

                        System.out.println(e);

                   } catch (Exception e) {

                        System.out.println(e);

                   }

            }

        }

}

Monday, January 23, 2012

Overloading and Overriding in Java


Overloading:

                  Java allows you to define two or more methods with the same name and different parameter list in one class.  Defining two or more methods with the same in one class are called as Method Overloading.

package com.jsl.core;
public class OverLoadingDemo {
                        public int add(int a,int b){
                                    return a+b;
                        }
                        public int  add(int a,int b,int c){
                                    return a+b;
                        }
                        public int  add(String a,String b){
                                    return Integer.parseInt(a)+Integer.parseInt(b);
                        }
}


Overloading also known as static binding or early binding or compile-tem polymorphism. The overloading method is binded with respective to reference variable by compiler based on method arguments.


package com.jsl.core;
public class MathOperations {
            public int sum(int a,int b){
                        return a+b;
            }
            public float sum(float a,float b){
                        return a+b;
            }
            public static void main(String[] args) {
                       
MathOperations obj=new MathOperations();
                       
System.out.println("The sum is :" +obj.sum(10, 10.5f));
                       
System.out.println("The sum is :"+obj.sum(10, 10));
                       
            System.out.println("The sum is :"+obj.sum(10.5f, 10.5f));
            }
}

Output:

The sum is :20.5
The sum is :20
The sum is :21.0


In case of method overloading, at the time of compilation compiler look for exact match parameter method. If method doesn’t have with exact matched parameter then compiler try to promotes the parameters.


package com.jsl.core;
public class MathOperations {
            public double sum(double a,double b){

                        return a+b;
            }
            public static void main(String[] args) {
                       
MathOperations obj=new MathOperations();
                       
double res=obj.sum('a', 'a');
                       
System.out.println("The sum is :" +res);
            }
}

Output:
The sum is :194.0

Here at the time of compilation the compiler try to find the exact match parameter method obj.sum('a', 'a') but there is no method with two characters, then compiler promotes character parameters double type and bind that method with the reference variable.

Over loading with objects:

package com.jsl.core;
public class Member {
                        private int id;
                        private String name;
                        Member(int id,String name){
                                    this.id=id;
                                    this.name=name;
                        }
                        @Override
                        public String toString() {
                                    return "Id is : "+id+"  Name is : "+name;
                        }
}


package com.jsl.core;
public class MethodOverloading {
          
      public void showInfo(Object obj){
                       
System.out.println(obj);
            }
           
      public void showInfo(Member obj){
                       
System.out.println(obj);
            }
           
      public static void main(String[] args) {
                       
MethodOverloading obj=new MethodOverloading();
                        obj.showInfo(new Object());
                        obj.showInfo("JSL TECH");
                        obj.showInfo(new Member(1001, "Lakshman"));
            }
}

Output:

java.lang.Object@addbf1
JSL TECH
Id is : 1001  Name is : Lakshman

Here there is no method with the showInfo( ) with string parameter. The compiler promotes to super class type and invokes the object class method.

Example:
package com.jsl.core;

public class MethodOverloading {
            public void showInfo(String name){
                        System.out.println(name);
            }
            public void showInfo(StringBuffer name){
                        System.out.println(name);
            }
            public static void main(String[] args) {
                       
            MethodOverloading obj=new MethodOverloading();
                        obj.showInfo(new Object());
            }

}

Here it leads to compilation error, because object() can’t be caste to the String or StringBuffer type. So leads compilation error.

Overriding:


Sometimes you inherit a method that doesn't meet the requirements for a subclass. When this happens, you can override the method in subclass.

The rules for overriding as follows:

·         The overriding method must have same name and same parameter list.

·         The overriding method access specifier should be same or less restrictive; it should not be more restrictive.

Private --------> (default)    ------->    protected ---------> public

·         Return type must be same, except co-variant type.

·         In the overriding method declaration, the exception should be same exception or without exception or narrow exception.  It shouldn’t be new or border exception.

·         The static method can’t be override as non static method.

Example:

package com.jsl.core;
class Person{
            private int id;
            private String name;
            Person(int id,String name){
                        this.id=id;
                        this.name=name;
            }
            @Override
            public String toString() {
                        return "The id is : "+id+"\nThe name is :"+name;
            }
}
public class OverridingDemo {
            public static void main(String[] args) {
                        Person person=new Person(1001, "JSL Tech");
                        System.out.println(person);
            }
}

Output:

The id is : 1001
The name is :JSL Tech

The toString( ) method is object class method which return the string. By default it returns ClassName+hashCode, but in our case we overriding the toString method in Person class which return the object content is the form of String.


Co-variant type in method overriding example

package com.jsl.core;
class One{
            public Number getValue(){
                        return 1000;
            }
}
class Two extends One{
            @Override
            public Float getValue(){
                        return 3000.5f;
            }
           
}
public class OverridingDemo {
            public static void main(String[] args) {
                        One obj=new Two();
                        System.out.println("The value is :"+obj.getValue());
            }
}


Output:

The value is: 3000.5

Here the super class method return type is Number class, and in the sub class method return type is Float. All the numbered class super class is object class. This is called co-variant type.


Overriding method can’t reduce the visibility:

package com.jsl.core;

class One{
            protected void display(){
                        System.out.println("The display method one");
            }
            void show(){
                        System.out.println("The show method one");
            }
            public void print(){
                        System.out.println("The print method of one");
            }
}

class Two extends One{
            @Override
            public void display() {
                        System.out.println("The display method of two");
            }
            @Override
            protected void show(){
                        System.out.println("The show method of two");
            }
            @Override
            public void print() {
                                    System.out.println("The print method of two");
            }
}

Here the default show( ) method is overridden as the protected show( ) method. In overriding method we should give same acess




Overloading
Overriding
Writing two or more methods with same name and different parameter list(i.e order or number of parameter must be different) in same class is called overloading
Writing super class methods in the sub class with same name and same parameter list is called method overriding.  
Return type can be change
Return type must be same, except co-variant type
Access specifier can be change
Access Specifier should be same or less restrictive he should not be more restrictive
The exception can be change
The exception should be same exception or without exception or narrow exception.  It shouldn’t be new or border exception.

Spring Boot 3 : JWT with SecurityFilterChain, AuthorizeHttpRequests, RequestMatchers

pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0...