Tuesday, 21 August 2018

Nesting of Methods



Only an object of that class using a dot operator can call a member function of a class. A member function can be called by using its name inside another member function of the same class. This is known as nesting of member functions.
Example Program:
class nest
{
            int m,n;
            void accept(int x,int y)
            {
                        m=x;
                        n=y;
            }
            int largest()
            {
                        if(m>=n)
                                    return m;
                        else
                                    return n;
            }
            void display()
            {
                        int large=largest();        //calling a method
                        System.out.println("Largest Value="+large);
            }
}
class nesting
{
            public static void main(String []args)
            {
                        nest n=new nest();
                        n.accept(6,7);
                        n.display();
            }
}
Output:
D:\ \programs>javac nesting.java
D:\ \programs>java nesting
Largest Value=7          

Static Members


Static Members
Static members are like global variables which are sharable across all the objects of the class and will maintain their values between objects.
Features:
  • They should be declared with the help of keyword “static”.
  • They are accessible across the entire class objects.
  • They are generally used to persist the value between objects calling.
  • If they are declared as public they can be accessible with the help of classname instead of object name.
//Program on Static Members
class staticdemo
{
            int objno;        
            static int objcnt;          
            void hitcount( )
            {
                        objno=++objcnt;
            }
            void showhits()
            {
                        System.out.println("This page has been hit for "+objcnt);
            }
            void showposition()
            {
                        System.out.println("Client " + objno+  "/" +objcnt);
            }
}
class Implstatic
{
            public static void main(String []args)
            {
                        staticdemo s=new staticdemo();
                        staticdemo t=new staticdemo();
                        staticdemo v=new staticdemo();
                        s.hitcount();
                        t.hitcount();
                        v.hitcount();
                        v.showhits();
                        s.showposition();
                        t.showposition();
                        v.showposition();
            }
}
Output:
D:\sysvol>javac Implstatic.java
D:\sysvol>java Implstatic
This page has been hit for 3
Client1/3
Client2/3
Client3/3

Static Methods:
Similar to static members, within the class concept we can have static methods, which are capable of accessing only static members, and can be called with the help of class name.


Methods Overloading
Overloading is the concept of using the same name for multiple purposes by sharing the same external definition. The appropriate definition gets called depending upon the arguments and written type of the method. Using the concept of method overloading, we can design a family of functions with one method name but with different argument lists. The method would perform different operations depends on the argument list in the method call.
Program:
class test
{
            int area(int i)
            {
                        return i*i;
            }
            int area(int a,int b)
            {
                        return a*b;
            }
}
class area
{
            public static void main(String []args)
            {
                        test t=new test();
                        int area;
                        area=t.area(5);
                        System.out.println("Area of Sqaure is:"+area);
                        area=t.area(5,6);
                        System.out.println("Area of Sqaure is:"+area);
            }
}
Output:
D:\sysvol>javac area.java
D:\sysvol>java area
Area of Sqaure is:25
Area of Sqaure is:30


Constructors

A Constructor is a special member function, which is used to initialize the objects of its class. The Constructor is invoked whenever an object of its associated class is created. The constructor constructs the value of data members of the class.

Features :
  • They are invoked automatically when the objects are created.
  • They do not have return type not even void.
  • The compiler calls constructor implicitly as soon as an object of its type is created.
  • Constructors can be overloaded.
  • The constructor name is same as class name.
Syntax:

                        Class class_name

                        {
                                    data members;
                                    class_name();
                        };
                        classname::classname()
                        {
                                    ----------------
                                    ----------------
                        }
Example:
                        Class sample
                        {
                                    sample();
                        };
                        sample::sampe()
                        {
                                    cout<<”constructor Demo”;
                        }
Program:
class complex
{
int real,img;
complex(){ }
complex(int a)
{
real=img=a;
}
complex(int x,int y)  //parameterized constructor
{
real=x;
img=y;
}
complex sum(complex c1,complex c2)
{
complex c3=new complex();
c3.real=c1.real+c2.real;
c3.img=c1.img+c2.img;
return c3;
}
void display()
{
System.out.println(real+"+i"+img);
}
}
class complexnum
{
public static void main(String args[])
{
complex c1=new complex(1,2);
complex c2=new complex(2);
complex c3=new complex();
c3=c3.sum(c1,c2);
c3.display();
}
}
Output:
C:\>javac complexnum.java
C:\>java complexnum
3+i4

Class/Objects and Methods


 Defining a Class and Object:
Class: class is a user defined data type that represents an entity, which is a collection of members and methods.
The entire set of data and code of an object can be made the user define data type with help of a class. Infact objects are variables of type class. Once a class has been defined, we can create any number of objects belonging to that class.
Syntax:            class class_name
                        {
                                    variable declarations/data members;
                                    function declarations/member functions;
}
The class body contains the declarations of variables and functions, which are called as class members. The variables declare inside the class are known as data members and functions are known as member functions.

Creating Objects

Object: is a functionable element that is used to access the members and methods of a class. Simply, object is an instance of class.
The declaration of an object is similar to that of a variable of any basic type.
Syntax: classname obj_name=new classname();
Example: student s=new student();
where s is an object of class student.

Accessing class members

Once an object of a class has been created there must be a provision to access its members. This is done by using the member access operator (.) called as dot.
Syntax:
            Object_name.datamember=value;
            Object_name.memberfunction(actual_args);

Example:
            s.a=10;
            s.display();

Example program:
class student   //userdefined class
{         
int sno=10;       //members/fields declaration   
void show()     //method declaration   
{                     
System.out.println("Hai");       
}
}
class simple    
{
            public static void main(String []args)
            {
                        student s=new student(); //object created
                        System.out.println("Sno="+s.sno);  //accessing members of class
                        s.show();          //calling method
            }
}
Output:C:\>javac simple.java

C:\>java simple

Sno=10

Hai


Decision Making and Branching, Decision Making and Looping and Jumps in Loops


Decision Making and Branching

Decision Making with If statement
The general form of simple statement is
                        if(test expression)
{
Statement-block;
}
Statement –x;

            The statement block may be a single statement or a group of statements. If the test expression is true, the statement-block will executed; otherwise the statement-block will be skipped and the execution will jump to the statement-x
Example:
class gross
{
            public static void main(String []args)
            {
                        float gross_sal,net_sal=0.0f;
                        gross_sal=Float.valueOf(args[0]).floatValue();
                        if(gross_sal<10000.0f)
                                    net_sal=gross_sal;
                        if(gross_sal>=10000.0f)
                                    net_sal=gross_sal-0.15f*gross_sal;
                        System.out.println("Net Salary is Rs " + net_sal);
            }
}
Output:
D:\ >javac gross.java
D:\ >java gross 4.5
Net Salary is Rs 4.5
D:\ >java gross 12876.7
Net Salary is Rs 10945.195

If else Statement
the if-else statement is an extension of the simple if statement. The general form is..
            if(test expression)
                        {
                                    True-block statement(s)
                        }
            Else
                        {
                                    False-block statement(s)
}
Statement-x;
If the test expression is true then the true-block statement(s) immediately following the if statement are executed; otherwise the false-block statement(s) are executed. In either case, either true-block or false-block will be executed, not both.

The following is the example of

class evenodd
{
            public static void main(String []args)
            {
                        int num=Integer.parseInt(args[0]);
                        if(num%2==0)
                                    System.out.println(num + " is even");
                        else
                                    System.out.println(num + " is odd");   
            }
}
Output:
D:\ \programs>javac evenodd.java
D:\ \programs>java evenodd 6
6 is even
D:\ \programs>java evenodd 5
5 is odd

Nesting If Else Statement
When a series of decisions are involved, we may have to use more than one if..else statement in nested form as follows:
IF (logical-expression) 
{
   IF (logical-expression) {
      Statements  }
   ELSE
      {   statements  }
   statements
ELSE
   statements
   IF (logical-expression) {
      statements
   }
   statements
}
Program:
class nestedif
{
            public static void main(String []args)
            {
                        int a=325,b=712,c=478;
                        System.out.print("Largest value is:");
                        if(a>b)
                        {
                                    if(a>c)
                                    {
                                                System.out.print(a);
                                    }
                                    else
                                    {
                                                System.out.print(c);
                                    }
                        }
                        else
                        {
                                    if(c>b)
                                    {
                                                System.out.print(c);
                                    }
                                    else
                                    {
                                                System.out.print(b);
                                    }
                        }
            }
}
Output:
D:\ \programs>javac nestedif.java
D:\ \programs>java nestedif
Largest value is: 712

ElseIf Ladder
The conditions are evaluated from the top. As soon as the true condition is found, the statement associated with it is executed and the control is transferred to the statement-x. When all the n conditions become false, then the final else containing the default-statement will be executed.
The general form is:
if(condition1)
            Statement-1;
else if(condition 2)
            Statement –2;
else if(condition 3)
            Statement –3;
----------------------
else if(condition n)
            statement –n;
else
            default statement;
statement-x;
Program:
class elsif
{
            public static void main(String []args)
            {
                        int per=Integer.parseInt(args[0]);
                        char grade;
                        if(per>=90)
                                    grade='A';
                        else if(per>=75)
                                    grade='B';
                        else if(per>=60)
                                    grade='C';
                        else if(per>=50)
                                    grade='D';
                        else
                                    grade='F';
                        System.out.println("Grade=" +grade);
            }
}
Output:
D:\ \programs>javac elsif.java
D:\ \programs>java elsif 67
Grade=C

The switch Statement
The switch statement tests the value of a given variable (or expression) against a list of case values and when a match is found a block of statements associated with that case is executed. The general form of the switch statement is as shown below:

                                    switch(expression)
                                    {
                                                case value 1:
                                                                                    block1;
                                                                                    break;
                                                case value2:
                                                                                    block2;
                                                                                    break;
                                                ………………
                                                ………………
                                                default:
                                                                                    default-block;
                                                                                    break;
                                    }
Example:
class color
{
public static void main(String args[])
{
String ch=args[0];
char choice=ch.charAt(0);
System.out.println("Press B for Blue  ");
System.out.println("Press G for Green ");
System.out.println("Press R for Red   ");

switch(choice)
{
case 'B':
case 'b':            System.out.println("You choose Blue color");
                        break;
case 'G':
case 'g':            System.out.println("You choose Green color");
                        break; 
case 'r':
case 'R':           System.out.println("You choose Red color");
                        break;

default:            System.out.println("invalid choice");
}
}
}

The ?: operator.
The value of a variable often depends on whether a particular Boolean expression is or is not true and on nothing else. For instance one common operation is setting the value of a variable to the maximum of two quantities  Is
 (a > b) ? a : b; is an expression which returns one of two values, a or b. The condition, (a > b), is tested. If it is true the first value, a, is returned. If it is false, the second value, b, is returned. Whichever value is returned is dependent on the conditional test, a > b. The condition can be any expression, which returns a boolean value.
Example:
class conditional
{
public static void main(String args[])
{
int a,b;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
int max;
max=(a>b)? a : b;
System.out.println("max="+max);
}
}

Decision Making and Looping
The while statement
The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false.
Syntax:   While(expression){
               Statements; }
Using the while statement to print the values from 1 through 10 can be accomplished as in the following WhileDemo program:
class WhileDemo {
     public static void main(String[ ] args){
          int count = 1;
          while (count < 11) {
               System.out.println("Count is: " + count);
               count++;
          }
     }
}

The do-while statement
The Java programming language also provides a do-while statement, which can be expressed as follows:
Syntax:           do {
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileDemo program:
class DoWhileDemo {
     public static void main(String[] args){
          int count = 1;
          do {
               System.out.println("Count is: " + count);
               count++;
          } while (count <= 11);
     }
}

The for statement

The for statement provides a compact way to iterate over a range of values.
The general form of the for statement can be expressed as follows:
for (initialization; termination; increment) {
    statement(s)
}
When using this version of the for statement, keep in mind that:
  • The initialization expression initializes the loop; it's executed once, as the loop begins.
  • When the termination expression evaluates to false, the loop terminates.
  • The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
The following program, For Demo, uses the general form of the for statement to print the numbers 1 through 10 to standard output:
class ForDemo 
{
     public static void main(String[] args){
          for(int i=1; i<11; i++){
               System.out.println("Count is: " + i);
          }
     }
}

Jumps in Loops
Java supports three types of jumping statements:
  • Break
  • Continue
  • Return

Break:
Some times we need to exit from a loop before the completion of the loop then we use break statement and exit from the loop and loop is terminated.
Continue:
Sometimes we do not need to execute some statements under the loop then we use the continue statement that stops the normal flow of the control and control returns to the loop without executing the statements written after the continue statement.
Diff between break and continue:
There is the difference between break and continue statement that the break statement exit control from the loop but continue statement keeps continuity in loop without executing the statement written after the continue statement according to the conditions.
Examples for break and continue
class star
{
public static void main(String args[])
{
loop1: for(int i=1;i<=100;i++)
{
System.out.println();
if(i>10) break;
for(int j=1;j<=100;j++)
{
System.out.print("*");
if(i==j)continue loop1;
}
}
}
}

Return Statement:
It is used to explicitly return from the current method. The flow of control transfers back to the caller of the method. To return a value, simply put the value after the return keyword.