Java concepts Theory


For any type of consultation, query or doubt. You may contact to the following:
DEbabrataguha20@gmail.com 

and join the group 
https://www.facebook.com/groups/331231161093613/


Theory Type 1: Definition of OOPS Concepts


1.What is Object Oriented Programming (OOP)?

Object Oriented Programming is a programming approach based on the concept of “Objects” which can contain data in terms of fields and procedure.

2.What is JVM?

JVM is an acronym for Java Virtual Machine; it is an abstract machine which provides the runtime environment in which Java bytecode can be executed.

3.What is Class & Object?

Class:
A class is a blueprint representing a set of objects that share common characteristics and behavior.
Object:
Object is an entity with a specific identity and having specific characteristics and specific behavior.


4.What id Data abstraction, Encapsulation, Modularity , Inheritance, polymorphism?

Data Abstraction:

Data abstraction or abstraction refers to the act of representing essential features without using the background details.

Practical tips: (no need to write this in the answer sheet)**

As an example, we do not know the code behind Scanner class and its methods like nextInt() , nextDouble() etc. But we know how to use them. That is being called as Abstraction. If you move the steering of a car right , the car will move to the right. So we all know this method. But by which technique it happens, we do not know. This concept of hiding background details is being called as method abstraction.

Encapsulation:

The wrapping of data and functions (that operate on data) into single unit (called class) is known as encapsulation.

Practical tips: (no need to write this in the answer sheet)**

As an example, We know the method names of Scanner class. Methods like nextInt(), nextDouble. But we do not know the variable names used inside. Because those variables are hidden inside the class. This concept is being called as Encapsulation.  

Modularity:

The act of partitioning a program into individual components is called modularity.

Practical tips: (no need to write this in the answer sheet)**

Modularity is mainly maintained by functions/methods. Rather doing all the calculation together, in math class , xy can be done by pow function, sine value can be determined by a separate function named “sin”. So in short, one function for one type of work.

Inheritance:

Inheritence is the capability of one class of things to inherit or derive the capabilities or properties from another class.

Practical tips: (no need to write this in the answer sheet)**

class  a
{
       int x=10;
}
class b extends a
{
}
class c
{
       public static void main(String args[])
       {
              b obj = new b ();
              System.out.println(“the value is “ + obj.x)
       }
}

In the above program, class b does not contain anything. But as it is extending the class a, so class b is able to get the variable x inside it.


Polymorphism:

Polymorphism is a property by which the same message can be sent to objects of several different classes and each object can respond in a different way depending on its class.

Practical tips: (no need to write this in the answer sheet)**

//Overloading add method of Math class. Same method name is used twice

class Math
{
               public void add(int a, int b)                         //add method adding two integers
               {
                              System.out.println(a+b);
               }


               public void add(float a, float b)   //add method adding two floats
               {
                              System.out.println(a+b);
               }
}

class Overload
{
               public static void main(String args[])
               {
                              Math ob = new Math();
                              ob.add(1,2);
                              ob.add(2.5f,4.5f);
               }
               }


5.What is Byte Code?

Bytecode is program code that has been compiled from source code into low-level code , designed for a software interpreter.


6.What is token, literal , Identifier, variable , constant, Keywords?

Token:
           Smallest individual unit in a program is called a token.

Literal:
Literals are data items that are fixed data values. There are several kinds of literals available in java. Like Integer literals, Floating point literals, Boolean literals, character literals etc.

Identifier:
Identifiers are the names given by the programmer to various program units of java. Identifiers are the names of variables, methods, classes etc.

Variable:
Variable is a named memory location which holds a data value of a particular datatype.

Constant:
Constant value represents a named value that remains fixed throughout an entire program . We can declare a constant using “Final” keyword.

Keyword:
a keyword is a word with a predefined meaning in Java programming language syntax. Reserved for Java, keywords may not be used as identifiers for naming variables, classes, methods or other entities.

Practical tips: (no need to write this in the answer sheet)**

void meth ()
{
      int x = a + 5 ;
}

Token       à  “void” , “meth” , “int” , “x” , “=” , “a” , “+” , “5” , “;”
Literal       à  “5”
Identifier  à  “x” , “a” , “meth”
Variable    à  “x” , “a”
Keywords à  “void” , “int”
Operator  à  “=” (assignment operator)  , “+” (binary mathematical operator)
Punctuator à “;”

7.What is datatype? What are the different types of datatypes?

Datatype is used to identify the type of data and associated operations of handling it.

            There are 2 types of datatypes as below:

i.                 Primitive Datatype / Fundamental Datatype
ii.                Reference Datatype / Derived Datatype

8.What are primitive datatype and reference data type?

           Primitive Datatype:

Primitive datatype or fundamental datatypes are provided by language and are not based on any other datatypes. It is used to define and hold a value of basic type in named variable.

           Reference Datatype:

Reference datatype are created using the primitive datatypes. A reference datatype is used to store memory address of an object.

Practical tips: (no need to write this in the answer sheet)**

class a
{
               int x=10;             
}

class datatype_demo
{
               public static void main(String args[])
               {
                              a ob1=new a();       // reference datatype
                              int ob2;                    // primitive datatype
               }
              }  


9.What is operator? What are the different types of operator? Give examples for each type.

Operator:

An operator is a symbol that tells the compiler or interpreter to perform specific  mathematical, relational, logical operations and produce final results.

Types of operator:

i.                 Mathematical operator                              (example: + , - , * ,  / ,  % )
ii.                Increment/Decrement operator              ( example: ++ , -- )
iii.              Relational operator                                      (example: > , < , >= , <= , == , != )
iv.              Logical operator                                            (example: &&, || , !)
v.                Assignment operator                                   ( example:= )


10.What is fall through?

               Fall of control to the following cases of matching case is called fall through.



Practical tips: (no need to write this in the answer sheet)**

class fallthrough
{
               public static void main(String args[])
               {
                              int a=2;
                              switch (a)
                              {
                                             case 1:  System.out.println("one");
                                             case 2:  System.out.println("two");
                                             case 3:  System.out.println("three");
                                             case 4:  System.out.println("four");
                                                            break;
                                             case 5:  System.out.println("five");
                              }
               }
}  

Here, output will be “ two three four” , because if we do not put “break” statement, it will keep falling and keep executing the statements.


           
11.What is jump statement? What is the use of break and continue statement?

The statements that cause unconditional control-transfer in program are called jump statements. Two most common jump statements are break and continue.

Break statement:

When Break statement is used inside switch , it ends the case. When break statement is executed inside a loop, the loop terminated and program control resumes at the next statement following the loop.

Continue statement:

When Continue statement is executed from inside a loop, from that point all remaining statements in the body of the loop are skipped and loop proceeds with the next iteration.


12.How is the if…else if combination more general than a switch statement?

Switch statement must be controlled by a single integer control variable and each case section corresponds to a single constant value for the variable. The if .. else if combination allows any kind of condition supporting all types of comparisons after each if.



13.What is type conversion? What is explicit and implicit type conversion?

Type conversion means converting a variable of one data type to another.

There are 2 categories of Type Conversion as follows:

Explicit type conversion:

              When we are assigning a larger type value to a variable of smaller type, then we need to               perform explicit type casting.

Implicit type conversion:

              When we are assigning a smaller type value to a variable of larger type, then this type of conversion happens automatically. This type of conversion is called as implicit type casting.

Practical tips: (no need to write this in the answer sheet)**

class type_conversion_demo
{
               public static void main(String args[])
               {
                              int a=5;
                              double b=9.5;
                             
                              b=a;                      // implicit type conversion
                              a=(int) b;             // explicit type conversion
               }
              }    


14.What is access specifier? What are the access levels or specifiers supported by java?

Access specifiers control access to members of  a class from within a java program.

Access levels available in java:

                           i.          Public
                          ii.          Private
                        iii.          Protected
                        iv.          Default


15.What is wrapper class?

Wrapper classes are specially designed classes that act as wrappers to primitive data types so that primitive values can be accessed as objects.


16.What are the advantages of Encapsulation?

Advantages of encapsulation are as follows:

                           i.          Data hiding
                          ii.          Implementation logics are hidden
                        iii.          Flexibility
                        iv.          More control in programmer’s hand


17.What is Data hiding?

Data hiding is a software development technique specifically used in object-oriented programming (OOP) to hide internal object details (data members). Data hiding ensures exclusive data access to class members and protects object integrity by preventing unintended or intended changes.


18.What is the use of Final Keyword?

final keyword is used with Class to make sure no other class can extend it, for example String class is final and we can’t extend it.

We can use the final keyword with methods to make sure child classes can’t override it.

final keyword can be used with variables to make sure that it can be assigned only once.

However the value of a variable can not be changed if we put a final in front of that.


Practical tips: (no need to write this in the answer sheet)**

Example 1: Use of “Final” keyword in front of a class

final class a
{

}

class b extends a     //will throw an error, because you can not extend a final class
{

               }    

Example 2: Use of “Final” keyword in front of a method

class a
{
               final void meth1()
               {
                              System.out.println("hi");
               }
               void meth2()
               {
                              System.out.println("hello");
               }
}

class b extends a
{
               void meth1()       // will throw an error, because you can not override meth1()
               {
                              System.out.println("hi again");
               }
               void meth2()       // you can override meth2()
               {
                              System.out.println("hello again");
               }

              }

Example 3: Use of “Final” keyword in front of a variable

class a
{
               public static void main(String... ar)
               {
                              final int a=5;
                              a++        // this line will throw an error, as you can not change the value of a final variable
               }
 } 


19.What is the use of Static Keyword?

static keyword is mainly used for memory management. It can be used with variables, methods, blocks and nested classes. It is a keyword which is used to share the same variable or method of a given class. Basically, static is used for a constant variable or a method that is same for every instance of a class.

Practical tips: (no need to write this in the answer sheet)**

class a
{
               static int x;
               int y;
}

class b
{
               public static void main(String... ar)
               {
                              a ob1=new a();
                              a ob2=new a();
                              a ob3=new a();

                              ob1.x=10;            ob1.y=100;
                              ob2.x=20;            ob2.y=200;
                              ob3.x=30;            ob3.y=300;
                             
                              System.out.println(" x--> "+ob1.x +" & y--> "+ob1.y);  //prints “x--> 30 & y --> 100”
                              System.out.println(" x--> "+ob2.x +" & y--> "+ob2.y);  //prints “x--> 30 & y --> 200”
                              System.out.println(" x--> "+ob3.x +" & y--> "+ob3.y);  //prints “x--> 30 & y --> 300”
                             
                              System.out.println(" one version of x--> "+a.x);  // as there is one version of x, we can call it by its class name
               }
} 
    


20.What is ternary operator in java??

Java ternary operator is the only conditional operator that takes three operands. It’s a one liner replacement for if-then-else statement and used a lot in java programming. We can use ternary operator if-else conditions or even switch conditions using nested ternary operators.

Practical tips: (no need to write this in the answer sheet)**

example 1:

if(a>10)
{
               b=1;
}
else
{
               b=0;
}

it can be written as the following way

b=(a>10)?1:0;    


example 2:

if(a>10)
{
               System.out.println(“hi”);
}
else
{
               System.out.println(“hello”);
}

it can be written as the following way

System.out.println(  (a>10)? ”hi” ; ”hello”  ) ;



example 3:

if(a > b)
{
               if ( a > c)
               {
                              max=a;
               }
               else
               {
                              max=c;
               }
}
else
{
               if ( b > c)
               {
                              max=b;
               }
               else
               {
                              max=c;
               }
}

it can be written as the following way

max = ( a>b ) ? (  (a>c)?a:c  )  : (  (b>c)?b:c  ) ;



21.What is overriding?

In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes.

Practical tips: (no need to write this in the answer sheet)**

class  a
{
               int x=10;
               void meth()
               {
                              System.out.println("hi");
               }
}
class b extends a
{
               int x=20;                   // overrides the previous x
               void meth()             // overrides the previous meth()
               {
                              System.out.println( “ hello” ) ;
               }
            }
class c
{
               public static void main ( String args[] )
               {
                                             b ob = new b ();
                              System.out.println ( ob.x ) ;       // prints 20
                              ob.meth();                                    // prints “hello”
               }
            }



22.What does super keyword do?

super keyword can be used to access super class method or variable when you have overridden the method or variable in the child class.

We can use super keyword to invoke superclass constructor in child class constructor.

Practical tips: (no need to write this in the answer sheet)**

class  a
{
               int x=10;
               void meth()
               {
                              System.out.println("hello");
               }
}
class b extends a
{
               int x=20;
               void meth()
               {
                              super.meth(); // it will print "hello"
                              System.out.println(super.x) // it will print 10       
               }
            }


23.What is Constructor? When is it invoked?

A constructor is a special type of member-method having the same name as that of the class.

A constructor of a class is invoked automatically at the time of object creation.


24.What is Default constructor?

A constructor that accepts no parameters is called non-parameterized constructors and are also considered as default constructor.

 

25.Write 2 features of constructor.

                 i.          Constructor has the same name as that of a classs
                ii.          Constructor has no return type, not even void.


26.What is constructor overloading?

Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter list. The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.



27.What are the different types of constructors? Define each of them.

Default Constructor or non-parameterized constructor:

               A constructor that accepts no parameters is called non-parameterized constructor and are also considered as default constructor.

Parameterized constructor:

               A constructor is a member method having the same name as that of its class and no return type. It receives parameters and initialize the objects with the received values.


Practical tips: (no need to write this in the answer sheet)**

class  a
{
               int x;
               a()
               {
                              x=1;
               }
               a( int param)
               {
                              x=param;
               }
}
class b
{
               public static void main ( String args[] )
               {
                              a ob1 = new a ();                             //calling default constructor
                              a ob2 = new a ( 50 );                      //calling parameterized constructor
                              System.out.println ( ob1.x ) ;  // prints 1
                              System.out.println ( ob2.x ) ;  // prints 50
               }
               }


28.What is  “This” keyword? What is its significance?

Member functions of every object have access to a magic keyword named “this”, which points to the object itself. Thus any member function can find out the address of the object of which it is a member.

The this keyword represents an object that invokes a member function

Practical tips: (no need to write this in the answer sheet)**
class  a
{
               int x;
               void meth ( int x)
               {
                              this.x=x;   // “this.x” denotes the class variable x, whereas “x” denotes the local variable to the function meth()
               }
}


29.Write the advantages of functions / methods?

                           i.          Functions divide complex task into smaller , easily understandable tasks.
                          ii.          Functions are useful in hiding the implementation details.
                        iii.          Function enhance reusability of code.


30.What are the different parts available in Method definition?

                           i.          Access Specifier                              (Example : Public, Private, Protected, Default)
                          ii.          Modifier                                            (Example: Final, Volatile, Native etc.)
                        iii.          Return type                                      (Example: void, int, float etc.)
                        iv.          Method name


Practical tips: (no need to write this in the answer sheet)**

public final void meth ( int x)
{
               System.out.println(“hi”);
}

In the above function,

Access Specifier  à “public”
Modifier               à “Modifier”
Return type         à  “Void”
Method name     à  “meth”


31.What is method/Function prototype?

Method prototype is the 1st line of the function definition that tells the program about the type of the value returned by the method and the number and type of arguments.


32.What is method signature?

Method signature refers to the number and types of arguments.

Practical tips: (no need to write this in the answer sheet)**

void meth ( int x)
{
               System.out.println(“hi”);
}

In the above function, function prototype is : “void meth (int x)
                                         function signature is :  “int x”


33.What are pure and impure methods?

Pure method:

A pure method is the one that takes objects and/or primitives as arguments but does not modify the objects.

Impure method:

An impure method is the one that takes objects and changes or modifies the state of received object.



34.What is function overloading?

A function name having several definitions in the same scope that are differentiable by the number or types of their argument is said to be an overloaded function. Process of creating overload function is called function overloading.


Practical tips: (no need to write this in the answer sheet)**

You can use the example used in polymorphism at the first of this note.


35.What is package?

A package is a group or a collection that consist of related classes and interfaces. There are two types of packages in a programming language. They are the built-in packages and user-defined packages. The programming language Java consist of built-in packages such as lang, awt, javax, swing, net, io, util, sql, etc.


36.What is interface?

Interface is a mechanism of achieving abstraction and multiple inheritance. The methods in an interface are abstract methods. These methods do not have any implementation. It can also have variables or fields.


37.What are the advantages and disadvantages of Array?

Advantages:

1. It is used to represent multiple data items of same type by using only single name.
2. It can be used to implement other data structures like linked lists, stacks, queues, trees, graphs etc.
3. 2D arrays are used to represent matrices.

Disadvantages:

1. We must know in advance that how many elements are to be stored in array.
2. Array is static structure. It means that array is of fixed size. The memory which is allocated to array can not be increased or reduced.
3. Since array is of fixed size, if we allocate more memory than requirement then the memory space will be wasted. And if we allocate less memory than requirement, then it will create problem.
4. The elements of array are stored in consecutive memory locations. So insertions and deletions are very difficult and time consuming.


























Theory type 2: Differences


1.Differentiate between actual and formal parameters.

Actual parameters are the parameters appearing in function call statement, that is these represent the values passed to the called function.

Formal parameters are the ones that appear in function definition , that is these represent the values received by the called function.

Practical tips: (no need to write this in the answer sheet)**

class  a
{
               void meth( int param)     // here "param" is formal parameter
               {
                              System.out.println (param);
               }
}
class b
{
               public static void main ( String args[] )
               {
                              a ob = new a ();
                              x=5;
                              ob.meth ( x );     // Here x is actual parameter, because we know the exact/actual value at the time of calling
               }
               }




2Difference between 2 ways of invoking functions?

There are following 2 ways of invoking functions:

Call by value:

               By this way, the called function creates its own workcopy for passed parameters and copies the passed values in it. Any changes that take place remains intact.


Call by reference:

               By this way, the called function receives the reference to the passed parameters and through this reference , it accesses the original data. Any changes that take place are reflected in the original data.


Practical tips: (no need to write this in the answer sheet)**

class a
{
               int x=10;
               void meth1(int y)
               {
                              y=y+1;
               }
               void meth2(a ob)
               {
                              ob.x = ob.x+1;
               }
}
class b
{
               public static void main(String args[])
               {
                              a obj=new a();
                              System.out.println("value is "+ obj.x);                     // it will print the initial value of x as 10;
                              obj.meth1(obj.x);
                              System.out.println("value is "+ obj.x);                     // call by value can not change the original value
                              obj.meth2(obj);
                              System.out.println("value is "+ obj.x);                     // if you make any change during "call by reference" in an object, there would be permanient changes inside

               }
}


3.What is the difference between class variable (static variable) and instance variable?

Static/class variable:

A data member that is declared once for a class. All of the objects of that class type share these data members, as there is single copy of them is available in memory.

Instance variable:

A data member that is created for every object of the class. For n number of object of a class, there would be n copies of instance variables, one each for object.

Practical tips: (no need to write this in the answer sheet)**

You can use the example used in “static keyword”  at the first of this note (Question #19).
In that case, x will be “Class variable “
                       y will be “instance variable “


4.What is the difference between autoboxing and unboxing?

When java automatically converts a primitive type into corresponding wrapper class object (as an example from int to integer), then it is called boxing, because primitive is boxed into wrapper class while opposite case is called unboxing (When an integer object is converted into primitive int).

Since the whole process happens automatically without writing any code for conversion it is

Practical tips: (no need to write this in the answer sheet)**

class demo
{
               public static void main(String args[])
               {
                              int i1=5;
                              Integer i2= new Integer(10);

                              i1=i2;     // unboxing
                              i2=i1;     // boxing                           
               }
              }


5.What is the difference between an object and a class?

A class represents a set of objects that share common characteristics and behavior.

Objects are the instances of a class. Objects represents the abstraction represented by the class in the real sense.


6.What is the difference between while and do-while loop?

                 i.          Both types of loops repeat a block of statements until some condition becomes false. The main difference is that in a while loop , the test condition is tested at the beginning of the loop and in a do-while loop , the test-condition is tested at the end of the loop.

                ii.          Also it is possible that body of while loop might not be executed at all . However the body of a do-while loop is executed at least once since the test condition for ending the loop is not tested until the body of the loop has been executed.


7.What is the difference between methods and constructor?

Parameter Constructors Methods
Purpose Creates an instance of class Groups Java statements
Return type Has no return type Void or a valid return type
Name Same name as the class Any name except the class name
Execution Called at the time of Object Creation Called when a function call for the specific method is encountered.


8.What is the difference between throw and throws?


Throw Throws
throw keyword is used to throw an exception explicitly. throws keyword is used to declare one or more exceptions
Only single exception is thrown by using throw. Multiple exceptions can be thrown by using throws.
throw keyword is used within the method. throws keyword is used with the method signature..


9.What is the difference between Break and Continue?

Break Continue
A break causes the switch or loop statements to terminate the moment it is executed. Loop or switch ends abruptly when break is encountered A continue doesn't terminate the loop, it causes the loop to go to the next iteration.
The break statement can be used in both switch and loop statements. The continue statement can appear only in loops.
When a break statement is encountered, it terminates the block and gets the control out of the switch or loop. When a continue statement is encountered, it gets the control to the next iteration of the loop.


10.What is the difference between Linear and Binary search?

Linear Search Binary Search
Linear search is an algorithm to find an element in a list by sequentially checking the elements binary search is an algorithm to find the position of a target value within a sorted array.
Also called sequential search. Also called half-interval search and logarithmic search
It is not required to sort the array before searching It is required to sort the array before searching.
Less efficient More efficient


11.What is the difference between Bubble and Selection sort?

Bubble sort Selection sort
A simple sorting algorithm that continuously steps through the list and compares the adjacent pairs to sort the elements. A sorting algorithm that takes the smallest value (considering ascending order) in the list and moves it to the proper position in the array. 
Uses item exchanging Uses item selection
Takes only 1 full iteration in case of array is already arranged in sorted order. It completes all the iterations even if the array is sorted


12.What is the difference between Error and Exception ?

Error Exception
Recovering from Error is not possible. We can recover from exceptions by either using try-catch block or throwing exceptions back to caller.
All errors in java are unchecked type. Exceptions include both checked as well as unchecked type.
Errors are mostly caused by the environment in which program is running. Program itself is responsible for causing exceptions.
Errors occur at runtime and not known to the compiler. All exceptions occurs at runtime but checked exceptions are known to compiler while unchecked are not.
They are defined in java.lang.Error package. They are defined in java.lang.Exception package


13.What is the difference between If-Else block and Switch ?

  1. expression inside if statement decide whether to execute the statements inside if block or under else block. On the other hand, expression inside switch statement decide which case to execute.
  2. You can have multiple if statement for multiple choice of statements. In switch you only have one expression for the multiple choices.
  3. If-esle statement checks for equality as well as for logical expression . On the other hand, switch checks only for equality.
  4. The if statement evaluates integer, character, pointer or floating-point type or boolean type. On the other hand, switch statement evaluates only character or a integer datatype.
  5. Sequence of execution is like either statement under if block will execute or statements under else block statement will execute. On the other hand the expression in switch statement decide which case to execute and if you do not apply a break statement after each case it will execute till the end of switch statement.
  6. If expression inside if turn outs to be false, statement inside else block will be executed. If expression inside switch statement turn out to be false then default statements is executed.
  7. It is difficult to edit if-else statements as it is tedious to trace where the correction is required. On the other hand it is easy to edit switch statements as they are easy to trace.


14.Write the difference between single dimension array and double dimension array.

Single dimension array Double dimension array
A simple data structure that stores a collection of similar type data in a contiguous block of memory. A type of array that stores multiple data elements of the same type in matrix or table like format with a number of rows and columns.
Stores data as list. Stores data in a row-column format.
Syntax: data_type name[]=new datatype[] Syntax: data_type name[][]=new datatype[][]
Errors occur at runtime and not known to the compiler. All exceptions occurs at runtime but checked exceptions are known to compiler while unchecked are not.
They are defined in java.lang.Error package. They are defined in java.lang.Exception package




15.Write the difference between explicit type casting and implicit type casting

Or,

Difference between type casting and type conversion


Implicit type casting or type conversion Explicit type casting or type casting
Implicit typecasting or type conversion is that which automatically converts one datatype into another. When an user can convert the one datatype into other, then it is called type conversion or implicit type casting
Implemented only when two datatypes are compatible Implemented on two incompatible datatypes
Widening conversion Narrowing conversion
Casting operator is not required. Casting operator “()” is required. 


16.Write the difference between searching and sorting

a.     In searching, a certain array is to be searched for whereas in sorting the members of the array are to be sorted in a particular order, i.e. descending or ascending order.

b.     Searching returns the position of the searched array while sorting returns an array with the elements arranged in ascending or descending order.


17.Write the difference between “.equals()” and “==”

a.     type: “==” is a binary operator , whereas “.equals() “ is a function 
b.     primitive or objects: “==” is used to compare primitives while “.equals()” is used to check equality of objects.
c.      Comparision: “==” compares two objects based on memory reference. Equals method compares based on the values


18.Write the difference between unary , binary and ternary operator.

                 i.          Unary operators are those that work on single operand e.g. increment operator( ++) or the decrement operator( - - ). int a =b++; or something like int C =d- -;

               ii.          Binary operators are the one that operate on two operands e.g. ‘+’, ‘ -’, ‘ *’, ‘/’. Syntax can be like int C=a+b;

              iii.          Ternary operators are the one that operates on three operands. It takes three argumets . 1st argument is checked for its validity . If it is true 2nd argument is returned else third argument is returned. For example if we write int C= a>b ? e:f; now if a is greater than b 'e' is returned otherwise 'f' is returned.


19.Write the difference between rint() and round()

                 i.          Rint() returns long value, whereas round returns double value.

               ii.          For the value like 1.5 or 9.5, rint() returns nearest lower rounded value as 1 and 9 respectively. Whereas for round(), it returns nearest upper rounded value as 2 and 10 respectively.

20. Write the difference between public , private and protected.
A public member is accessible from anywhere outside the class but within a program. You can set and get the value of public variables without any member.
A private member variable or function cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members.
A protected member variable or function is very similar to a private member but it provided one additional benefit that they can be accessed in child classes which are called derived classes.


21.Write the difference between next() and nextLine()

next() method can take input till space and ends input of getting space.

nextLine() method can take input till the line change or new line and ends input of getting '\n' or press enter.


22.Write the difference between package and interface

Package Interface
An organized set of related classes and interfaces A set of fields and abstract methods that mainly allows implementing abstraction
Import keyword helps to access a package Implement keyword helps to access an interface


23.Write the difference between Final , Finally and Finalize

Final Finally Finalize
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.
It is a keyword It is a block It is a method


24.Write the difference between catch() and finally()

catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.

Finally − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.


25.What is the difference between overloading and overriding?

OverloadingOverriding
In method overloading, more than one method shares the same method name with different signature in the class.In method overriding, derived class provides the specific implementation of the method that is already provided by the base class or parent class.
Method overloading may or may not require inheritance.While method overriding always needs inheritance.
In this, methods must have same name and different signature.While in this, methods must have same name and same signature.
It is Compile time polymorphismIt is Run time polymorphism
return type can or can not be be samereturn type must be same















Theory type 3: charts

1.Please specify the size of different datatypes.

Datatypes
Size (in Byte)
Byte
1
Short
2
Int
4
Long
8
Float
4
Double
8
Char
2


2.Please specify different type of exceptions , Errors and their functionality.

Exception
Meaning
ArithmeticException
Arithmetic error, such as divide-by-zero
ArrayIndexOutOfBoundsException
Array index is out of the limit
NullPointerException
Invalid use of NULL reference
NumberFormatException
Invalid conversion of a string to a numeric
InputMismatchException
Wrong type of data inserted


3.Please specify the string functions.

Functions
Functionality
Syntax
substring
Extract a string from a string
String s="SachinTendulkar";  
   System.out.println(s.substring(6));//Tendulkar  
   System.out.println(s.substring(0,6));//Sachin

compareTo
Compares two strings lexicographically
String s1="hello";  
String s2="hello";  
String s3="meklo";  
String s4="hemlo";  
String s5="flag";  
System.out.println(s1.compareTo(s2));//0 because both are equal  
System.out.println(s1.compareTo(s3));//-5 because "h" is 5 times lower than "m"  
System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m"  
System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f" 

indexOf
Returns the position of the first found occurrence of specified characters in a string
String s1="this is index of example";  
//passing substring  
int index1=s1.indexOf("is");//returns the index of is substring  
int index2=s1.indexOf("index");//returns the index of index substring  
System.out.println(index1+"  "+index2);//2 8  
  
//passing substring with from index  
int index3=s1.indexOf("is",4);//returns the index of is substring after 4th index  
System.out.println(index3);//5 i.e. the index of another is  
  
//passing char value  
int index4=s1.indexOf('s');//returns the index of s char value  
System.out.println(index4);//3  

lastIndexOf()
Returns the position of the last found occurrence of specified characters in a string
String s1="this is index of example";//there are 2 's' characters in this sentence  
int index1=s1.lastIndexOf('s');//returns last index of 's' char value  
System.out.println(index1);//6  

toLowerCase()
Converts a string to lower case letters
String s=”Hello Hi”;
System.out.println(s.toLowerCase());
 // “hello hi”
To UpperCase()
Converts a string to upper case letters
String s=”Hello Hi”;
System.out.println(s.toUpperCase());
 //  “HELLO HI”
trim()
Removes whitespace from both ends of a string
String s=”       Hello          Hi            ”;
System.out.println(s.trim());
 // “hello        hi”
startsWith()
Checks whether a string starts with specified characters
String s=”Hello Hi”;
System.out.println(s.startsWith(“he”));
 // true
endsWith()
Checks whether a string ends with specified characters
String s=”Hello Hi”;
System.out.println(s.endsWith(“hi”));
 // true
replace()
Searches a string for a specified value, and returns a new string where the specified values are replaced
String s=”Hello Hi”;
System.out.println(s.replace(“e”,”aa”));
 // Haallo Hi
System.out.println(s.replace(‘H’,’X’));
 // Xello Xi
equals()
Compares two strings. Returns true if the strings are equal, and false if not
String s1=”Hello”;
String s2=”hello”;
String s3=”Hi”;

System.out.println(s1.equals(s2));
 // False
System.out.println(s1.equals(s3));
 // False
equalsIgnoreCase()
Compares two strings, ignoring case considerations
String s1=”Hello”;
String s2=”hello”;
String s3=”Hi”;

System.out.println(s1.equalsIgnoreCase(s2));
 // true
System.out.println(s1.equalsIgnoreCase(s3));
 // False


Comments

Popular posts from this blog

About Myself ..

MS SQL SERVER SOLUTION (Chapter 4 ) : Group By