CAO-UNIT-4

1. Basic Memory Concepts:

- A memory unit is the collection of storage units or devices together.

- The memory unit stores the binary information in the form of bits.

- Memory/ Storage is classified into 2 categories:

                    i) Volatile Memory

                    ii) Non Volatile Memory

i) Volatile Memory:

- This loses its data, when power is switched off.

ii) Non-Volatile Memory:

- This is a permanent storage and does not lose any data when power is switched off.


Memory Access Methods:

i) Random Access:

- Main memories are random access memories, in which each memory location has a unique address.

- Using this unique address any memory location can be reached in the same amount of time in any order.

ii) Sequential Access:

- This method allows memory access in a sequence or in order.

iii) Direct Access:

- In this mode, information is stored in tracks, with each track having a separate read/write head.

 

Connection of the memory to the Processor:

- Connection of the memory to the Processor is depicted as,


- Data transfer between the memory and the processor takes place through the use of two processor registers

- MAR (Memory Address Register)

- MDR (Memory Data Register)

- If MAR is k bits long and MDR is n bits long, then the memory unit may contain upto 2k addressable locations.

- During a memory cycle, n bits of data are transferred between the memory and the processor

- This transfer takes place over the processor bus, which has k address lines and n data lines

- The bus also includes the control lines Read/ Write (R/W) and Memory Function Completed (MFC) for coordinating data transfers

- Other control lines may be added to indicate the number of bytes to be transferred

 

 

Memory Hierarchy:

- The Memory Hierarchy is depicted as,


- The comparisons in the Memory Hierarchy is depicted as,




2. Main Memory:

- The memory unit that communicates directly within the CPU, Auxiliary memory and Cache memory, is called main memory.

- It is the central storage unit of the computer system.

- It is a large and fast memory used to store data during computer operations.

- Main memory is made up of RAM and ROM

i) RAM: Random Access Memory:

DRAM:

- Dynamic RAM, is made of capacitors and transistors

- It is slower and cheaper than SRAM.

- Dynamic RAMs are the pre-dominant choice for implementing computer main memories.

- The high densities achievable in these chips make large memories economically feasible.

SRAM:
- Static RAM, has a six transistor circuit in each cell and retains data, until powered off.

- The choice of a RAM chip for a given application depends on several factors such as, cost, speed, power dissipation, and size of the chip.

- Static RAMs are generally used only when very fast operation is the primary requirement.

- Their cost and size are adversely affected by the complexity of the circuit that realizes the basic cell.

- They are used mostly in cache memories.

 

ii) ROM: Read Only Memory:

- It is non-volatile and is more like a permanent storage for information.

- It also stores the bootstrap loader program, to load and start the operating system when computer is turned on. 

The various types of ROM are

- PROM

- EPROM

- EEPROM

- FLASH MEMORY

 

ROM:

- A ROM cell is depicted as,



- A logic value 0 is stored in the cell if the transistor is connected to ground at point P, otherwise a 1 is stored.

- The bit line is connected through a resistor to the power supply

-To read the state of the cell, the word line is activated

- Thus the transistor switch is closed and the voltage on the bit line drops to near zero if there is a connection between the transistor and ground.

- If there is no connection to ground, the bit line remains at the high voltage, indicating a 1.

- A sense circuit at the end of the bit line generates the proper output value.

- Data are written into a ROM when it is manufactured.

 

PROM:

- It stands for Programmable Read Only Memory.

- It was first developed in 70s by Texas Instruments.

- It is made as a blank memory.

- A PROM programmer or PROM burner is required in order to write data onto a PROM chip.

- The data stored in it cannot be modified and therefore it is also known as one time programmable device.

 

 

EPROM:

- It stands for Erasable Programmable ROM.

- It is different from PROM as unlike PROM the program can be written on it more than once.

- This comes as the solution to the problem faced by PROM.

- The bits of memory come back to 1, when ultra violet rays of some specific wavelength falls into its chip’s glass panel.

- The fuses are reconstituted and thus new things can be written on the memory.

 

EEPROM:

- It stands for Electrically Erasable Read Only Memory.

These are also erasable like EPROM, but the same work of erasing is performed with electric current. Thus, it provides the ease of erasing it even if the memory is positioned in the computer.

It stores computer system’s BIOS. Unlike EPROM, the entire chip does not have to be erased for changing some portion of it.

- Thus, it even gets rid of some biggest challenges faced by using EPROMs.

 

FLASH ROM:

It is an updated version of EEPROM.

In EEPROM, it is not possible to alter many memory locations at the same time.

However, Flash memory provides this advantage over the EEPROM by enabling this feature of altering many locations simultaneously.

It was invented by Toshiba and got its name from it capability of deleting a block of data in a flash. 

Flash Cards:

- One way of constructing a larger module is to mount flash chips on a small card.

- Such flash cards have a standard interface that makes them usable in a variety of products.

- A card is simply plugged into a conveniently accessible slot.

- Flash cards come in a variety of memory sizes.

- Typical sizes are 8, 32, and 64 Mbytes.

Flash Drives:

- Larger flash memory modules have been developed to replace hard disk drives.

- These flash drives are designed to fully emulate the hard disks, to the point that they can be fitted into standard disk drive bays.

- However, the storage capacity of the flash drives is significantly lower.

- Currently, the capacity of flash drives is less than one Giga Byte.

 

3. Memory System Considerations:

- The choice of a RAM chip for a given application depends on several factors such as, cost, speed, power dissipation, and size of the chip.

Memory controller:

- The address is divided into two parts.

- The high-order address bits, which select a row in the cell array, are provided first and latched into the memory chip under control of the RAS signal.

- Then the lower-order address bits, which select a column, are provided on the same address pins and latched using the CAS signal.

- A typical procedure issues all bits of an address at the same time.

- The required multiplexing of address bits is usually performed by a Memory Controller Circuit, which is interposed between the processor and the dynamic memory

- Use of a Memory Controller is depicted as,



- The controller accepts a complete address and the R/W signal from the processor, under control of a request signal which indicates that a memory access operation is needed.

- The controller then forwards the row and column portions of the address to the memory and generates the RAS and CAS signals.

- Thus, the controller provides the RAS-CAS timing, in addition to its address multiplexing function.

- It also sends the R/W and CS signals to the memory.

- The CS signal is usually active low.

- Data lines are connected directly between the processor and the memory.

- Note that the clock signal is needed in SDRAM chips.

 

4. Cache Memory:

- The cache is a small and very fast memory, interposed between the processor and the main memory.

- Its purpose is to make the main memory appear to the processor to be much faster than it actually is.

- The effectiveness of this approach is based on a property of computer programs called locality of reference.

- Consider the arrangement, the use of a cache memory is depicted as



- When the processor issues a Read request, the contents of a block of memory words containing the location specified are transferred into the cache.

- Subsequently, when the program references any of the locations in this block, the desired contents are read directly from the cache.

- Usually, the cache memory can store a reasonable number of blocks at any given time, but this number is small compared to the total number of blocks in the main memory.

- The correspondence between the main memory blocks and those in the cache is specified by a mapping function.

Hit Ratio:

- The performance of cache memory is measured in terms of a quantity called hit ratio.

- When the CPU refers to memory and finds the word in cache it is said to produce a hit.

- If the word is not found in cache, it is in main memory then it counts as a miss.

- The ratio of the number of hits to the total CPU references to memory is called hit ratio.

Hit Ratio = Hit / (Hit + Miss)

 

*) Mapping Functions:

- There are several possible methods for determining where memory blocks are placed in the cache.

- Consider a cache consisting of 128 blocks of 16 words each, for a total of 2048 (2K) words, and assume that the main memory is addressable by a 16-bit address.

- The main memory has64K words, which we will view as 4K blocks of 16 words each.

 

i) Direct Mapping:

- The simplest way to determine cache locations in which to store memory blocks is the direct-mapping technique.

- In this technique, block j of the main memory maps onto block j modulo 128 of the cache, is depicted as,




- Thus, whenever one of the main memory blocks 0, 128, 256,  . . . is loaded into the cache, it is stored in cache block0.

- Blocks 1, 129, 257,  . . . are stored in cache block 1, and so on.

- The memory address can be divided into three fields

- The low-order 4 bits select one of 16 words in a block.

- When a new block enters the cache, the 7-bit cache block field determines the cache position in which this block must be stored.

- The high-order 5 bits of the memory address of the block are stored in 5 tag bits associated with its location in the cache.

- The tag bits identify which of the 32 main memory blocks mapped into this cache position is currently resident in the cache.

- As execution proceeds, the 7-bit cache block field of each address generated by the processor points to a particular block location in the cache.

- The high-order 5 bits of the address are compared with the tag bits associated with that cache location. If they match, then the desired word is in that block of the cache.

- If there is no match, then the block containing the required word must first be read from the main memory and loaded into the cache.

 

ii) Associative Mapping:

- The most flexible mapping method, in which a main memory block can be placed into any cache block position.



- In this case, 12 tag bits are required to identify a memory block when it is resident in the cache.

- The tag bits of an address received from the processor are compared to the tag bits of each block of the cache to see if the desired block is present.

- This is called the associative-mapping technique.

- It gives complete freedom in choosing the cache location in which to place the memory block, resulting in a more efficient use of the space in the cache.

- When a new block is brought into the cache, it replaces (ejects) an existing block only if the cache is full.

- The complexity of an associative cache is higher than that of a direct-mapped cache, because of the need to search all 128 tag patterns to determine whether a given block is in the cache.

- To avoid a long delay, the tags must be searched in parallel.

- A search of this kind is called an associative search.

 

iii) Set-Associative Mapping:

- Another approach is to use a combination of the direct- and associative-mapping techniques.

- The blocks of the cache are grouped into sets, and the mapping allows a block of the main memory to reside in any block of a specific set.

- Hence, the contention problem of the direct method is eased by having a few choices for block placement.

- At the same time, the hardware cost is reduced by decreasing the size of the associative search.

- An example of this set-associative-mapping technique is shown in Figure 8.18 for a cache with two blocks per set.

- In this case, memory blocks 0, 64, 128, . . . , 4032 map into cache set 0, and they can occupy either of the two block positions within this set.

- Having 64 sets means that the6-bit set field of the address determines which set of the cache might contain the desired block.

- The tag field of the address must then be associatively compared to the tags of the two blocks of the set to check if the desired block is present.

- This two-way associative search is simple to implement.

- The number of blocks per set is a parameter that can be selected to suit the requirements of a particular computer.

- For the main memory and cache sizes, four blocks per set can be accommodated by a 5-bit set field, eight blocks per set by a 4-bit set field, and so on.


- The extreme condition of 128 blocks per set requires no set bits and corresponds to the fully-associative technique, with 12 tag bits.

- The other extreme of one block per set is the direct-mapping method.

- A cache that has k blocks per set is referred to as a k-way set-associative cache.




















CAO UNIT-1

1. Computer Types:
- Computer is an electronic device which accepts data as input, processes that input data and produces the result data as output.
- Computer is a fast electronic calculating machine that accepts digitized input information, processes it according to a list of internally stored instructions and produces the resulting output information.
- The list of instructions is called a Computer Program.
- The internal storage is called Computer Memory.
- The different Computer Types are,
            i) Desktop or Personal Computers
            ii) Notepad Computers
            iii) WorkStations
            iv) Enterprise Systems
            v) Servers
            vi) Super Computers

i) Desktop or Personal Computers:
- Desktop Computers have processing and storage units, visual display and audio output units, and a keyboard that can all be located easily on a home or office desk.
- The storage media includes,
            - Hard Disks
            - CD-ROMs,…., etc
- The most common form of desktop computers is Personal Computers (PCs), which has found wide use in homes, schools and business offices.

ii) Notepad Computers:
- Notepad Computers are also called as Portable Notebook Computers or Laptops.
- These are the compact version of the personal computer with all of these components packaged into a single unit like the size of thin briefcase.

iii) Work Stations:
- Work Stations have more computational power than Personal Computers, used in Engineering applications, especially for interactive design work.

iv) Enterprise Systems:
- Enterprise Systems are also called as Mainframes.
- These are used for business data processing in medium to large corporations that require much more computing power and storage capacity than workstations can provide.

v) Servers:
- Servers contain sizable database storage units and are capable of handling large volumes of requests to access the data.

vi) Super Computers:
- Super Computers are used for the large-scale numerical calculations required in applications such as Weather Forecasting and Aircraft Design and Simulation.








MT.java

Aim:
To print multiplication table of a given number

Source code:
import java.lang.*;
import java.util.*;
class MT
 {
   public static void main(String args[])
     {
       int n,i;
       Scanner input=new Scanner(System.in);
       System.out.println("Enter a number");
       n=input.nextInt();
       System.out.println("Multiplication Table is");
       for(i=1;i<=10;i++)
         {
           System.out.println(n+"*"+i+"="+n*i);
          }
     }
 }
       
Output:
Enter a number
5
Multiplication Table is
5*1=5
5*2=10
5*3=15
5*4=20
5*5=25
5*6=30
5*7=35
5*8=40
5*9=45
5*10=50 






Armstrong.java

Aim:
To find armstrong number

Source code:
import java.lang.*;
import java.util.*;
class Armstrong
 {
   public static void main(String args[])      
     {
       int sum=0,n,digit,m;
       Scanner input=new Scanner(System.in);  
       System.out.println("Enter value for n");
       n=input.nextInt();
       m=n;
       while(n!=0)
         {
           digit=n%10;
           sum=sum+(digit*digit*digit);
           n=n/10;
         }       
       if(m==sum)
         System.out.println("Armstrong");
       else
         System.out.println("Not Armstrong");
      }
  }

Output-1:
Enter value for n
153
Armstrong

Output-2:
Enter value for n
134
Not Armstrong




Ascii256.java

Aim:
Program to print ASCII values

Source code:
//program to print ASCII values
import java.lang.*;
class Ascii256
 {
   public static void main(String args[])
     {
       int k;
       for(k=0;k<256;k++)
           System.out.print(k+"="+(char)k+" ");
     }
  }

Output:
0=  1= 2= 3= 4= 5= 6= 7= 8 9=      10=
 14= 15= 16= 17= 18= 19= 20= 21= 22= 23= 24= 25= 26= 27= 28= 29= 30= 31= 32=  33=! 34=" 35=# 36=$ 37=% 38=& 39=' 40=( 41=) 42=* 43=+ 44=, 45=- 46=. 47=/ 48=0 49=1 50=2 51=3 52=4 53=5 54=6 55=7 56=8 57=9 58=: 59=; 60=< 61== 62=> 63=? 64=@ 65=A 66=B 67=C 68=D 69=E 70=F 71=G 72=H 73=I 74=J 75=K 76=L 77=M 78=N 79=O 80=P 81=Q 82=R 83=S 84=T 85=U 86=V 87=W 88=X 89=Y 90=Z 91=[ 92=\ 93=] 94=^ 95=_ 96=` 97=a 98=b 99=c 100=d 101=e 102=f 103=g 104=h 105=i 106=j 107=k 108=l 109=m 110=n 111=o 112=p 113=q 114=r 115=s 116=t 117=u 118=v 119=w 120=x 121=y 122=z 123={ 124=| 125=} 126=~ 127= 128=? 129=? 130=? 131=? 132=? 133=? 134=? 135=? 136=? 137=? 138=? 139=? 140=? 141=? 142=? 143=? 144=? 145=? 146=? 147=? 148=? 149=? 150=? 151=? 152=? 153=? 154=? 155=? 156=? 157=? 158=? 159=? 160=  161=¡ 162=¢ 163=£ 164=? 165=¥ 166=? 167=? 168=? 169=? 170=ª 171=« 172=¬ 173=? 174=? 175=? 176=° 177=± 178=² 179=? 180=? 181=µ 182=? 183=· 184=? 185=? 186=º 187=» 188=¼ 189=½ 190=? 191=¿ 192=? 193=? 194=? 195=? 196=Ä 197=Ã… 198=Æ 199=Ç 200=? 201=É 202=? 203=? 204=? 205=? 206=? 207=? 208=? 209=Ñ 210=? 211=? 212=? 213=? 214=Ö 215=? 216=? 217=? 218=? 219=? 220=Ãœ 221=? 222=? 223=ß 224=à 225=á 226=â 227=? 228=ä 229=Ã¥ 230=æ 231=ç 232=è 233=é 234=ê 235=ë 236=ì 237=í 238=î 239=ï 240=? 241=ñ 242=ò 243=ó 244=ô 245=? 246=ö 247=÷ 248=? 249=ù 250=ú 251=û 252=ü 253=? 254=? 255=ÿ
QR.java

Aim:
To find Quotient and Remainder

Source code:
import java.lang.*;
import java.util.*;
class QR
 {
   public static void main(String args[])
     {
       double a,b,q;
       int r;
       Scanner input=new Scanner(System.in);
       System.out.println("Enter values for a,b");
       a=input.nextDouble();
       b=input.nextDouble();
       q=a/b;
       r=(int)a%(int)b;
       System.out.println("Quotient="+q);
       System.out.println("Remainder="+r);
     }
 }
    
Output:
Enter values for a,b
7
3
Quotient=2.3333333333333335
Remainder=1


TempConv.java

Aim:
To find Temperature Conversion (Fahrenheit to Celsius)

Source code:
import java.lang.*;
import java.util.*;
class TempConv
 {
  public static void main(String args[]) 
  {
    double f,c;
    Scanner input=new Scanner(System.in);
    System.out.println("Enter Fahrenheit value");
    f=input.nextDouble();
    c=((f- 32)*5)/9;
    System.out.println("Fahrenheit to Celsius value="+c);
   }
 }
    
Output:
Enter Fahrenheit value
100
Fahrenheit to Celsius value=37.77777777777778

 

OOPJAVA UNIT-2

1. Inheritance in Java:

- Inheritance is the way of producing new classes from already existing classes.

                        OR

- Inheritance is the process by which objects of one class acquire the properties of objects of another class

- Inheritance supports the concept of hierarchical classification.

- The newly created class is also called as sub class or child class or derived class.

- The old or existing class is also called as super class or parent class or base class.

Types of Inheritance:

- Inheritance is of 5 types

i) Single Inheritance

ii) Multi-level Inheritance

iii) Multiple Inheritance

iv) Hierarchical Inheritance

v) Hybrid Inheritance

- Java does not support Hybrid Inheritance.



i) Single Inheritance:

- Single Inheritance representing one super class and one sub class.

Example:

class A

 {

  int a=10;

  void display()

   {

    System.out.println("a="+a);

   }

 }

class B extends A

 {

 }

class Single

 {

  public static void main(String args[])

   {

    B obj=new B();

    obj.display();

   }

 }

Output:

a=10

 

ii) Multi-level Inheritance:

- Multi-level inheritance representing a sub class derived from a sub class derived from a super class.

Example:

class A

 {

  int a=10;

  void display1()

   {

    System.out.println("a="+a);

   }

 }

class B extends A

 {

  int b=20;

  void display2()

   {

    System.out.println("b="+b);

   }

 }

class C extends B

 {

 }

class Multilevel

 {

  public static void main(String args[])

   {

    C obj=new C();

    obj.display1();

    obj.display2();

   }

 }

Output:

a=10

b=20

 

 

iii) Multiple Inheritance:

- Multiple inheritance representing multiple super classes and one sub class.

- Java does not support multiple inheritance directly.

- Java provides an interface concept to support the concept of multiple inheritance.

Example:

interface Car

{

    int  speed=60;

    public void distanceTravelled();

}

interface Bus

{

    int distance=100;

    public void speed();

}

public class Vehicle  implements Car,Bus

{

    int DT;

    int ASP;

    public void distanceTravelled()

    {

        DT=speed*distance;

        System.out.println("Total Distance Travelled is : "+DT);

    }

    public void speed()

    {

        int ASP=DT/speed;

        System.out.println("Average Speed maintained is : "+ASP);

    }

    public static void main(String args[])

    {

        Vehicle v1=new Vehicle();

        v1.distanceTravelled();

        v1.speed();

    }

}

Output:

Total Distance Travelled is : 6000

Average Speed maintained is : 100

 

iv) Hierarchical Inheritance:

- Hierarchical inheritance representing one super class and multiple sub classes.

Example:

class A

 {

  int a=10;

  void display()

   {

    System.out.println("a="+a);

   }

 }

class B extends A

 {

 }

class C extends A

 {

 }

class D extends A

 {

 }

class Hierarchical

 {

  public static void main(String args[])

   {

    B b1=new B();

    C c1=new C();

    D d1=new D();

    b1.display();

    c1.display();

    d1.display();

   }

 }

Output:

a=10

a=10

a=10

 

2. SUPER CLASS AND SUB CLASS:

- The newly created class is also called as sub class or child class or derived class.

- The old or existing class is also called as super class or parent class or base class.

i) Super Keyword in Java:

- super is a keyword in java which refers to the immediate super class object

- super can be used to refer immediate parent class instance variable

- super can be used to invoke immediate parent class method

- super() can be used to invoke immediate parent class constructor

Example1:

class A

{

       A()

      {

          System.out.println("Super class");

       }

}

class  B extends A

 {

        B()

         {

             super();

             System.out.println("Current class");

         }

 }

 class SuperDemo

 {

      public static void main(String args[])

       {

            B obj = new B();

        }

 }

Output:

Super class

Current class

Example2:

class Person

  int id; 

  String name; 

  Person(int id,String name)

  { 

    this.id=id; 

    this.name=name; 

  } 

class Emp extends Person

  float salary; 

  Emp(int id,String name,float salary)

   { 

     super(id,name);//reusing parent constructor 

     this.salary=salary; 

   } 

  void display()

  {

    System.out.println(id+" "+name+" "+salary); 

  } 

}

class SuperDemo2

  public static void main(String[] args)

   { 

     Emp e1=new Emp(1,"RGV",30000f); 

     e1.display(); 

    }

}

Output:

1    RGV    30000.0

 

3. Method Overriding:

- If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java.

- In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding:

·       Method overriding is used to provide the specific implementation of a method which is already provided by its superclass.

·       Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

  • The method must have the same name as in the parent class
  • The method must have the same parameter as in the parent class.
  • There must be an IS-A relationship (inheritance).

Example:

class Parent

{

    void show() { System.out.println("Parent's show()"); }

}

class Child extends Parent

{

    void show() { System.out.println("Child's show()"); }

}

class Main

{

    public static void main(String[] args)

    {

        Parent obj1 = new Parent();

        obj1.show();

        Parent obj2 = new Child();

        obj2.show();

    }

}

Output:

Parent's show()

Child's show()

 

4. Object class in Java:

- The Object class is the parent class of all the classes in java by default.

- In other words, it is the topmost class of java.

- Object class is present in java.lang package.

- Every class in Java is directly or indirectly derived from the Object class.

- If a Class does not extend any other class then it is direct child class of Object and if extends other class then it is an indirectly derived.

- Therefore, the Object class methods are available to all Java classes.

- Hence Object class acts as a root of inheritance hierarchy in any Java Program.

Methods in Object class:

- The Object class provides many methods depicted in a table as,

Method

Description

public final Class getClass()

returns the Class class object of this object. The Class class can further be used to get the metadata of this class.

public int hashCode()

returns the hashcode number for this object.

public boolean equals(Object obj)

compares the given object to this object.

protected Object clone() throws CloneNotSupportedException

creates and returns the exact copy (clone) of this object.

public String toString()

returns the string representation of this object.

public final void notify()

wakes up single thread, waiting on this object's monitor.

public final void notifyAll()

wakes up all the threads, waiting on this object's monitor.

public final void wait(long timeout)throws InterruptedException

causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method).

public final void wait(long timeout,int nanos)throws InterruptedException

causes the current thread to wait for the specified milliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method).

public final void wait()throws InterruptedException

causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method).

protected void finalize()throws Throwable

is invoked by the garbage collector before object is being garbage collected.

 

5. Polymorphism in Java:

- Polymorphism is a concept by which we can perform a single action in different ways.

- Polymorphism is derived from 2 Greek words: poly and morphs.

- The word "poly" means many and "morphs" means forms. So polymorphism means many forms.

- There are two types of polymorphism in Java:

- compile-time polymorphism and runtime polymorphism.

- compile-time polymorphism supports overloading and runtime polymorphism supports overriding.

 

6. Dynamic binding:

- Connecting a method call to the method body is known as binding.

- There are two types of binding

i) Static Binding (also known as Early Binding).

ii) Dynamic Binding (also known as Late Binding).

- When type of the object is determined at compiled time(by the compiler), it is known as static binding.

- If there is any private, final or static method in a class, there is static binding.

- When type of the object is determined at run-time, it is known as dynamic binding.

Example (dynamic binding)

class Animal{  

void eat(){System.out.println("animal is eating...");}  

}  

 

class Dog extends Animal{  

void eat(){System.out.println("dog is eating...");}  

 

public static void main(String args[]){  

Animal a=new Dog();  

a.eat();  

}  

}  

Output:
dog is eating...

 

7. Casting Objects and the instanceof Operator:

- One object reference can be typecast into another object reference. This is called casting

object.

Example:

m(new Student());

- It assigns the object new Student() to a parameter of the Object type.

- This statement is equivalent to

Object o = new Student(); // Implicit casting

m(o);

- The statement Object o = new Student(), known as implicit casting, is legal because an

instance of Student is an instance of Object.

- Suppose you want to assign the object reference o to a variable of the Student type using

the following statement:

Student b = o;

- In this case a compile error would occur. Why does the statement Object o = new Student()

work but Student b = o doesn’t?

- The reason is that a Student object is always an instance of Object, but an Object is not necessarily an instance of Student.

- Even though you can see that o is really a Student object, the compiler is not clever enough to know it.

- To tell the compiler that o is a Student object, use explicit casting.

- The syntax is similar to the one used for casting among primitive data types.

- Enclose the target object type in parentheses and place it before the object to be cast, as follows:

Student b = (Student)o; // Explicit casting

- It is always possible to cast an instance of a subclass to a variable of a superclass (known as

upcasting), because an instance of a subclass is always an instance of its superclass.

- When casting an instance of a superclass to a variable of its subclass (known as downcasting),

- Explicit casting must be used to confirm your intention to the compiler with the (SubclassName)

cast notation.

The instanceof Operator:

- The instanceof is an object reference operator and returns true if the object on the left-hand side is an instance of the class given on the right hand side.

- This operator allows us to determine whether the object belongs to a particular class or not.

Example:

            person  instanceof  student

- It is true if the object person belongs to the class student, otherwise it is false.

 

8. Abstract class in java:

- An abstract class must be declared with an abstract keyword.

- It can have abstract and non-abstract methods.

- It cannot be instantiated.

- It can have constructors and static methods also.

- It can have final methods which will force the subclass not to change the body of the method.

- A method which is declared as abstract and does not have implementation is known as an abstract method.

Example:

abstract class shape

{

abstract double area();

}

class rectangle extends shape

{

double l=12.5,b=2.5;

double area()

{

return l*b;

}

}

class triangle extends shape

{

double b=4.2,h=6.5;

double area()

{

return 0.5*b*h;

}

}

class square extends shape

{

double s=6.5;

double area()

{

return 4*s;

}

}

class shapedemo

{

public static void main(String[] args)

{

rectangle r1=new rectangle();

triangle t1=new triangle();

square s1=new square();

System.out.println("The area of rectangle is: "+r1.area());

System.out.println("The area of triangle is: "+t1.area());

System.out.println("The area of square is: "+s1.area());

}

}

Output:

The area of rectangle is: 31.25

The area of triangle is: 13.65

The area of square is: 26.0

 

9. The final keyword:

- The final keyword in java is used to restrict the user.

- The java final keyword can be used in many context. Final can be:

a) final variable

b) final method

c) final class

- The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable.

- It can be initialized in the constructor only.

- The blank final variable can be static also which will be initialized in the static block only.

a) final variable:

- If you make any variable as final, you cannot change the value of final variable(It will be constant).

Example of final variable:

- There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because final variable once assigned a value can never be changed.

class Bike9

{  

 final int speedlimit=90;//final variable  

 void run()

{  

  speedlimit=400;  

 }  

 public static void main(String args[])

{  

 Bike9 obj=new  Bike9();  

 obj.run();  

 }  

}//end of class  

Output:
Compile Time Error

 

b) final method:

- If you make any method as final, you cannot override it.

Example of final method:

class Bike{  

  final void run(){System.out.println("running");}  

}  

     

class Honda extends Bike{  

   void run(){System.out.println("running safely with 100kmph");}  

     

   public static void main(String args[]){  

   Honda honda= new Honda();  

   honda.run();  

   }  

}  

Output:
Compile Time Error

 

c) final class:

- If you make any class as final, you cannot extend it.

Example of final class:

final class Bike{}  

  

class Honda1 extends Bike{  

  void run(){System.out.println("running safely with 100kmph");}  

    

  public static void main(String args[]){  

  Honda1 honda= new Honda1();  

  honda.run();  

  }  

}  

Output:
Compile Time Error
 
 

Is final method inherited?

- Yes, final method is inherited but you cannot override it. For Example:

class Bike{  

  final void run(){System.out.println("running...");}  

}  

class Honda2 extends Bike{  

   public static void main(String args[]){  

    new Honda2().run();  

   }  

}  

Output:

running...

 

10. Interfaces:

- An interface is a collection of abstract methods and final variables

- By default, the methods declared inside interface are abstract and variables are final.

- By default, all variables and methods inside an interface are public.

- Java provides an interface concept to support the concept of multiple inheritance.

Defining Interfaces:

interface  InterfaceName

{

Variable declarations;

Method declarations;

}

Variable declaration in an Interface:

static  final  type  variablename=value;

Method declaration in an interface:

returntype  methodname(parameter-list);

Example:

interface Area

{

final static float pi=3.14F;

float compute(float x,float y);

void show();

}

Extending Interfaces:

Syntax:

interface SubInterfaceName extends SuperInterfaceName

{

Variable declarations;

Method declarations;

}

Example:

interface A

{ }

interface B extends A

{ }

- Interface can be extended from more than one interface also

Example:

interface A

{

}

interface B

{

}

interface C extends A,B

{

}

Implementing Interfaces:

Syntax1:

class  classname  implements  interfacename

{

body of classname;

}

Syntax2:

class  classname  extends superclassname  implements  interface1,interface2,……..

{

body of classname;

}

 

Example Program:

Class implementing Claculator interface

interface Calculator

{

 int add(int a,int b);

 int subtract(int a,int b);

 int multiply(int a,int b);

 int divide(int a,int b);

}

class Normal_Calculator implements Calculator

{

 public int add(int a,int b){

 return a + b; }

 public int subtract(int a,int b) {

 return a – b; }

 public int multiply(int a,int b) {

 return a * b; }

 public int divide(int a,int b)

{

 return a / b;

}

 public static void main(String args[])

{

 Normal_Calculator c = new Normal_Calculator();

 System.out.println("Value after addition = "+c.add(5,2));

 System.out.println("Value after Subtraction = " +c.subtract(5,2));

 System.out.println("Value after Multiplication = " +c.multiply(5,2));

 System.out.println("Value after division = " +c.divide(5,2));

}

}

Output

C:\javabook>java Normal_Calculator

Value after addition = 7

Value after Subtraction = 3

Value after Multiplication= 10

Value after division = 2

 

Implementing Multiple Inheritance:

interface Car

{

    int  speed=60;

    public void distanceTravelled();

}

interface Bus

{

    int distance=100;

    public void speed();

}

public class Vehicle  implements Car,Bus

{

    int DT;

    int ASP;

    public void distanceTravelled()

    {

        DT=speed*distance;

        System.out.println("Total Distance Travelled is : "+DT);

    }

    public void speed()

    {

        int ASP=DT/speed;

        System.out.println("Average Speed maintained is : "+ASP);

    }

    public static void main(String args[])

    {

        Vehicle v1=new Vehicle();

        v1.distanceTravelled();

        v1.speed();

    }

}

Output:

Total Distance Travelled is : 6000

Average Speed maintained is : 100

 

 

 

 

 

 

 

11. Abstract Class Vs Interface:





12. Packages:

- A package is a collection of classes, interfaces and sub-packages.

- By using packages, we can reuse the code already we created.

- Packages are java’s way of grouping a variety of classes and/or interfaces together.

- Java API contains a set of classes and interfaces that are in the form of packages.




Types of packages:

- Java contains two types of packages

            i) Predefined Packages

            ii) User-defined Packages

i) Predefined Packages

- Java has many predefined packages.

- A package is contained many predefined classes and interfaces and all these are given by compressing into a single jar file called RT.jar file

- RT.jar file is located at,

            C:\jdk1.5\jre\lib\RT.jar

- Commonly used predefined packages are given in a table as,






- The smallest package in java is java.applet

- The biggest package in java is java.awt

 

Using System or Predefined Packages:

- We use predefined packages using import keyword.

Syntax:

import packagename.*;

OR

import packagename.classname;

Example:

import java.io.*;

import java.lang.Math;

ii) User-defined Packages:

- The general form of creating user-defined packages is

            package packagename;

Steps to create user-defined packages:

- Create a folder where directory name and package name to be created. Both must be same.

c:\>md pack1

- Change into created folder

            c:\>cd pack1

- Define the classes and interfaces required in each application or program and write first statement as package statement

            package packagename;

Example:

One.java

package pack1;

public class One

{

--------

--------

}

Two.java

package pack1;

public class Two

{

--------

--------

}

- Compile all the applications to get .class files. Now the package is created

c:\pack1>javac *.java

- Finally import this package into the other programs.

   This is called accessing a package

Accessing a user-defined package:

Syntax:

import packagename.*;

Example:

Sample.java

import pack1.*;

class Sample

{

public static void main(String args[])

{

-----------

-----------

}

}

 

 

13. java.lang PACKAGE:

- java.lang is a special package, as it is imported by default in all the classes that we create.

- There is no need to explicitly import the lang package.

- It contains the classes that form the basic building blocks of Java.

- Remember we have been using String and the System class, but we have not imported any package for using these classes, as both these classes lie in the java.lang package.

- Commonly used classes and interfaces are given in a table as,





- The wrapper classes for primitive types are given in a table as,






 

14. The java.util Package:

- The package java.util contains a number of useful classes and interfaces.

- Java util package contains collection framework, collection classes, classes related to date and time, event model, internationalization, and miscellaneous utility classes.

- On importing this package, you can access all these classes and methods.

- The classes and interfaces in java.util include:

S.NO

CLASS

PURPOSE

1

Hashtable class

for implementing hashtables, or associative arrays

2

Vector class

which supports variable-length arrays

3

Enumeration interface

for iterating through a collection of elements

4

StringTokenizer class

for parsing strings into distinct tokens separated by delimiter characters

5

EventObject class and the EventListener interface

which form the basis of the new AWT event model in Java 1.1.

6

Locale class

which represents a particular locale for internationalization purposes

7

Calendar and TimeZone classes

interpret the value of a Date object in the context of a particular calendar system

8

ResourceBundle class, 

ListResourceBundle and 

PropertyResourceBundle

which represent sets of localized data

 

15. GENERIC PROGRAMMING IN JAVA:

- The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.

- It makes the code stable by detecting the bugs at compile time.

- Before generics, we can store any type of objects in the collection, i.e., non-generic.

- Now generics force the java programmer to store a specific type of objects.

Advantage of Java Generics:

There are mainly 3 advantages of generics,

i) Type-safety: 

- We can hold only a single type of objects in generics.

- It doesn’t allow to store other objects.

- Without Generics, we can store any type of objects.

List list = new ArrayList();    

list.add(10);  

list.add("10");  

With Generics, it is required to specify the type of object we need to store.  

List<Integer> list = new ArrayList<Integer>();    

list.add(10);  

list.add("10");// compile-time error  

ii) Type casting is not required: 

List list = new ArrayList();    

list.add("hello");    

String s = (String) list.get(0);//typecasting    

After Generics, we don't need to typecast the object.  

List<String> list = new ArrayList<String>();    

list.add("hello");    

String s = list.get(0);    

iii) Compile-Time Checking: 

- It is checked at compile time so problem will not occur at runtime.

- The good programming strategy says it is far better to handle the problem at compile time than runtime.

List<String> list = new ArrayList<String>();    

list.add("hello");    

list.add(32);//Compile Time Error    

Syntax to use generic collection:

ClassOrInterface<Type>    

Example to use Generics in java:

ArrayList<String>