Saturday 15 September 2018

Java Program to Check Palindrome String

          A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. Madam, mum, dad, 12321,racecar etc are palindrome string. Below is the java program to check whether you entered string is a palindrome or not.



Thursday 13 September 2018

What exactly does @Override do in Java?

       @Override is annotation which is used to make compiler check all rules of overriding.If we don't write @Override over the method, then compiler will apply all overriding rules only if below three point are :
1. There are super class and sub class relation.
2. Method names are same.
3. Parameters are same.
But if we have written as @Override on sub class method, then compiler must apply all rules irrespective of above three points.
Below are the examples which will explain the use of @Override annotation.
1. Example without @Override annotation.























In the above example, there is no compile time and run time error. We will get output.
Child is called.

2. Example with @Override annotation.
























In the above example, there is compile time error when we use @Override annotation that is we can not override private method.

Sunday 9 September 2018

Can we Override static methods in Java

            The process of implementing the super class method in sub class is called as method overriding. As per Java principle, classes are closed for modification. so if we want to modify a method in any class, changing existing method is not a good idea instead of that we should extend that class and override method in the child class.If we try to override the method which is static, compiler won't give any error but we will get the output that does not satisfy the definition of overriding.
For example, we have two classes Animal and Cat, in Animal class, we have declared two methods, one is static and another is not static and in Cat class, we have overridden the Animal class methods.
From the output of the below programs, we can say that static methods can not be overridden.































Output :
Animal class : The static method in Animal
Cat Class : The instance method in Cat

Saturday 8 September 2018

Can we Override private methods in Java.

          We can not override the private methods because scope of the private access specifier is only within the class. By the definition of overriding,when we want to override something, then there should be inheritance concept means we should have parent and sub class.When super class method is private that will not be visible to subclass, whatever the methods we are writing in sub class will be treated as new method and not a overridden method.
For example, We have written a private method in parent class and same method, we are trying to access in child class but compiler giving the error, thus we can say that we can not override private method.


Saturday 1 September 2018

How to create SharedPreference in Android.

Create one class

here is complete code how to create SharedPreference
    public class SessionManager {
    SharedPreferences pref;
    SharedPreferences.Editor editor;// Editor for Shared preferences
    Context _context;
    int PRIVATE_MODE = 0;
    private static final String PREFERENCES = "Preferences";
    public static final String UNAME = "uname";
    public static final String PNAME = "pname";
    public static final String TIME = "time";
    public static final String DATE = "date";
    public static final String ADDRESS = "address";
    private static final String PREF_NAME = "newApp";
    public SessionManager(Context context) {
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    public void saveDEtails(String uname, String pname, String time,
        String date,String address) {
        editor.putString(UNAME, uname);
        editor.putString(PNAME, pname);
        editor.putString(TIME, time);
        editor.putString(DATE, date);
        editor.putString(ADDRESS, address);
        editor.commit();
    }
    public HashMap getUserDetails(){
        HashMap user = new HashMap();
        user.put(UNAME, pref.getString(UNAME, null));
        user.put(PNAME, pref.getString(PNAME, null));
        user.put(TIME, pref.getString(TIME, null));
        user.put(DATE, pref.getString(DATE, null));
        user.put(ADDRESS, pref.getString(ADDRESS, null));
        return user;
    }
}
// And where you want to stored the data in SharedPreference
SessionManager mSession;
mSession = new SessionManager(getApplicationContext());
mSession.saveDEtails(nameu,namep,time,weddingdate,add);
//Here you can get value from SharedPreference
SessionManager mSession;
HashMap user;
mSession = new SessionManager(getApplicationContext());
user = mSession.getUserDetails();
String  username = user.get(SessionManager.UNAME); // get name
String  partnername = user.get(SessionManager.PNAME); // get email
String  time = user.get(SessionManager.TIME);
String date = user.get(SessionManager.DATE);
String address = user.get(SessionManager.ADDRESS);

Creating JDBC Connection in Java

Following are the steps to create JDBC connection in Java.

1. Register driver class.
2. Create connection object.
3. Create statement object.
4. Executing queriesoswd
5. Close connection.

Below are the code :
import java.sql.*;
class MysqlCon{
    public static void main(String args[]){
        try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection(
                           "jdbc:mysql://localhost:3306/test","root","admin");
           //here test is database name, root is username and admin is  password 
            Statement stmt=con.createStatement();
            ResultSet rs=stmt.executeQuery("select * from emp");
            while(rs.next()) {
                System.out.println(rs.getInt(1) + ":" + rs.getString(2) + ":" + rs.getString(3));
            }
            con.close();

        }catch(Exception e){ System.out.println(e);}

    }
}

Tuesday 28 August 2018

Defining Integer as Octal


Octal Number System :
  • Octal number system is the base 8 number system.
  • Legal digits in an octal literal can be 0 to 7 only.
  • If you try to write int a = 08 or a = 09 in Java, It will give compile time error.
  • Octal literal starts with leading zero, for example 010,023,011 etc.

Below is the Java program If we write int = 010, then we will be the output.

public class OctalNumberClass{

  public static void main(String []args){
     int abc = 010;
     System.out.println("Octal Values :"+abc);
  }
}

Output : Octal Values :8

Wednesday 22 August 2018

final, finally and finalize in Java

final :
  • final is a modifier applicable for classes, methods and variables.If a class is declared as final then we can't extend that class means we can not create child class for that class.
  • If a method is declared as final then we can't override that method in the child class.
  • If a variable is declared as final then it will become constant and we can't perform re-assignment for that variable.
finally : 
  • finally is a block always associated with try catch to maintain clean up code.
  • Code in the finally code will always be executed even if an exception is thrown.
  • finally block can be used instead of catch block.
  • Sample Code : 
       try
       {
            //risky code
       }
       catch(X e)
       {
            //Handling code
       }
       finally
      {
            //clean up code 
      }

finalize : 
  • finalize() is a method which is present in the object class.
  • Garbage Collector calls the finalize() method just before destroying the object to check which objects are eligible to garbage collect.
  • It is used to clean or release the resources i.e.closing database connection.
Important Point to remember :
      finally is meant for clean up activities related to try catch block and finalize() is meant for clean up activities related to object.

Tuesday 21 August 2018

How to create an immutable class in Java

To create an immutable class, you should consider below points:
  • Declare the class as final so that no one will extend the class.
  • Declare all the variables in the class as final so that no one can change the value of the variables.
  • Declare all variables as private so that others can not access directly.
  • Do not write setter methods so that others can not modify the actual value of the variables.
  • Write the parameterized constructor.
Example of Immutable Class :

public final class ABC {

    private final int id;
    private final String name;
    private final String address;

    public ABC(int id, String name,String address) {
        this.name = name;
        this.id = id;
        this.address = address;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getAddress() {
        return address;
    }
}

Use of Immutable Class :

class Test
{
    public static void main(String args[])
    {
        ABC abc = new ABC(1,"PQRS", "Pune");
        System.out.println(abc.id);
        System.out.println(abc.name);
        System.out.println(abc.address);
    }
}


Monday 6 August 2018

Difference bet Constructor and Method in Java

Constructor Method
Constructor must have the same name as the class
name.
Method name can be same or can not be same
as the class name.
Constructor is used to initialize the variables. Method is used to show the behaviour of the
object and we can write business logic.
Constructor does not return any type. Method must return any type otherwise
It will be consider as constructor.
Constructor is called when we create the object.
Ex. A a = new A();
We need to called the method explicitly when
we require.
Ex. A a = new A();
a.showMessage();
If we don’t write constructor in Java class, then
Java compiler consider the default constructor.
In case of method, Java compiler don’t act like
constructor.

Tuesday 31 July 2018

Constructor

       The Constructor is similar to method except constructor must have the same name as class name and it must not return any type. By default, every class have constructor whether we have declared or not. It is called when we create object using new keyword. for ex. A a = new A(). Constructor are used to initialize the objects. There are two types of constructor.
       i. Default Constructor
       ii. Parameterized Constructor.

Example of Default Constructor :

class XYZ{  
XYZ(){
System.out.println("XYZ is created");
}  
public static void main(String args[]){  
XYZ b=new XYZ();  
}  
}

Example of Parameterized Constructor :

class XYZ{  
    int id;  
    String name;  
      
    XYZ(int i,String n){  
    id = i;  
    name = n;  
    }  
    void show(){
System.out.println(id+" "+name);
   }  
   
    public static void main(String args[]){  
    XYZ x1 = new XYZ(1,"Mangesh");  
    XYZ x2 = new XYZ(2,"Harish");  
    x1.show();  
    x2.show();  
   } 
}