Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Friday, August 15, 2014

Posted by Anmol Sharma
In the previous article, we discussed about two basic file handling functions in Java including searching for an existing created file in the system and creating a file using java’s inbuilt function.

In this article we will cover up the other two file handling operations which includes reading from a file and writing to a file using java’s own methods. In this program we create a file by specifying a file name, open it at the same time and add records to it as per custom format. After writing to the file, it is good practice to close it.

import java.io.*;
import java.lang.*;
import java.util.*;

public class FileHandlingTrial {

       private Formatter file;
      
              public void openFile (){ //creating & opening a file
                    
                     try{
                           file= new Formatter("New Text Document.txt"); //will be created in default workspace folder else specify a path
                     }
                    
                     catch(Exception e){
                           System.out.println("Illegal file operation");
                                 
                           }
                     }
                    
                     public void addRecords(){// writes to the created file
                           file.format("%s %s %s", "99", "MCA", "IP University");
                    
                     }
                    
                     public void closeFile(){ //good practice to close the file after use
                           file.close();
                     }
      
}


class FileHandlingTrial1 {
      
       public static void main(String[] args){
             
         FileHandlingTrial asp = new FileHandlingTrial();
        
         asp.openFile();
         asp.addRecords();
         asp.closeFile();
             
       }
}


In this last program of file handling we will read the content added by the user.
Here also we create three methods in which first opens the file, second reads the content of the file and third one finally closes the file after reading the contents.


import java.io.*;
import java.util.*;



public class FileHandlingTrial {

private Scanner file;

public void openFile(){ // to open the file
      
       try{
              file = new Scanner(new File("new.txt"));
             
             
       }
      
       catch(Exception e){
             
              System.out.println("File not found");
       }
}

public void readFile(){ // to read data from the file
      
       while(file.hasNext()){
              String a=file.next();
              String b=file.next();
              String c=file.next();
              String d=file.next();
             
              System.out.printf("%s %s %s %s\n", a, b, c, d);
             
}

}

public void closeFile(){
file.close();
}
}


class FileHandlingTrial1 {
      
       public static void main(String[] args){
             
         FileHandlingTrial asp = new FileHandlingTrial();
        
         asp.openFile();
         asp.readFile();
         asp.closeFile();
             
       }
}

Screenshot // click to open a higher resolution version





Tuesday, August 12, 2014

Posted by Anmol Sharma
Java provides File class in ‘java.io’ package for handling all basic and necessary file operations and methods used for file handling like reading the contents of a file, writing to a file, searching for a file, determining the path of the file stored on a disk, etc. File class contains number of methods for performing specific operations on a file, few of which are used in this article.

In this program, the user is checking for the existence of a particular file stored on system’s hard disk. File class of Java IO package has been used to provide access to methods like exists(), getName() which checks for the file and if found returns the message else gives user defined message.

import java.io.File; //file class for basic file operations

class FileHandlingTrial{
               
         public static void main(String[] args) {
                               
  File asp = new File("C:\\file\\info.txt"); // constructor takes the path of the file already existing on the system
                               
             if(asp.exists()) // built in method to test whether a specified file exists or not.
                                               
                        System.out.println(asp.getName() + "File Found"); // prints the message along with file name
                                               
                                        else
                        System.out.println("File Not Found");
                               
                }
}


In the previous program we checked for an already created file on the system. We can also create a file using the program with help of facilities provided by java.io package

import java.util.*;

class FileHandlingTrial{
               
                public static void main(String[] args) {
                               
                                final Formatter asp; //formatter print strings to file
                               
                                try{

                                      asp = new Formatter("c://file//trial.txt"); //provide path of file where it will be stored
                                               
                                                System.out.println("File Created");
                                }
                               
                                catch(Exception e){
                                               
                             System.out.println("Error"); // for possible mistyping of wrong or illegal folder location like specifying a drive which does not exist on system.
                                }
                                               
                }
}


In the next article which will be part 2 of file handling, reading from a file and writing to a file will be discussed. Thanks folks for reading. 

Screenshot // click to open a higher resolution version





Posted by Anmol Sharma
Exception handling in java is similar as in C#. There are couple of differences like java allows checked exceptions which are handled by the caller of the program. Another minor difference is in the finally statement which can have return and break statement which is not the case in C#.

Refer to previous article for Introduction to Exception handling Exception Handling Basics in C#

Following code illustrates the basic concept of exception handling dealing with divide by zero exception in Java. As we know exception is any abnormal condition in a program which abrupt the normal flow of the program. Exception handling allows users to take corrective measures and have easy to understand information returned to them in case an exception arises.


import java.util.*;

public class ExceptionTrial {
               
                public static void main(String[] args){
                Scanner input = new Scanner(System.in); //allows the user to input values
               
                int x=1;
               
                do{
               
                try{ //put the code in try block which may raise an exception
                               
               
                System.out.println("Enter a number  :");
                int n1=input.nextInt();
                System.out.println("Enter another number to divide");
                int n2=input.nextInt();
                int sum = n1/n2;
               
                System.out.println(sum);
                x=2;
                }
               
                catch(Exception e){   //handles the exception, lets the user know whats wrong.
                               
                                System.out.println("You can not divide a number by zero");
                               
                }
                }while(x==1); // loop to let user enter correct value after encountering exception
               
               
                }
            
}

Screenshot // click to open a higher resolution version


Monday, July 28, 2014

Posted by Anmol Sharma
An exception is any uncommon condition arising during execution of a program. There might be several conditions when an exception is encountered in a program but at most basic level examples of exceptions include file not found exception, dividing a number by 0, inputting a wrong data type values etc

It is necessary to handle exceptions otherwise an end user will not feel at home with the application and it is a sign of poor problem understanding. Just for example, if there is a program which accepts a string “thinkdigital” and converts it to uppercase “THINKDIGITAL” and vice a versa then there must be a facility which handles an event when a user enters a non-string input which cannot be understood by the program. This is just an example to make any layman understand about the logic of exception

In .net framework, we have System.Exception class which provides all possible exception handling facility in c#.

Any piece of code which can trigger an exception goes under the ‘try’ block, once an exception occurs, the control moves to the ‘catch’ block and handles the exception. A try block can have number of catch block depending upon different types of exceptions occurring during an operation. But always the base catch block executes first and if required child catch blocks are executed.  There is a ‘finally’ block which is optionally used for performing maintenance tasks like freeing memory, closing file stream connections etc.


// Illustration code

using System;
using System.IO; //required for file operations


class ExceptionExampleProgram
{
    public static void Main()
    {
        StreamReader streamReader = null;
        try //code which may trigger an exception comes under the try block
        {
            streamReader = new StreamReader("C:\\file\\info.txt"); //reads the content of the file specified
            Console.WriteLine(streamReader.ReadToEnd());
            streamReader.Close();

        }
        catch (FileNotFoundException Trial) // handles the exception using predefined properties in exception class or user defined message
        {

            //Console.WriteLine(FileNotFound.Message); // printing message using system defined 'Message' property
            Console.WriteLine("This program can not find the file specified {0}, Please check again", Trial.FileName); // printing user defined message to make things more clear
         
        }
        finally // to perform clean up tasks like closing connections and release memory for efficiency
        {
            if (streamReader !=null) // required as if stream reader is null then it cant be closed
            {
            streamReader.Close();
            }
            Console.WriteLine("Stream reader now closed, so is this article :P");
            Console.ReadLine();
        }
    }
}

Screenshots // click to open a higher resolution version

/* Normal Execution */

/* File Not Found Exception Handling */

/* Another type of exception which can occur if directory path is altered, 
another catch block is required for this */

Sunday, July 27, 2014

Posted by Anmol Sharma
While garbage collection is automated in java, still it provides system.gc() method which force run the garbage collector and perform clean-up tasks. And at the same time, it is never recommended to run the garbage collector explicitly which causes the system to be inefficient and even the JVM will ignore the explicit method in most cases.

 There are various reasons not to use explicit gc but it is not the matter of discussion. The point of discussion is that many times it is asked in what circumstances or applications System.gc() should be used. Why it all exist then? First of all at beginners level like us we should hardly bother about using System.gc() at all. Let the automatic garbage collection do the job. But for a general idea it is interesting to note that there are some applications and circumstances where explicit garbage collections proves to be quite useful. And that’s why this method is not deprecated from java.

- In applications when user actually wants to know how much memory is lying unused by expired instances, in other words to find about memory leaks called as profiling.

- In android applications while creating bitmaps to prevent out of memory errors.

- Some task managers where user clicks a button and kills the task.

- Before performing benchmarking tests of an application.

- During development, debugging and testing phases of an applications

- When you want to prove yourself as a bad computer science student :P

I just cannot come across any other reason why one should even bother about manual resource collector when we have automatic memory management which is quite efficient.

Just in case you didn’t understand the above text then I am sure you will understand about this with the help of following piece of witticism  I just wrote while thinking all about this ;P

/* Me during a hypothetical (kalpanik) job interview in an IT company... */

Interviewer – Can we perform explicit garbage collection using system.gc() in java? Explain in most simple words taking real life example…?

Me – Yes, we can perform explicit garbage collection using system.gc() in java but mostly it will be totally ignored by JVM. There is no guarantee if JVM will even bother about the presence of the system.gc() method.
Taking a real life example, It’s actually like proposing a girl or asking her out for a cup of coffee but there is no guarantee that she will accept your request or not. It will be totally ignored mostly. So let the garbage collector run on its own  explicit garbage collection matlab ek tarfa pyaar  …err Dil ki baat thodi technical hogai ://

Interviewer with tears in eyes – Bhai Single lagtey ho  …Kitni salary loge?

PS - Do not imitate this in real life interview, you just might be blacklisted forever from that company ;P :--D

In the next article I will try to explain the overall garbage collection process in java and if possible try to compare with method in other languages.

So that’s all folks, thanks for reading.

Friday, July 18, 2014

Posted by Anmol Sharma
While both of them acts as base types, there are quite significant differences between abstract classes and interfaces in C#. Few noteworthy points are as follows –

-        -   Abstract classes can have access modifiers whereas interfaces doesn’t have access modifiers

-          - Abstract class can inherit either from another abstract class or another interface while an interface can         inherit only from an interface.

-         -  A class can inherit more than one interface, while a class cannot inherit multiple classes at the same time.

-         -  While interfaces can’t have implementation of any members, abstract classes can have.


   Illustration code
using System;

    public abstract class JIMS
    {
        int RollNo;
        public void print() //abstract class can have implemetations
        {
            Console.WriteLine("This is a print method");
        }
    }

 public interface iJIMS
    {
        /* public void print() // interfaces can not have implementations nor access specifier and it will give an error.
        {                      
            Console.WriteLine("This is a print method");
        }*/
     //int RollNo; // interfaces can not have fields while abstract classes can have 
     void Print();

    }


 public class Program
 {
     public static void Main()
     {
         Console.WriteLine("46geekslab - Difference between abstract classes and Interfaces in c#");
         Console.ReadLine();
     }
 }