Monday, 11 June 2018

Inheritance

Inheritance in Java


In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object  or class, retaining the same implementation. In most class-based object-oriented languages, an object created through inheritance (a "child object") acquires all the properties and behaviors of the parent object. Inheritance allows programmers to create classes that are built upon existing classes, to specify a new implementation while maintaining the same behaviors (realizing an interface), to reuse code and to independently extend original software via public classes and interfaces. The relationships of objects or classes through inheritance give rise to a directed graph.
An inherited class is called a subclass of its parent class or super class.

Types

  •     Single inheritance



where subclasses inherit the features of one superclass. A class acquires the properties of another class.


Example

      Base Class:-

      package hello;

      public class Parent {
  public void insert(String name, int age) {
   System.out.println("Name of Person :
                         "+name+"\n"+"Age : "+age);
  }
  public void add(int a, int b) {
int c = a+b;
System.out.println(c);
}

      }

      Derived Class:-


      package hello;

      public class Child extends Parent{
Child() {
}

public static void main(String[] args) {
Child c = new Child();
c.insert("Kapil", 25);
c.add(10, 12);

}

      }


      


  • Multilevel inheritance

where a subclass is inherited from another subclass. It is not uncommon that a class is derived from another derived class as shown in the figure "Multilevel inheritance".


Example

Super Base Class:-

      package hello;

   public class GrandParent {
public void country() {
System.out.println("Indian");
}

   }

  

 Base Class:-

      package hello;

    public class Parent extends GrandParent{
public void insert(String name, int age) {
super.country();
System.out.println("Name of Person :     "+name+"\n"+"Age : "+age);
}
}


 Derived Class:-

      package hello;

      public class Child extends Parent{
Child() {
}

public static void main(String[] args) {
Child c = new Child();
c.insert("Kapil", 25);

}

      }


Method Overriding

Many object-oriented programming languages permit a class or object to replace the implementation of an aspect—typically a behavior—that it has inherited. This process is usually called overriding.

Note:-
  1. method must have same name as in the parent class
  2. method must have same parameter as in the parent class.
  3. must be IS-A relationship (inheritance).


Example

      Base Class:-

      public class Engine{ 
           public void run(){
                      System.out.println("Engine is running");
                   }  
     }  

      Derived Class:-    

  public class Bike extends Engine{ 
     public static void main(String args[]){  
       Bike obj = new Bike(); 
       obj.run();  
     } 
  }

Friday, 8 June 2018

User input in Java

Scanner in Java

There are various ways to read input from the keyboard, the java.util.Scanner class is one of them.
The Java Scanner class breaks the input into tokens using a delimiter that is whitespace bydefault. It provides many methods to read and parse various primitive values.

Java Scanner class is widely used to parse text for string and primitive types using regular expression.

Java Scanner class extends Object class and implements Iterator and Closeable interfaces.


Decision Making

Decision Making in Java


Decision Making statements are piece of code which evaluates the program along with the statements to be executed and observes that the condition is true or false. if the condition is true the it executes the statement and vice-versa.

Types of Decision Making statements : 



  1. if statement :- An if statement consists of a boolean expression followed by one or more statements.
  2. if...else statement :- An if statement can be followed by an optional else statement, which executes when the boolean expression is false.
  3. if...else if statement :- You can use one if or else if statement inside another if or else ifstatement.
  4. switch statement :- switch statement allows a variable to be tested for equality against a list of values.

Example if


public class Example_if {

public static void main(String[] args) {
int a = 10;
int b = 9;
if(a>b) {
System.out.println("A is Greater than B");
}

}

}

Example if...else


public class Example_if {

public static void main(String[] args) {
int a = 21;
int b = 22;
if(a>b) {
System.out.println("A is Greater than B");
}else{
System.out.println("B is Greater Number");
}

       }
}

Example if...else if


public class Example_if {

public static void main(String[] args) {
int a = 9;
int b = 22;
if(a>b) {
System.out.println("A is Greater than B");
}else if(b>a){
System.out.println("B is Greater Number");
}else {
System.out.println("Exceptional case");
}

}

}

Example switch


public class Days {

public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.print("Enter Value : ");
int day = input.nextInt();
switch(day) {
case 1:
System.out.println("Day is Monday");
break;
case 2:
System.out.println("Day is Tuesday");
break;
case 3:
System.out.println("Day is Wednesday");
break;
case 4:
System.out.println("Day is Thursday");
break;
case 5:
System.out.println("Day is Friday");
break;
case 6:
System.out.println("Day is Saturday");
break;
case 7:
System.out.println("Day is Sunday");
break;
default: System.out.println("Only 7 days in                                            a week");
}

}

}

Loops in Java

Loops In Java

In Java, there may be requirement of the situation that you wants to execute a piece of code number of times, In that case loops may help you to handle the situation and run code multiple times.


Types of loop in java:-

  1. do...while loopLike a while statement, except that it tests the condition at the end of the loop body.

2. while loopRepeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. 


3. for loopExecute a sequence of statements multiple times and abbreviates the code that manages the loop variable.

  

Example do..while Loop:


public class Loops {


public static void main(String[] args) {

do {
System.out.println(a);
a++;
}while(a<10);

}

}


Example while Loop:



public class Loops {

public static void main(String[] args) {

int a = 10;
while(a>0) {
System.out.println(a);
a--;
}

}

}

Example for Loop:

public class Loops {

public static void main(String[] args) {

for(int a=10; a>0; a--) {
System.out.println(a);
}

}

}

Wednesday, 14 February 2018

Methods in Java


Methods

A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method’s name. Think of a method as a subprogram that acts on data and often returns a value. Each method has its own name.
Types of Java Methods :- There are 2 types of methods:
1. Standard Library Methods
2. User-defined Methods

1. Standard Library Methods

These are built in methods in java that are readily available for use. These standard libraries come along with the java class library(JCL) in a java archive(.jar) file with JVM and JRE.
  • Print() is a method of java.io.PrintStream. The print(“.....”) prints the string inside the quotation marks. Eg.

Program :-

Public class Numbers{
Public static void main(String[] aa){
System.out.print(“Hello java”);
}
}
When you run the program, the output will be:
Hello java


2. User-defined Methods

You can also define methods inside a class as per our wish, In this methods are defined as per the user’s choice.
  • Creation of User-defined Method :-

Before call a method(or use a method), we need to define it. Eg.

Public static void myMethod(){ //myMethod() is defined
System.out.println(“My function called”);
}


You can see 3 keywords public, static and void in the creation of methods, lets discuss about it :-

  • The public keyword makes myMethod() method public. Public members can be accessed from outside of the class.
  • The static keyword denotes that the method can be accessed without creating the object of the class.
  • The void keyword signifies that the method doesn’t return any value.

  • How to call a Java Method ?

Now you need to use a defined method in your class. For that you have to call the method.
myMethod(); //this statement calls the myMethod()


Program of Java Method

Class Main{
Public static void main(String aa[]){
System.out.println(“creation of method”);
myMethod(); // method call
System.out.println(“method was executed successfully!”);
}
Public static void myMethod(){ // method definition
System.out.println(“it is my method definition”);
}
}

When we run it, the output will be :-

Creation of method
Method was executed successfully!
It is my method definition

Note that, we call the method without creating object of the class. It was because myMethod() is static. Consider another example, in this our method is non-static and is inside another class.

Program :-

Class Main{
Public static void main(String aa[]){
Output obj=new Output();
System.out.println(“hello world”);
// calling myMethod() of Output class
Obj.myMethod();
}}
Class Output{
// public: this method can be called from outside the class
Public void myMethod(){
System.out.println(“my method called”);
}}


Types of Methods:-



  1. Parametrized methods:- These methods contain a parameter list/argument list which recives a value from the calling method. For eg.
Public int sum(int a, int b){
//body
}
Program:-
Import java.util.scanner;
Class callbyvalue
Public static void main(String aa[]){
Scanner in=new Scanner(System.in);
Int x,y;
System.out.println(“Enter 2 numbers:”);
X=in.nextInt();
Y=in.nextInt();
Callbyvalue ob=new callbyvalue();
Ob.sum(x,y);
System.out.println(“the sum is:”+ob.sum(x,y));
}
Public int sum(int a,int b){
Int s=a+b;
Return s;
}


  1. Non-Parametrized methods:- These methods do not have any parameter-list. The programmer can simply call the function without sending any values to the function.
Program:-
Class ABC
{
public static void main(String aa[]){
add();
display();
}
Public static void add(){
Int a=1,b=2,c;
c=a+b;
System.out.println(c);
}
public static void display(){
{System.out.println(“Hello Java”);
}}


Here’s an eg of parametrized and non-parametrized methods:-