Thursday, March 16, 2017

Exception Handling Using Try Catch Java

Tags
The statements which can throw exception are placed in try block and after the exception is thrown the catch block following the try block are executed and the program is not abnormally terminated.

Code::

import java.util.*;
public class Exception 
{

    
    public static void main(String[] nt) 
    {
        Scanner in =new Scanner(System.in);
        System.out.print("Enter any Number:");
        try
        {
        int a=in.nextInt();
        int b=12345/a;
        System.out.println("Result is :"+b);
        }
        catch(ArithmeticException e)
        {
            System.out.println("Exception: " +e);
        }
        
    }

}

Output::

UnCaught Exception

Tags
Exception is a run time error which is caused due to Programmer error,Input error and others abnormal condition which leads to termination of the program.

UnCaught Exception is that which is handled by java run time system by default handler and leads to abnormal termination of program.

Code::

import java.util.*;
public class Exception 
{

    
    public static void main(String[] nt) 
    {
        Scanner in =new Scanner(System.in);
        System.out.print("Enter any Number:");
        int a=in.nextInt();
        int b=12345/a;
        System.out.println("Result is :"+b);
    }
    
}

Output::

Friday, March 10, 2017

Classes and Objects Python

Tags
Following are Some Examples to illustrate the concept:

Code::
1.

class rectangle:
    def __init__(self,w,h):
        self.w=w
        self.h=h
   
    def area(self):
        self.area=self.w*self.h
        return self.area
   
    def perimeter(self):
        self.perimeter=2*(self.w+self.h)
        return self.perimeter
   
    def issquare(self):
        if(self.w is self.h):
            return True
        else:
            return False
   
    def getw(self):
        return self.w
   
    def geth(self):
        return self.h
   
r=rectangle(5,5)
print("Width:",r.getw(),"Height:",r.geth())
print("Area is:",r.area())
print("Perimeter is:",r.perimeter())
print("IsSquare:",r.issquare())

Output::
2.

class complex:
    def __init__ (self,a,b):
        self.r=a
        self.i=b
   
    def add(self,sec):
        r=complex(0,0)
        r.r=self.r+sec.r
        r.i=self.i+sec.i
        return r
       
    def sub(self,sec):
        r=complex(0,0)
        r.r=self.r-sec.r
        r.i=self.i-sec.i
        return r
   
    def mul(self,sec):
        r=complex(0,0)
        r.r=self.r*sec.r
        r.i=self.i*sec.i
        return r
   
    def div(self,sec):
        r=complex(0,0)
        r.r=self.r/sec.r
        r.i=self.i/sec.i
        return r
   
    def __str__ (self):
        return(str(self.r)+"+"+str(self.i)+"i")
   
c1=complex(2,3)
c2=complex(3,1)
print("Addition is:",c1.add(c2))
print("Subtraction is:",c1.sub(c2))
print("Multiplication is:",c1.mul(c2))

print("Division is:",c1.div(c2))

Output::

Thursday, March 9, 2017

Inheritance Python

Tags
Inheritance is the process of reusing the existing code .
Define new classes from the old one i.e including all features of old classes.

Following Program will illustrate the concept:

Code::


class bankaccount:
    def __init__ (self):
        self.bal=int(input("Enter Initial Balance:"))
   
    def withdraw(self,amt):
        if amt<self.bal:
            self.bal=self.bal-amt
        else:
            raise ValueError ("Insufficient Funds")
   
    def deposit(self,amt):
        self.bal=self.bal+amt
   
    def transfer(self,amt,toacc):
        try:
            self.withdraw(amt)
            toacc.deposit(amt)
        except ValueError as e:
            print("Try Again",e)
    def __str__(self):
        return"Balance is: "+str(self.bal)

class cheque(bankaccount):
    def __init__ (self):
        bankaccount.__init__(self)
        self.cheq={}
    def process(self,amt,number,org):
        try:
            self.withdraw(amt)
        except ValueError as e:
            print("Cheque Returned for",e)
        self.cheq[number]=(org,amt)
    def cheqinfo(self,number):
        if self.cheq.get(number):
            print(self.cheq[number])
        else:
            print("No Such Cheque")
    def withdraw(self,amt):
        print('Withdrawing')
        bankaccount.withdraw(self, amt)

nt=bankaccount()        #object of bankaccount type created
nt.deposit(1500)
print(nt)
nt.withdraw(1500)
print(nt)
nti=bankaccount()          #new object created
nt.transfer(1500, nti)
print(nt,nti)

dn=cheque()
dn.process(1500, 1001, 'nearur')

dn.cheqinfo(1001)

Output::

Wednesday, March 8, 2017

Final Keyword

Tags
Final Keyword is used to make any value immutable(not changable),avoid inheritance,or avoid method overriding.

Final To Avoid Method Overriding:

Code::
class Sample
{
  final void show()
    {
        System.out.println("Hello NT");
    }
}
class Test extends Sample
{
    /*void show()
    {
        Sytsem.out.println("Hello NTI");
    }*/          //Compile Time Error
}
public class FinalKeyword 
{

    public static void main(String[] nt) 
    {
      Test t=new Test();
      t.show();
    }
    

}
Output::


Final To avoid Inheritance :

Code::
final class Sample
{
     void show()
    {
        System.out.println("Hello NT");
    }
}
/*class Test extends Sample
{
  
}*/ //compile time error
public class FinalKeyword 
{

    public static void main(String[] nt) 
    {
      
    }
    
}

Abstract Class

Tags
Abstract Class is used to make some methods compulsory for subclasses to redefine them according to the subclass.
Thus it provide basic about the functions which an object has to perform .

Syntax:    abstract type name(parameter list);

If a method is abstract then the class must be declared abstract. All the subclasses have to define that method.

Following will illustrate the concept:

Code::

abstract class Base
{
    abstract void show();
}
class Derived extends Base
{
    void show()
    {
        System.out.println("Derived Show");
    }
}
public class AbstractUse 
{
    public static void main(String [] nt)
    {
       // Base b=new Base();  Compile time error
        Derived d=new Derived();
        d.show();
        Base n;     //abstract class reference can be created
        n=d;
        n.show();
    }
}

Output:: 

Dynamic Method Dispatch

Tags
Dynamic Method Dispatch is an important feature of java in which the call to a overridden method is resolved at runtime i.e:runtime polymorphism.

In this case the Superclass reference object is assigned the subclass objects hence according to the object referenced the version of overridden method is called.

Following example will illustrate the concept:

Code::

import java.util.*;
class Figure
{
    double a,b;
    Figure(double c,double d)
    {
        a=c;
        b=d;
    }
    void area()
    {
        System.out.println("Area: 0");
    }
}
class Rectangle extends Figure
{
    Rectangle(double c,double d)
    {
        super(c,d);
    }
    void area()
    {
        System.out.println("Area of Rectangle:"+a*b+" square meters");
    }
}
class Triangle extends Figure
{
    Triangle(double c,double d)
    {
        super(c,d);
    }
    void area()
    {
        System.out.println("Area of Triangle:"+0.5*a*b+" square meters");
    }
}
class Circle extends Figure
{
    Circle(double c)
    {
        super(c,c);
    }
    void area()
    {
        System.out.println("Area of Circle:"+3.142*a*a+" square meters");
    }
}
class Square extends Figure
{
    Square(double c)
    {
        super(c,c);
    }
    void area()
    {
        System.out.println("Area of Square: "+a*b+" square meters");
    }
}
public class Area 
{
       public static void main(String[] nt)
       {
           Rectangle r=new Rectangle(5,4);
           Circle c=new Circle(10);
           Square s=new Square(5);
           Triangle t=new Triangle(4,5);
           Figure f;
           f=r;
           f.area();         //rectangle area
           f=c;
           f.area();          // circle area
           f=s;
           f.area();         //square area
           f=t;
           f.area();        //triangle area
       }
}

Output::

Tuesday, March 7, 2017

Electrical Resistance of Wire

Tags
The electrical resistance R of a cylindrical wire with length l (in meter) and diameter d (in meter) can be computed from the area A of its diameter (m2) and the  resistivity Ρ of the material (rho, meter times Ohm). The formula:

R=P*(l/A)

Code::

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author mrdishant
 */
import java.util.*;
public class Resistance {
    public static void main(String[] nt)
    {
        Scanner in=new Scanner(System.in);
        System.out.print("Enter Length of wire:");
        double length=in.nextDouble();
        System.out.print("Enter Diameter of Wire:");
        double d=in.nextDouble();
        System.out.print("Enter Resistivity of wire:");
        double p=in.nextDouble();
        double r=p*(4*length/3.142*d*d);
        System.out.println("Resistance of Wire:"+r);
 
    }
    
}

Output::

Metropolis City or Not

Tags
Question::  We define a Metropolis to be a city, that is either a capital city with more than 100 000 citizens or more than 200 000 citizens and an average income of 720 000 000 per year.

Give a boolean expression with all three variables that is true if and only if the city is a metropolis.

Code::

import java.util.*;
public class NT 
{
    public static void main(String [] nt)
    {
        boolean iscapital=false;
        long nofcitizens;
        double taxpercitizen;
        Scanner in=new Scanner(System.in);
        System.out.print("Press Y if City is a Capital Else anything:");
        char a=in.next().charAt(0);
        if(a=='y'||a=='Y')
        {
            iscapital=true;
        }
        System.out.print("Enter Number of Citizens:");
        nofcitizens=in.nextLong();
        System.out.print("Enter Tax Per Citizen:");
        taxpercitizen=in.nextDouble();
        if(iscapital  && nofcitizens>=100000||nofcitizens>=200000&&taxpercitizen*12*nofcitizens>720000000)
        {
            System.out.println("Yes This city is a Metropolis");
        }
        else
        {
            System.out.println(" This city is not a Metropolis");
        }
    }
    

}

Output:: 

Sunday, March 5, 2017

Method Overloading In Inheritance Java

Tags
If there is a method in subclass having same name as that of method in superclass but these have some difference in number and type of arguments then Method Overloading Takes place.

Code::
class d
{
    void show()
    {
        System.out.println("D's method");
    }
}
class e extends d
{
    void show(int x)
    {
        System.out.println("E's method");
    }
}
public class MethodOverriding {

    public static void main(String[] nt)
    {
        e ob=new e();
        ob.show();
        ob.show(67);
    }

}
Output:

Method Overriding In Java

Tags
When Superclass and subclass have method having same signature and name then a call to that method using subclass object will lead to invoking subclass version of that method. This is called method overriding.

Following Code will illustrate the concept:

Code::

class d
{
    void show()
    {
        System.out.println("D's method");
    }
}
class e extends d
{
    void show()
    {
        System.out.println("E's method");
    }
}
class f extends e
{
    void show()
    {
        System.out.println("F's method");
    }
}
public class MethodOverriding {

    public static void main(String[] nt)
    {
        f ob=new f();
        ob.show();
    }

}

Output::
As the above example shows that only subclass version is called.

Order of Execution of Constructors Java

Tags
Constructors follow the order of derivation in case of Inheritance
i.e- Superclass to Subclass
firstly superclass constructor is called then subclass constructor is called.
also in case of Multilevel inheritance.

Following code will illustrate the concept:

Code::

class a
{
    a()
    {
        System.out.println("A's Constructor");
    }
}
class b extends a
{
    b()
    {
        System.out.println("B's Constructor");
    }
}
class c extends b
{
    c()
    {
        System.out.println("C's Constructor");
    }
}
public class Constructors
{

    public static void main(String[] nt)
    {
        c ob=new c();
    }

}

Output::


super.member in JAVA

Tags
Keyword Super is also used to use the members of superclass which are same as the members of subclass.In this case if we use that member it refers to the member of subclass.

Syntax::   super.member;
here member can be data member or method

Following code will illustrate the concept:

Code::

import java.util.*;
class Base
{
    Scanner in=new Scanner(System.in);
    int a,b;
    Base()
    {
        System.out.print("Enter Value of a:");
        a=in.nextInt();
        System.out.print("Enter Value of b:");
        b=in.nextInt();
       
    }
    void display()
    {
        System.out.println("A= "+a+" \nB= "+b);
    }
}
class Derived extends Base
{
    Scanner in=new Scanner(System.in);
    int c;
    Derived()
    {
        System.out.print("Enter Value of c:");
        c=in.nextInt();
    }
    void display()
    {   super.display();
        System.out.println("C= "+c);    
    }
}
public class Inheritance
{

    public static void main(String[] nt)
    {
        Derived ob2=new Derived();
        System.out.println("Values are:");
        ob2.display();
    }
}

Output::

Saturday, March 4, 2017

Super() in Java

Tags
Keyword Super is used to refer to the immediate Superclass in case of Inheritance from the Subclass.It is used to call the constructor in case of constructor overloading because without this default constructor is called.

It is used in two forms:

1.Super is used to call the constructor of the Superclass in Subclass Constructor.

Syntax:: super(parameter  list)

Code::

import java.util.*;
class Base
{
    Scanner in=new Scanner(System.in);
    int a,b;
    Base()
    {
        System.out.print("Enter Value of a:");
        a=in.nextInt();
        System.out.print("Enter Value of b:");
        b=in.nextInt();
       
    }
    void show()
    {
        System.out.println(a+b);
    }
}
class Derived extends Base
{
    Scanner in=new Scanner(System.in);
    int c;
    Derived()
    {
        super();
        System.out.print("Enter Value of c:");
        c=in.nextInt();
    }
    void display()
    {
        System.out.println(a+b+c);     // a,b are the members of superclass
    }
}
public class Inheritance
{

    public static void main(String[] nt)
    {
        Derived ob2=new Derived();
        System.out.print("Sum is:");
        ob2.display();
    }
}

Output::

Reference To Subclass Object (Object Slicing)

Tags
A Superclass reference variable can refer to a Subclass Object .By doing this the superclass reference variable can access only those members of subclass object which are inherited (those are members of superclass).

Following Code will illustrate the concept:

Code::

class Super
{
    int a,b;
    void show()
    {
        System.out.println(a+b);
    }
}
class Sub extends Super
{
    int c;
    void display()
    {
        System.out.println(a+b+c);     // a,b are the members of superclass
    }
}
public class Inheritance
{

    public static void main(String[] nt)
    {
        Super ob;
        Sub ob2=new Sub();
        ob2.a=50;
        ob2.b=10;
        ob2.c=10;
        ob=ob2;         //superclass reference  variable is assigned a subclass object
        ob.show();
        ob2.display();
    }
}
Output::

Converse is not True i.e a Subclass variable cannot refer to a Superclass object.
Reason behind this can be that Subclass has some members which are not in Superclass so here error occurs.

Multilevel Inheritance Java

Tags
In Multilevel Inheritance the Subclass of one superclass is acting as a Superclass for another subclass. Hence the members of both superclass are present in the subclass.

Following code will illustrate the concept:

Code::
import java.util.*;
class A
{
    int a;
}
class B extends A
{
    int b;
}
class C extends B
{
    int c;
    void show()
    {
        System.out.println(a+b+c);                //a,b are members of superclass
    }
}
public class Multilevel
{

    public static void main(String[] nt)
    {   C ob=new C();
        Scanner in =new Scanner(System.in);
        System.out.print("Enter First Number:");
        ob.a=in.nextInt();
        System.out.print("Enter Second Number:");
        ob.b=in.nextInt();
        System.out.print("Enter Third Number:");
        ob.c=in.nextInt();
        System.out.print("Sum is: ");
        ob.show();
    }
   
}

Output::
Java Does not Support Multiple Inheritance Because in Multiple Inheritance if Two Classes have same members then its an ambiguity for Subclass to use which member.  So There is no Multiple Inheritance in Java. But we can achieve this with the help of Interfaces.

Single Inheritance Java

Tags
Inheritance is  a feature of reusing the code.Without starting from scratch we can create a new class(Child,Subclass) having all features of old(Parent,Superclass) in addition to its own features.

Syntax:  class Subclass name extends Superclass name
{

//body of sub class

}

Following Code will illustrate the concept:

Code::

class Super
{
    int a,b;
    void show()
    {
        System.out.println(a+b);
    }
}
class Sub extends Super
{
    int c;
    void display()
    {
        System.out.println(a+b+c);     // a,b are the members of superclass
    }
}
public class Inheritance
{

    public static void main(String[] nt)
    {
        Super ob=new Super();
        Sub ob2=new Sub();
        ob.a=50;
        ob.b=20;
        ob2.a=50;
        ob2.b=20;
        ob2.c=10;
        ob.show();
        ob2.display();
    }
}

Output::
Above example also illustrate the fact that we can use a superclass itself.