Monday, 17 June 2013

Exception Handling

http://howtodoinjava.com/wp-content/uploads/ExceptionHierarchyJava.png
Exception Handling

Exception handling:

In programming languages,some time our program compile successfullybut failed to execute program, such type of error interrupt program and runtime environment of language automatically throw appropriate exception. In such a case rest of the programdoesnot execute. If we want to execute rest of the program it gives an error message,then they hav to handle exception which is thrown by runtime environmen of the language, and the technique used to handle runtime error is called exception handling.

There are two types of exception classes:
1 Built in exception classes.
2 User defined exception classes.

There are 5 reserved keyword which help to handle runtime error:
1 try
2 catch
3 throw
4 throws
5 finally

1 try :  It is used where chances of runtime error are there. Runtime environment automatically detect type of error and throw object of appropriate exception class.
        Syntax:        
           try
        {
       The code that may generate an exception is placed in this block.
         }

2 catch : A exception which is thrown by try block must be brought either in catch block or finally block.

        Syntax:            
         catch(Exception_name objectname)
     {
              Statements/ error to display to user when exception occour.
}


3 throw: When ever a exception occour throw block throws the exception to the catch block. Each exception that occour must be caught, the type of exception generated is catched by the catch block of that particluar exception, catch block is declared below the try block.

           Syntax:    
                   try
              {
              The code that may generate an exception is placed in this block.
                }
                  catch(Exception_name objectname)
             {
                  Statements/ error to display to user when exception occour.
                }  

4 throws: throws keyword gives a method flexibility of throwing an Exception rather than handling it. with throws keyword in method


5 finally : execute in every situation even the exception occour or not.finally create a block of code that will be executed afetr a try catch block completed and before the code following try catch block. If an exception is thrown finally block will execute eve if no catch satement matches exception.

Friday, 14 June 2013

regionMatches()

regionMatches method matches two strings, it matches the characters of second string with the characters of the first string from the point defined in the syntax. The string comparison start from the




Description of regionMatches() method:

str1. regionMatches ( 4 , str2 , 4 , 7 )

str1 :name of the string with which to compare the second strnig

regionMAtches::: keyword

4 : it is the starting index of first index, from where to start matching the region of str1 with the region of str2..

str2: name of the second string whose region we have to match with first string str1

4: is the startring index of second string, matching of second string with first string str1 will start from this starting index number that is 4

7 : is the number of characters from starting index number of second string,, the starting index of str2 is 4, then the the region will be compared upto 10 more characters.

true: is for case senstivity..


Program for regionMatches()    : 


import java.io.*;
public class RegionM
{
public static void main(String args[])
{
String str1=new String("Gurpreet Singh");
String str2=new String("Manpreet Singh");
String str3=new String("Gurinder singh");
System.out.println("comparing str1 and str2"+str1.regionMatches(4,str2,4,7));
System.out.println("comparing str2 and str3"+str2.regionMatches(true,3,str3,3,7));
}
}


Output:




Searching String - lastIndexOf()

To search for the last occurence of a specific character  in the string , lastIndexOf() function is used.This function returns an integer type value ,it returns the last occurrence of the specified character in the string.The charcter should be written in single quote
Syntax:    Stringname.lastIndexOf('ChararacterToBeSearched');

The same function can be used to search for a particular string in a complete string.The string is always written in double quotes.This function will return he last occurence of the string in the complete string.If the string 
Syntax :   Stringname.lastIndexOf("StringToBeSearched");

If you want to search for a character after a particular number of characters, then the start index is also given along with the character, when the program is compiled by Java complier , compiler donot search for the specified character upto that index number specified by you.
Syntax:  Stringname.lastIndexOf('ChararacterToBeSearched',StartIndex);

In the same way if you want to search a string or a word in the string to be searched then the start index is given along with the string to be searched. Compler during compiling donot search forthe string upto that index numbered entered.
Syntax::   Stringname.lastIndexOf("StringToBeSearched",StartIndex);

Program for lastIndexOf()


class Last
{
public static void main(String arg[]) 
{
String s= "this is the duty of every citizen of india to serve his country at the cost of anything";
System.out.println(s);

System.out.println(s.indexOf('o'));
System.out.println(s.lastIndexOf('o'));

System.out.println(s.indexOf("the"));
System.out.println(s.lastIndexOf("the"));

System.out.println(s.indexOf("o",10));
System.out.println(s.lastIndexOf('o',60));

System.out.println(s.indexOf("the",10));
System.out.println(s.lastIndexOf("the",60));

}
}

Output of the above code is :


Thursday, 13 June 2013

Searching strings- indexof() method

The string class provide two methods that allow to search a string for a specific character or substring...

indexof();

lastIndexOf();



To search for a specific character  in the string , indexOf() function is used.This function returns an integer type value ,it returns the first occurrence of the specified character in the string.The charcter should be written in single quote
Syntax:    Stringname.indexOf('ChararacterToBeSearched');

The same function can be used to search for a particular string in a complete string.The string is always written in double quotes.
Syntax :   Stringname.indexOf("StringToBeSearched");

If you want to search for a character after a particular number of characters, then the start index is also given along with the character, when the program is compiled by Java complier , compiler donot search for the specified character upto that index number specified by you.
Syntax:  Stringname.indexOf('ChararacterToBeSearched',StartIndex);

In the same way if you want to search a string or a word in the string to be searched then the start index is given along with the string to be searched. Compler during compiling donot search forthe string upto that index numbered entered.
Syntax::   Stringname.indexOf("StringToBeSearched",StartIndex);

Program to demonstrate the use of indexOf() unction

import java.io.*;
import java.util.*;
class Searchstr
{

public static void main(String arg[])
{
String s= "this is the duty of every citizen of india to serve his country at any cost";
System.out.println(s);

System.out.print("\n\nIndex of(o) = ");
System.out.println(s.indexOf('o'));

System.out.print("Index of(the) = ");
System.out.println(s.indexOf("the"));

System.out.print("Index of('o',10) = ");
System.out.println( s.indexOf('o',10));

System.out.print("Index of(the,10) = ");
System.out.println( s.indexOf("the",10));

}
}

Below is the output of above code:



Wednesday, 12 June 2013

String Compare function

String compare function is used to sort a string by name. The string entered by user is scanned word by word. This function arrange the string in alphabetic order.
If the second word appear earlier to first word, then this function generates a negative value i.e. less than Zero.
If the second word appear after the first word, then this function generates a positive value i.e. greater than Zero.
If the second word is same to the first word, then this function generates Zero.

Program for string compare function:


class Strcomp
{
public static void main(String arg[])
{
String arr[]={"this","is","the","duty","of","every","citizen","to","serve","his","country"};
String t;
int i,j;
for(i=0;i<arr.length;i++)
{
for(j=i+1;j<arr.length;j++)
{
if(ar[j].compareTo(arr[i])<0)
{
t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
}
for(i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
}

Following is the output of the above code:



Tuesday, 11 June 2013

OOP Principles

1. Encapsulation:

Encapsulation is the mechanism that binds together code and the data it manipulates ,and keeps both safe from outside interface and misuse..
the Data members and the member functions that are binded together in a block act as a fixed block and no data member or member function outside the class can access the members of class unless it has the rights to access them..
class Encap
{
void sum()
{
int a,b,c;
a=10;
b=20;
c=a+b;
System.out.print("Sum is"+c);
}
}
Only the objects of this class can access these functions and data members.


2. Inheritance:

Inheritance means one class inherits the features of some other class. The member functions are not again written in to the derived class but the member functions of base class are directly copied into the derived class. The objects of derived class can access the member functions of base class.
Base class is also known as parent class and the derived class is also known as child class.
Following are two main types of inheritance.


3. Polymorphism

Polymorphism allows one interface to be used for a general class of actions. Polymorphism in simple means"ability to take more than one form" , means you can use different functions with same name to perform different task, the functions may need to have different number of arguments, on the basis of number of arguments passed it is decided that which same of same name is to be executed.

Monday, 10 June 2013

Drawbacks of Java

Following are some of the main drawbacks of Java:

a) Slow performance: The speed of execution is not too much fast. The designers of java are trying to increase its speed and are also trying to make its JIT(Just In Time )complier more efficient and fast.
 
b) No support for low-level programming: One more drawback of Java is that it cannot be used for writing  Low Level Programming Language as it is designed to develop code for the different platform. The java compiler takes the source code as input from the user. Compiles that code and generate an intermediate code which is platform independent.

c) Poor features in GUI: Java supports GUI controls but with very less features. For example, an image cannot be placed on a button. The is overcome with the introduction of javax.swing package.

d) No control over garbage collection: Garbage collection is one of the built-in features of Java and is entirely managed by JVM. programmer is not given any handles to control the garbage collection to make coding simple. For this reason, Java does not come with delete(), free(), malloc() and sizeof() etc. functions.
 

Thursday, 6 June 2013

Multilevel Inheritance

Multilevel inheritance is the form of inheritance in which there is a base class and the derived class. The derived class is itself the base class .Derived class itself acts as the base class of some other derived class.


Following is the code of a multilevel inheritance.The code below has four classes Fclass ,Sclass, Tclass,Mlevel. Fclass is the base class for Sclass, Sclass is the derived lass for Fclass and acts as the base class for Tclass, Tclass is the derived class of Sclass.
Mlevel class creates object of the Tclass and using objects functions f1,f2 and f3 are called.

Program for Multilevel Inheritance

class Fclass
{
void f1()
{
System.out.println("First Class");
}
}

class Sclass extends Fclass
{
void f2()
{
System.out.println("Second Class");
}
}

class Tclass extends Sclass
{
void f3()
{
System.out.println("Class three");
}
}

class Mlevel
{
public static void main(String arg[])
{
Tclass obj=new Tclass();
obj.f1();
obj.f2();
obj.f3();
}
}

Following is the output of the above code for better understanding:


Single level Inhertance

In single level inheritance there is one base class and one child class that inherits the  features of the base class. The child class inherits the child class using the keyword"extends".
Syntax for single level inheritance is:
   class Child_class_name extends Base_class_name

Program for Single Level Inheritance

class My        //Base class
{
void input()
{
System.out.println("Class My");
}
}

class You extends My                       // class You inherits My class
{
void output()
{
System.out.print("Class You");
}
}

class Slevel
{
public static void main(String arg[])
{
You obj=new You();
obj.input();
obj.output();
}
}

Wednesday, 5 June 2013

Casting - Implicit Casting

class Implicit
{
public static void main(String arg[])
{
int x=10;
double y=x;
System.out.print(y);
}
}

Tuesday, 4 June 2013

A simple Hello world Program



When we write a java program .. it is saved with the file name  ClassName.java(Make sure the extension is .java. the Classname.java file is compiled using the java compliler..
If the file complies successfully then a class file of the same name (Classname.class) will be generated.then the generated class file is executed .

SO lets start with the official "Hello world program"

Hello World Program

class HelloWorld    //Declare name of the main class, first lettershould becapital
{
public static void main(String arg[]])
{
System.out.println("Hello world");                     //Prints output on the screen
System.out.print("Welcome to Codsters, Clear your concepts and logics");
}
}


Java Introduction

Java is one of the most popular and most widely used programming language used in million of devices all around the globe. Java is widely used because of its features that it provides to the programmer can make applications and others software that provides easy and attractive user interface.

Java is an object oriented programming language that works on the basis of classes and objects. It follows bottom up approach during the execution of the program.

Following are some of the features of Java:

  • Inheritance : It is the process of creating the new classes and using the behavior of the existing classes by extending them to use the existing code and adding the additional features in the child class if needed along with the features of base class.Base classis the classfrom which the child class inherits or extends the features.

  • Encapsulation: : It is the mechanism of combining the information and providing the abstraction.

  • Polymorphism: :   It is the ability to take multiple forms, Polymorphism is the way of providing the different oprations to the functions having the same name but performing different tasks.

  • Dynamic binding :   It is the way of providing the maximum functionality to a program about the specific type at runtime.

  •  
    full details in json
    Proudly Powered by Blogger.
    back to top