Java Assignment – 1



Ans.

Following are the notable features of Java:

1. Object Oriented

In Java, everything is an Object. Java can be easily extended since it is based on the Object model.

2. Platform Independent

Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform-independent byte code. This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.

3. Simple

Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be easy to master.

4. Secure

With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption.

5. Architecture-neutral

Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system.

6. Portable

Being architecture-neutral and having no implementation dependent aspects of the specification makes Java portable. The compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset.

7. Robust

Java makes an effort to eliminate error-prone situations by emphasizing mainly on compile time error checking and runtime checking.

8. Multithreaded

With Java's multithreaded feature it is possible to write programs that can perform many tasks simultaneously. This design feature allows the developers to construct interactive applications that can run smoothly.

9. Interpreted

Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light-weight process.

10. High Performance

With the use of Just-In-Time compilers, Java enables high performance.

11. Distributed

Java is designed for the distributed environment of the internet.

12. Dynamic

Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry an extensive amount of run-time information that can be used to verify and resolve accesses to objects at run-time.



Ans.

      Wrapper class is used to convert any datatype in to object.

      The primitive datatypes are not object. They do not belong to any class. They are defining in the language itself.

      Sometimes, it is required to convert datatype into object in java.

      For example: - In a java Vector class does not support primitive datatype. So, we have to compulsory convert primitive datatype into object.

      Wrapper class solves converting simple type.

Primitive Datatype

Wrapper Class

boolean

Boolean

char

Character

double

Double

float

Float

int

Integer

long

Long


      Example:

class WrapperDemo{
                     public static void main(String args[ ]){
                                 int a=10;
                                 Integer i=Integer.valueOf(a);
                                 System.out.println(“a=”+a+”i=”+i);
                    }
} 

Ans. 

There are five states in Thread life cycle.

1.      Newborn state

2.      Runnable state

3.      Running state

4.      Blocked state

5.      Dead state


1) New born state

ü  When we create a thread object, the thread is born and is said to be in newborn state.

ü  The thread is not still scheduled for running. 

2) Runnable state

  ü The next state after the newborn state is Runnable state.

ü  Runnable state means that the thread is ready for execution and is waiting for the availability of the processor.

ü  The threads has joined waiting queue for execution based on priority of thread. 

3) Running state 

ü Running means that processor has given its time to the thread for its execution.

ü  A running thread may change its state to another state using resume (), modify (), sleep (), wait () methods etc.

    4) Blocked state

ü  A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently the running state.

ü  This happens when the thread is suspended, sleeping or waiting in order to satisfy certain requirements.

              5) Dead state

ü  Every thread has a life cycle. A running thread ends its life when it has completed executing its run ( ) method.
ü  It is natural death. However we can kill it by sending the stop message to it as any state thus causing a premature death for it. 

 


Ans.

      Inheritance is a process by which object of one class run the properties of object of another class.

      Inheritance provides reusability of code.

      Reusing the properties of existing class is called inheritance.

      Types of Inheritance

 1.  Single Inheritance

In Single Inheritance one class extends another class (one class only).

2.  Hierarchical Inheritance

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.



3.  Multilevel Inheritance

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance.



4.  Multiple Inheritances

            In Multiple Inheritance, one class extending more than one class. Java does not support multiple inheritance.


5.  Hybrid Inheritance

        Hybrid inheritance is a combination of Single and Multiple inheritance.




Ans.

      Java does not support multiple inheritances.

      Multiple inheritance mean one sub class and more than one super class.

      Java provides alternate solution for multiple inheritances that is interface.

      Using interface we can implements multiple inheritance.

      Interface is basically a kind of class.

      Interface contains methods and variable but it defines only abstract method and final variable.

      Interface does not specify any code to implement methods (method does not have body).

      Java use interface keyword to create interface.

      Syntax:

 interface interfaceName{
			Variable Declaration;
			Method Declaration;
}

      Example:

 interface A{ int i=10;}
interface B{int j=20;}
class C implements A,B{
        void sum(){
                 System.out.println(“the sum is ”+(i+j));
         }
}

class InterFaceDemo{
        public static void main(String args[]){
                C c1=new C();
				c1.sum();
        }
}


Ans.

In Java, the finally block is always executed no matter whether there is an exception or not.

The finally block is optional. And, for each try block, there can be only one finally block.

The basic syntax of finally block is

try {
  //code
}
catch (ExceptionType1 e1) { 
  // catch block
}
finally {
  // finally block always executes
}
If an exception occurs, the finally block is executed after the try...catch block. Otherwise, it is executed after the try block. For each try block, there can be only one finally block.

Example: Java Exception Handling using finally block

class Main {
  public static void main(String[] args) {
    try {
      // code that generates exception
      int divideByZero = 5 / 0;
    }

    catch (ArithmeticException e) {
      System.out.println("ArithmeticException => " + e.getMessage());
    }
    
    finally {
      System.out.println("This is the finally block");
    }
  }
}

Output

ArithmeticException => / by zero
This is the finally block

Ans.

The Java throw keyword is used to explicitly throw a single exception.

When we throw an exception, the flow of the program moves from the try block to the catch block.

Example: Exception handling using Java throw

class Main {
  public static void divideByZero() {

    // throw an exception
    throw new ArithmeticException("Trying to divide by 0");
  }

  public static void main(String[] args) {
    divideByZero();
  }
}

Output

Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0
        at Main.divideByZero(Main.java:5)
        at Main.main(Main.java:9)


Ans.

Constructors with the same name but different signature are called overloaded constructors. They may have different numbers of arguments, different sequences of arguments, or different types of arguments. Let’s have a look at the below program.

Example

class Student {

    private String name;

    private int id;

    //no-argument constructor
    public Student() { System.out.println("no-argument constructor called !");}
    
    //overloaded constructor with one argument(name)
    public Student(String name) {
        this.name = name;
        System.out.println("constructor with one argument(name) called !");
    }

    //overloaded constructor with one argument(id) 'argument type is different'
    public Student(int id) {
        this.id = id;
        System.out.println("constructor with one argument(id) called !");
    }


    //another overloaded constructor with two argument (String , int)
    public Student(String name, int id) {
        this.name = name;
        this.id = id;
        System.out.println("constructor with two arguments(String , int) called !");
    }

    //another overloaded constructor with two argument (int , String) 'Seq of arguments is different'
    public Student(int id, String name) {
        this.name = name;
        this.id = id;
        System.out.println("constructor with two arguments(int , String) called !");
    }
}

class Main {

    public static void main(String args[]) {

        //object creation and no-argument constructor called
        Student s1 = new Student();

        //object creation and constructor with one param(String) called
        Student s2 = new Student("Vikram");

        //object creation and constructor with one param(int) called
        Student s3 = new Student(10);

        //object creation and constructor with two params (String ,int) called
        Student s4 = new Student("Vikas",29);

        //object creation and constructor with two params (int , String) called
        Student s5 = new Student(29,"Vivek");


    }
}


no-argument constructor called !
constructor with one argument(name) called !
constructor with one argument(id) called !
constructor with two arguments(String , int) called !
constructor with two arguments(int , String) called !

Ans.
MULTITHREADING in Java is a process of executing two or more threads simultaneously to maximum utilization of CPU. Multithreaded applications execute two or more threads run concurrently. Hence, it is also known as Concurrency in Java. Each thread runs parallel to each other. Mulitple threads don't allocate separate memory area, hence they save memory. Also, context switching between threads takes less time.

public class GuruThread1 implements Runnable
{
       public static void main(String[] args) {
        Thread guruThread1 = new Thread("Guru1");
        Thread guruThread2 = new Thread("Guru2");
        guruThread1.start();
        guruThread2.start();
        System.out.println("Thread names are following:");
        System.out.println(guruThread1.getName());
        System.out.println(guruThread2.getName());
    }
    @Override
    public void run() {
    }
 
}



Ans.

No.finalfinallyfinalize
1)Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final method can't be overridden and final variable value can't be changed.Finally is used to place important code, it will be executed whether exception is handled or not.Finalize is used to perform clean up processing just before object is garbage collected.
2)Final is a keyword.Finally is a block.Finalize is a method.

Java final example

class FinalExample{  
public static void main(String[] args){  
final int x=100;  
x=200;//Compile Time Error  
}}  

Java finally example

class FinallyExample{  
public static void main(String[] args){  
try{  
int x=300;  
}catch(Exception e){System.out.println(e);}  
finally{System.out.println("finally block is executed");}  
}}  

Java finalize example

class FinalizeExample{  
public void finalize(){System.out.println("finalize called");}  
public static void main(String[] args){  
FinalizeExample f1=new FinalizeExample();  
FinalizeExample f2=new FinalizeExample();  
f1=null;  
f2=null;  
System.gc();  
}}  


1 comment:

Ravi Kunpara said...

superb bro
social media lead pan chalu kari diyo

Get new posts by email:


APY Logo