Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at diehardtechy@gmail.com

Wednesday, July 30, 2014

How to clean waste space from hard drive? With pre installed utility : Disk cleanup

           How to clean waste space from hard drive?


To clean the waste space from hard drive to get better system performance, windows provides a built in utility called disk cleanup.

How to use Disk cleanup.

Step 1.
Disk cleanup utility can be launched by either of the following ways.

Way 1.
--> Press window -- To launch run window
--> Type cleanmgr in run and hit enter-- To launch Disk cleanup.


               
Way 2.
--> Go to window search.
--> Search for disk cleanup by typing in search box. 


After the Disk cleanup utility is launched, select the drive from which you want to clean the waste space. And click Ok.

Based upon the amount of junk file system will take some time to calculate amount of space which can be cleaned.



After successful calculation a new window will be displayed. Which will look something like below.
It tells you how much amount of space you will be able to free. In the below case it is 3.00 MB.



Click OK, and it will clean the junk from your system.



OCJP Practice question #26 [Equals method]

What will be the output of the following Java program ?




Answer : option C


Explanation:

Option C is true as class A doesn't override the equals method, so it will be called from Object class, and in Object class equals method 



  • For any non-null reference value x, x.equals(null)should return false.




Vararg in Java : A detailed overview.



Varargs in Java was introduced since java 1.5, vararg reduces the complexity of overloading a method multiple times.This approach also benefits in terms of less code and code re-usability. Less code further benefits in easy code readability. 

Example prior to varargs

A simple problem to add 2 or more numbers requires the add method to be overloaded multiple times.

//OverloadingDemo.java

class OverloadingDemo
{
                //Function to add 2 numbers
                public int add(int x, int y)
                {
                                int add=x+y;
                                return add;
                }
               
                //Function to add 3 numbers
                public int add(int x, int y, int z)
                {
                                int add=x+y+z;
                                return add;
                }

                //Function to add 4 numbers
                public int add(int x, int y, int z, int i)
                {
                                int add=x+y+z+i;
                                return add;
                }

                public static void main(String [] args)
                {
                                //Object creation
                                OverloadingDemo od=new OverloadingDemo();
                               
                                //Invokes the add(int x, int y) method 
                                System.out.println(od.add(10,20));
                               
                                //Invokes the add(int x, int y, int z) method
                                System.out.println(od.add(10,20,30));
                               
                                //Invokes the add(int x, int y, int z, int i) method
                                System.out.println(od.add(10,20,30,40));
                }
               
}

Since, the above example code leads to repetition of code every time the number of variable increases, also repetition of code makes it harder for other programmer to understand the code.

Think of the above problem when, how many numbers to add are not known at code time?

To solve the above problem Java 1.5 has provided support for verarg type variables.

How the updated code of the above problem will look like after vararg.

//OverloadingDemo.java
class OverloadingDemo
{
                public int add(int...y)
                {
                                int add=0;
                                for(int i:y)
                                {
                                                add=add+i;
                                }
                                return add;
                }
                public static void main(String [] args)
                {
                                //Object creation
                                OverloadingDemo od=new OverloadingDemo();                             
                                System.out.println(od.add(10,20,30,40));
                               
                }
               
}

The above code solves the problem of addition when numbers to add are not known. Also it provides code re usability, better and easy to understand code. 

Rules on var-arg.

1. Vararg must be last parameter in method argument list. Else it leads to compile time error : ')' expected.

2. Vararg type parameter must follow the below syntax.

SYNTAX:

datatype ... variable_name

Violation of above syntax leads to compile time error malformed floating point literal.


3. You can only have 1 vararg variable in a method definition. Else it leads to compile time error.

Monday, July 28, 2014

How to save an image from MS word to JPG image file

You may have encounter a need to save graphic from word document to image file . 


Below article states about how to save an graphic from MS word to image file format.

Step by Step procedure.

1. Open your word document from which you want to save image.

2. Navigate to the image, right click on image, click copy.

Document.docx


3. Open MS powerpoint.




4. Paste the copied graphic in one of the slide.


5. Right click on image and click save as picture.




6. Choose the picture format you want your image file to save in.



Tuesday, July 15, 2014

Understanding Enum: Definition And Need Of Enum : Chapter 2

Before you read this tutorial we suggest you to first read Understanding Enum: Definition And Need Of Enum : chapter 1 

Every enum inherits methods from java.lang.Enum class. The important methods are

public final String name()
Returns name of the current enum exactly as declared in its enum declaration.

Public final int ordinal()
Returns current enum position.

 
Write a program to print name and ordinal of all enum objects of enum Months. 

//Months.java

enum Months
{
             JANUARY,FEBRUARY,MARCH,APRIL,MAY,
             JUNE,JULY,AUGUST,SEPTEMBER,OCTOBER,NOVEMBER,DECEMBER;
}

//MonthsNameAndOrdinal.java

class MonthsNameAndOrdinal
{
             public static void main(String[] args)
             {
                             Months []months=Months.values();

                             for(Months month:months)
                             {
                                             System.out.print(month.name());
                                             System.out.print("....");
                                             System.out.print(month.ordinal()+"\n");
                                            
                             }
             }

Q? How can we assign prices (values) to Menu items in enum ? Is below syntax is valid ?

enum Months
{
             JANUARY=1, FEBRUARY=2;
}

It is a wrong syntax, it leads to CE because named constants are not of type “int” they are of type “Months”. So we can not assign values to named constants directly using “=” operator.

Then how can we assign?

Syntax:

             Namedconstant (value)

             For example: JAN(1), FEB(2)

Rule: To assign values to names constants as shown in the above syntax, enum must have a parameterized constructor with the passed argument type. Else it leads to CE.


Q. )Where these values 1, 2 are stored?

A: ) We must create a non-static int type variable to store these values. So, to store these named constants values we must follow 3 rules in enum class.

·         We must create non-static variable in enum with the passed argument type.
·         Also we must define parameterized constructor with argument type.
·         Named constants must end with “;” to place normal variables, methods, constructor explicitly. It acts as separator for compiler to differentiate named constants and genegarl members. 


Below code shows defining enum constants with values.

//Months.java

enum Months
{
                JAN(1),FEB(2);
                private int num;
                Months(int num)
                {
                                this.num=num;
                }
                public int getNum()
                {
                                return num;
                }
                public void setNum(int num)
                {
                                this.num=num;
                }
}  


Write a program to print above Months as how the real Months items are appeared.

Expected output:
1. JAN
2. FEB

//Year.java

class Year
{
                public static void main(String [] args)
                {
                                Months [] month=Months.values();
                                for(Months mon:month)
                                {
                                                System.out.print(mon.getNum()+". ");
                                                System.out.println(mon.name());
                                }
                }
}



Monday, July 14, 2014

Understanding enum: Definition and need of enum : Chapter 1

Chapter 1

Understanding enum: 

Definition and need of enum

Enum is a type of class which is final. It is created by using the keyword “enum”. It is used for defining set of named constants those represents a menu kind of item.

For Example:
Hotel Menu, Bar Menu, Course Menu etc…

Before java 5 these menu items are created by usin class. Class has a problem in accessing these menu items, that is it cannot return or print item name as it is declared instead it returns or prints its value.

For Example:

//Months.java
class Months
{
                static final int JAN =1;
                static final int FEB =2;

                public static void main(String[] args)
                {
                                System.out.println(Months.JAN);
                                System.out.println(Months.FEB);
                }
}

Prints
1
2

Enum is introduced in Java 5 to solve above problems, it means to print menu item name not value.

Syntax: to create enum data type in java 5 a new keyword “enum” is introduced.

enum <enumName> 
{
                //menu items names with "," seperator
                                                   ;
                //normal all 8 members which you define in a nnormal class
}

Note: For creating above name constants just use only names do not use any datatype

//Months.java
enum Months{
                JAN, FEB;
}

//year.java
class Year
{
                public static void main(String[]args)
                {
                                System.out.println(Months.JAN);
                                System.out.println(Months.FEB);
}

Compilation
>javac Year.java
>java Year

Prints:
JAN
FEB

What is the data type of named constants in enum ?
Its data type is current enum type. It is added by compiler automatically.

For example

In the enum Months, Its named constants are converted as shown below

public static final Months JAN;
public static final Months FEB;

Please Note:
  •  Enum is a final class hence cannot be inherited.
  •  It is sub class of Java.lang.Enum.
  •  It is a abstract class which is the default super class for every enum type classes. Also it is implementing from Comparable and Serializable interfaces.
  •  Since every enum type is Comparable so we can add its objects to collection TreeSet object, also it can be stored in file as it is Serializable type.

Friday, July 11, 2014

Overriding in java: a detailed overview, conditions and rules

Overriding in java: a detailed overview, conditions and rules

When a subclass has the instance method with same signature as in super class it is known as overriding.

Overriding is also known as run time polymorphism.

Signature: name of the method and parameters (including their types)

Class Example
{
                public void m1(int x, float y)
                {
                                System.out.println("Method m1");
                }
}

m1(int x, float y) -----signature

Note:

1. Only inherited method can be overridden.

2. Final method cannot be overridden.

3. The access specifiers for an overriding method can allow more, but not less, access than the overridden method.

For example, a protected instance method in super class can be made public, but not private, in the subclass.

Range from weaker to higher.
private--->default--->protected--->public

4. Return type of the sub class method must have same or sub return type of super class method return type but not sibling.

Otherwise compiler will throw an error saying return type not matched.  

5. If a super class method is throwing any exception sub class method can/can't throw the exception but vice versa is not true.

If super class method is throwing an exception, child class should also throw the same or sub exception.  Sub class method can't throw the Parent or higher exception than super class method.

Example:
class A
{
                public String ma(String[] args) throws ArithmeticException
                {
                                System.out.println("Hello World!");
                                return "";
                }
}

class B extends A
{
                public String ma(String[] args) throws Exception
                {
                                System.out.println("Hello World!");
                                return "";
                }
}



Example of overriding:

class Parent
{
                public void m1(int x, int y)
                {
                                System.out.println("Parent class M1 method");
                }
}

class Child extends Parent
{
                public void m1(int x, int y)
                {
                                System.out.println("Child class M1 method");
                }
}

class Test
{
                public static void main(String [] args)
                {
                                Parent p=new Child();
                                p.m1(10,20);
                }
}

OUTPUT:
Child class M1 method



If you run into any issue or have any doubt you can ask in comments. 

Thursday, July 10, 2014

How to speed up slow computer using IObit

Step 1 Go to http://www.iobit.com/

Step 2 Click Free download button on the home page.This looks like something below.



Step 3 As a result of step 2 you will have a file in your download folder which named as
AdvancedSystemCare-Installer.exe

Step 4 Double click on the file and run it. A new window will open (have patient, depending upon your system performance it may take time to arrive), which looks like something below.


Step 5 Click custom install, by default standard installation will be selected. Check/ Uncheck the yahoo, bing, etc. toolbar options, and click install. The screen shot follows. You can select standard install button if you want to install iobit recommended settings.



Step 6 It will download the setup and again will take some time to download (Remember your internet speed matters) after successful downloading it will install the software.


Step 7 on the next screen click next or no thanks.





Step 8: on the next window click next, next, next, and on last screen click start now.

Step 9: on the main window, select the options according to your wish and click scan.



The scan feature of Iobit will scan your system for issue and ask you to fix those.

If you want to boost your system's performance like never before , enjoy their premium version by clicking activate now button on main screen on application.

Wednesday, July 9, 2014

Java program to change the content of files : Java IO

Hello All,

In real time projects we need to change the contents of file, numbers in the file etc.

For example if you have a text file say "source.txt" and you want to replace some text like "abc" with "xyz" as shown below, Java has given a IO library which provides facility to cover this requirement.


Example Image :


Code to replace content of the file source.txt

import java.io.*;
class ReplaceWords
{
public void replaceWord()throws Exception
{
BufferedReader br=new BufferedReader(new FileReader("source.txt"));
StringBuilder sb=new StringBuilder();
while(br.ready())
{
sb=sb.append(br.readLine()+"\n");
}

String data=sb.toString();
data=data.replace("abc","xyz");

FileWriter fw=new FileWriter("destination.txt");
fw.write(data);
fw.flush();
br.close();
fw.close();
}

public static void main(String[] args) throws Exception
{
ReplaceWords rw=new ReplaceWords();
rw.replaceWord();
}
}


Make sure you have a input file "source.txt" in your current working directory, otherwise the above program will throw an exception saying FileNotFound. 

Above code will replace abc in source.txt with xyz and write them in new file destination.txt

If you want to save the contents in same file then just change the name destination.txt in code with source.txt

check below image to see what happens when the file not found.

When source file not found.


To run the above program just paste the above code in java editor and run.

If you run into any issue or have any questions, you can send us an email. Our mail id is diehardtechy@gmail.com

Tuesday, July 8, 2014

Difference between session.update() , session.merge() and session.saveOrUpdate() method of hibernate API.


What is the difference between session.update(Object obj), session.merge(Object obj) and session.saveOrUpdate(Object obj) method of hibernate API?

session.update(), session.merge() and session.saveOrUpdate() all three methods are used to update the records in database using hibernate persistence logic.


List of differences :

session.update(Object obj) method will update the record if the record is found in database, if record is not found in database it will throw an unchecked exception.it will not return anything as part of method call because its return type is void.

session.merge(Object obj) method will update the record if the record is found in database, if record is not found in database it will add that particular record in table, also it returns a persistent object of java pojo class whose object is going to insert in table. 

session.saveOrUpdate() method will update the record if the record is found in database, if record is not found in database it will add that particular record in table, but does not returns any thing as result of method call because its return type is void.

Prototype of session.update(Object object) method

public void update(Object object)throws HibernateException

Prototype of session.saveOrUpdate(Object object) method


public void saveOrUpdate(Object object)throws HibernateException

Prototype of session.merge(Object object) method


public Object merge(Object object)throws HibernateException

Example using session.update(Object obj) method:

import org.hibernate.*;
import org.hibernate.cfg.*;         
public class TestClient 
{
          public static void main(String[] args) 
          {
                   Configuration cfg= new Configuration();
                   cfg=cfg.configure("Hibernate.cfg.xml");
                   SessionFactory factory=cfg.buildSessionFactory();
                   Session ses=factory.openSession();
                   Transaction tx=ses.beginTransaction();
                   EmpBean eb2=new EmpBean();
                   eb2.setNo(125);
                   eb2.setFname("die");
                   eb2.setLname("hard");
                   eb2.setMail("diehardtechy@gmail.com"); 
                   ses.update(eb2); 

/* If record 125 is found in table then it will update the record , otherwise it will throw an exception. */

                   tx.commit();
                   ses.close();
                   factory.close();

          }
}

If record not found in database


Example using session.saveOrUpdate(Object obj) method:


import org.hibernate.*;
import org.hibernate.cfg.*;         
public class TestClient 
{
          public static void main(String[] args) 
          {
                   Configuration cfg= new Configuration();
                   cfg=cfg.configure("Hibernate.cfg.xml");
                   SessionFactory factory=cfg.buildSessionFactory();
                   Session ses=factory.openSession();
                   Transaction tx=ses.beginTransaction();
                   EmpBean eb2=new EmpBean();
                   eb2.setNo(125);
                   eb2.setFname("die");
                   eb2.setLname("hard");
                   eb2.setMail("diehardtechy@gmail.com"); 
                   ses.saveOrUpdate(eb2); 

/* If record 125 is found in table then it will update the record , otherwise it will add the record in the table. */
                   tx.commit();
                   ses.close();
                   factory.close();

          }
}

Example using session.merge(Object obj) method:

import org.hibernate.*;
import org.hibernate.cfg.*;         
public class TestClient 
{
          public static void main(String[] args) 
          {
                   Configuration cfg= new Configuration();
                   cfg=cfg.configure("Hibernate.cfg.xml");
                   SessionFactory factory=cfg.buildSessionFactory();
                   Session ses=factory.openSession();
                   Transaction tx=ses.beginTransaction();
                   EmpBean eb2=new EmpBean();
                   eb2.setNo(125);
                   eb2.setFname("die");
                   eb2.setLname("hard");
                   eb2.setMail("diehardtechy@gmail.com"); 
                   EmpBean ee=(EmpBean)ses.merge(eb2); 

/* If record 125 is found then it will update the record in db, otherwise it will add that record in database, it doesn't throw any exception if the record in not found. Also it returns the persistence pojo class object whose record is going to be inserted in DB.*/

                   System.out.println(ee);
                   tx.commit();
                   ses.close();
                   factory.close();

          }
}

All the above example java program are based upon the assumption that you have EmpBean.java as pojo class. If you don't have the EmpBean.java class or you are new to hibernate you can first read our article on How to start with Hibernate.