JAVA IMP QUESTIONS

1.  Explain different operators in java with example programs

Java provides many types of operators which can be used according to the need. They are classified based on the functionality they provide. Some of the types are:

  1. Arithmetic Operators
  2. Unary Operators
  3. Assignment Operator
  4. Relational Operators
  5. Logical Operators
  6. Ternary Operator
  7. Bitwise Operators
  8. Shift Operator

Let’s take a look at them in detail. 

1. Arithmetic Operators: They are used to perform simple arithmetic operations on primitive data types. 

  • * : Multiplication
  • / : Division
  • % : Modulo
  • + : Addition
  • – : Subtraction

2. Unary Operators: Unary operators need only one operand. They are used to increment, decrement or negate a value. 

  • ++ : Increment operator
    • Post-Increment: 
    • Pre-Increment: 
  • — : Decrement operator,
    • Post-decrement: 
    • Pre-Decrement:

3. Assignment Operator: ‘=’ Assignment operator is used to assign a value to any variable. 

4. Relational Operators: These operators are used to check for relations like equality, greater than, less than. They return boolean results after the comparison and are extensively used in looping statements as well as conditional if-else statements. The general format is, 

  • Some of the relational operators are- 
    • ==,.
    • !=, 
    • <,\
    • <=,
    • >, 
    • >=, 

5. Logical Operators: These operators are used to perform “logical AND” and “logical OR” operations, i.e., the function similar to AND gate and OR gate in digital electronics. One thing to keep in mind is the second condition is not evaluated if the first one is false, i.e., it has a short-circuiting effect. Used extensively to test for several conditions for making a decision. Java also have “Logical NOT”, it returns true when condition is false and vice-versa

Conditional operators are:

  • &&, Logical AND: returns true when both conditions are true.
  • ||, Logical OR: returns true if at least one condition is true.
  • ! , Logical NOT: returns true when condition is false and vice-versa

6. Ternary operator: Ternary operator is a shorthand version of the if-else statement. It has three operands and hence the name ternary.

The general format is:

condition ? if true : if false

7. Bitwise Operators: These operators are used to perform the manipulation of individual bits of a number. They can be used with any of the integer types. They are used when performing update and query operations of the Binary indexed trees. 

  • &, Bitwise AND operator: returns bit by bit AND of input values.
  • |, Bitwise OR operator: returns bit by bit OR of input values.
  • ^, Bitwise XOR operator: returns bit by bit XOR of input values.
  • ~, Bitwise Complement Operator: This is a unary operator which returns the one’s complement representation of the input value, i.e., with all bits inverted.

8. Shift Operators: These operators are used to shift the bits of a number left or right, thereby multiplying or dividing the number by two, respectively. They can be used when we have to multiply or divide a number by two. General format- 

 number shift_op number_of_places_to_shift;
  • <<, Left shift operator: shifts the bits of the number to the left and fills 0 on voids left as a result. Similar effect as of multiplying the number with some power of two.
  • >>, Signed Right shift operator: shifts the bits of the number to the right and fills 0 on voids left as a result. The leftmost bit depends on the sign of the initial number. Similar effect as of dividing the number with some power of two.
2.Define constructor? Explain constructor overloading in java

A constructor is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. 

The constructor overloading can be defined as the concept of having more than one constructor with different parameters so that every constructor can perform a different task.


Example

  1. public class Student {  
  2. //instance variables of the class  
  3. int id;  
  4. String name;  
  5.   
  6. Student(){  
  7. System.out.println("this a default constructor");  
  8. }  
  9.   
  10. Student(int i, String n){  
  11. id = i;  
  12. name = n;  
  13. }  
  14.   
  15. public static void main(String[] args) {  
  16. //object creation  
  17. Student s = new Student();  
  18. System.out.println("\nDefault Constructor values: \n");  
  19. System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);  
  20.   
  21. System.out.println("\nParameterized Constructor values: \n");  
  22. Student student = new Student(10"David");  
  23. System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);  
  24. }  
  25. }  

Output:

this a default constructor


Default Constructor values: 


Student Id : 0
Student Name : null


Parameterized Constructor values: 


Student Id : 10
Student Name : David

3.Write a java program to print the names of students by creating a Student class. If no name is passed while creating an object of Student class, then the name should be "Unknown", otherwise the name should be equal to the String value passed while creating object of Student class.

Class student {

Private string name;

Student(string n){

name=n


System.out.println(name);

}

Student( ){

System.out.println(“unknown “);

}

Class Name{

PublicStaticVoid main(String arg()){

Student w =new student ( );

Student  e =new student (“chaduvukondifirst” );

}

}

Output

Unknown 

Chaduvukondifirst

4 .how super keyword is used

The super keyword refers to superclass (parent) objects.

It is used to call superclass methods, and to access the superclass constructor.

The most common use of the super keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.

class Animal { // Superclass (parent)
  public void animalSound() {
    System.out.println("The animal makes a sound");
  }
}

class Dog extends Animal { // Subclass (child)
  public void animalSound() {
    super.animalSound(); // Call the superclass method
    System.out.println("The dog says: bow wow");
  }
}

public class Main {
  public static void main(String args[]) {
    Animal myDog = new Dog(); // Create a Dog object
    myDog.animalSound(); // Call the method on the Dog object
  }
} 

Outputs : The animal makes a sound  The dog says: bow wow



5 .how this keyword is used 

  THEthis keyword refers to the current object in a method or constructor.

public class Main {
  int x;

  // Constructor with a parameter
  public Main(int x) {
    this.x = x;
  }

  // Call the constructor
  public static void main(String[] args) {
    Main myObj = new Main(5);
    System.out.println("Value of x = " + myObj.x);
} }output
Value of x = 5

6 .Explain Arrays class in java with example program

An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). The base value is index 0 and the difference between the two indexes is the offset.

An array can contain primitives (int, char, etc.) and object (or non-primitive) references of a class depending on the definition of the array. In the case of primitive data types, the actual values are stored in contiguous memory locations. 
 example :
class GFG
{
    public static void main (String[] args)
    {        
      // declares an Array of integers.
      int[] arr;
         
      // allocating memory for 5 integers.
      arr = new int[5];
         
      // initialize the first elements of the array
      arr[0] = 10;
         
      // initialize the second elements of the array
      arr[1] = 20;
         
      //so on...
      arr[2] = 30;
      arr[3] = 40;
      arr[4] = 50;
         
      // accessing the elements of the specified array
      for (int i = 0; i < arr.length; i++)
         System.out.println("Element at index " + i +
                                      " : "+ arr[i]);         
    }
}
7 .Explain different control statements in java with example programs

 three types of control flow statements.

  1. Decision Making statements
    • if statements
    • switch statement
  2. Loop statements
    • do while loop
    • while loop
    • for loop
    • for-each loop
  3. Jump statements
    • break statement
    • continue statement

Decision-Making statements:

As the name suggests, decision-making statements decide which statement to execute and when. Decision-making statements evaluate the Boolean expression and control the program flow depending upon the result of the condition provided. There are two types of decision-making statements in Java, i.e., If statement and switch statement.

1) If Statement:

In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted depending upon the specific condition. The condition of the If statement gives a Boolean value, either true or false. In Java, there are four types of if-statements given below.

  1. Simple if statement
  2. if-else statement
  3. if-else-if ladder
  4. Nested if-statement

Let's understand the if-statements one by one.

1) Simple if statement:

It is the most basic statement among all control flow statements in Java. It evaluates a Boolean expression and enables the program to enter a block of code if the expression evaluates to true.

Syntax of if statement is given below.

  1. if(condition) {    
  2. statement 1//executes when condition is true   
  3. }    

2) if-else statement

The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block. The else block is executed if the condition of the if-block is evaluated as false.

Syntax:

  1. if(condition) {    
  2. statement 1//executes when condition is true   
  3. }  
  4. else{  
  5. statement 2//executes when condition is false   
  6. }  

3) if-else-if ladder:

The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we can say that it is the chain of if-else statements that create a decision tree where the program may enter in the block of code where the condition is true. We can also define an else statement at the end of the chain.

Syntax of if-else-if statement is given below.

  1. if(condition 1) {    
  2. statement 1//executes when condition 1 is true   
  3. }  
  4. else if(condition 2) {  
  5. statement 2//executes when condition 2 is true   
  6. }  
  7. else {  
  8. statement 2//executes when all the conditions are false   
  9. }  

4. Nested if-statement

In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if statement.

Syntax of Nested if-statement is given below.

  1. if(condition 1) {    
  2. statement 1//executes when condition 1 is true   
  3. if(condition 2) {  
  4. statement 2//executes when condition 2 is true   
  5. }  
  6. else{  
  7. statement 2//executes when condition 2 is false   
  8. }  
  9. }  
 Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks of code called cases and a single case is executed based on the variable which is being switched. The switch statement is easier to use instead of if-else-if statements. It also enhances the readability of the program.
  1. switch (expression){  
  2.     case value1:  
  3.      statement1;  
  4.      break;  
  5.     .  
  6.     .  
  7.     .  
  8.     case valueN:  
  9.      statementN;  
  10.      break;  
  11.     default:  
  12.      default statement;  
  13. }  

Loop Statements

we need to execute the block of code repeatedly while some condition evaluates to true. However, loop statements are used to execute the set of instructions in a repeated order. The execution of the set of instructions depends upon a particular condition.

In Java, we have three types of loops that execute similarly. However, there are differences in their syntax and condition checking time.

  1. for loop
  2. while loop
  3. do-while loop

Let's understand the loop statements one by one.

for loop

In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the condition, and increment/decrement in a single line of code. We use the for loop only when we exactly know the number of times, we want to execute the block of code.

  1. for(initialization, condition, increment/decrement) {    
  2. //block of statements    
  3. }    

The flow chart for the for-loop is given below.

Control Flow in Java

for-each loop

Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-each loop, we don't need to update the loop variable. The syntax to use the for-each loop in java is given below.

  1. for(data_type var : array_name/collection_name){    
  2. //statements    
  3. }    

while loop

The while loop is also used to iterate over the number of statements multiple times. However, if we don't know the number of iterations in advance, it is recommended to use a while loop. Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop statement in while loop.

It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the condition is true, then the loop body will be executed; otherwise, the statements after the loop will be executed.

The syntax of the while loop is given below.

  1. while(condition){    
  2. //looping statements    
  3. }    

The flow chart for the while loop is given in the following image.

Control Flow in Java

do-while loop

The do-while loop checks the condition at the end of the loop after executing the loop statements. When the number of iteration is not known and we have to execute the loop at least once, we can use do-while loop.

It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax of the do-while loop is given below.

  1. do     
  2. {    
  3. //statements    
  4. while (condition);    

8 .Explain method overloading in java with example program

Method Overloading 

If a class has multiple methods having same name but different in parameters, it is known as Method Overloading
  1. class Adder{  
  2. static int add(int a,int b){return a+b;}  
  3. static int add(int a,int b,int c){return a+b+c;}  
  4. }  
  5. class TestOverloading1{  
  6. public static void main(String[] args){  
  7. System.out.println(Adder.add(11,11));  
  8. System.out.println(Adder.add(11,11,11));  
  9. }}  
output:
22
33

9.Create a class named 'PrintNumber' to print various numbers of different datatypes by creating different methods with the same name 'printdata' having a parameter for each datatype 

class Number{

 int printdata(int a){return a;}  

 float printdata(float a){return a;}  

 double printdata(double a){return a;} 

}


public class PrintNumber

{

       int a;

  float b;

  double c;

  public static void main(String[] args) {

   Number c1= new  Number();

         System.out.println(c1.printdata(5));

        System.out.println(c1.printdata(6.00));

   System.out.println(c1.printdata(787787));  

  }

}

Ouput :

6.00

7878787

10 .Explain types of inheritances in java

Inheritance is a mechanism of driving a new class from an existing class. The existing (old) class is known as base class or super class or parent class. The new class is known as a derived class or sub class or child class. It allows us to use the properties and behavior of one class (parent) in another class (child).

Types of Inheritance

  • Single Inheritance

In single inheritance, a sub-class is derived from only one super class. It inherits the properties and behavior of a single-parent class. Sometimes it is also known as simple inheritance.

Types of Inheritance in Java

.

Executive.java

  1. class Employee  
  2. {    
  3. float salary=34534*12;    
  4. }    
  5. public class Executive extends Employee  
  6. {   
  7. float bonus=3000*6;  
  8. public static void main(String args[])  
  9. {  
  10. Executive obj=new Executive();   
  11. System.out.println("Total salary credited: "+obj.salary);    
  12. System.out.println("Bonus of six months: "+obj.bonus);   
  13. }    
  14. }   

Output:

Total salary credited: 414408.0
Bonus of six months: 18000.0
  • Multi-level Inheritance

In multi-level inheritance, a class is derived from a class which is also derived from another class is called multi-level inheritance. In simple words, we can say that a class that has more than one parent class is called multi-level inheritance. Note that the classes must be at different levels. Hence, there exists a single base class and single derived class but multiple intermediate base classes.

Types of Inheritance in Java

MultilevelInheritanceExample.java

  1. //super class  
  2. class Student  
  3. {  
  4. int reg_no;  
  5. void getNo(int no)  
  6. {  
  7. reg_no=no;  
  8. }  
  9. void putNo()  
  10. {  
  11. System.out.println("registration number= "+reg_no);  
  12. }  
  13. }  
  14. //intermediate sub class  
  15. class Marks extends Student  
  16. {  
  17. float marks;  
  18. void getMarks(float m)  
  19. {  
  20. marks=m;  
  21. }  
  22. void putMarks()  
  23. {  
  24. System.out.println("marks= "+marks);  
  25. }  
  26. }  
  27. //derived class  
  28. class Sports extends Marks  
  29. {  
  30. float score;  
  31. void getScore(float scr)  
  32. {  
  33. score=scr;  
  34. }  
  35. void putScore()  
  36. {  
  37. System.out.println("score= "+score);  
  38. }  
  39. }  
  40. public class MultilevelInheritanceExample   
  41. {  
  42. public static void main(String args[])  
  43. {  
  44. Sports ob=new Sports();  
  45. ob.getNo(0987);  
  46. ob.putNo();  
  47. ob.getMarks(78);  
  48. ob.putMarks();  
  49. ob.getScore(68.7);  
  50. ob.putScore();  
  51. }  
  52. }  

Output:

registration number= 0987
marks= 78.0
score= 68.7


  • Hierarchical Inheritance

Hierarchical Inheritance

If a number of classes are derived from a single base class, it is called hierarchical inheritance.

Types of Inheritance in Java


HierarchicalInheritanceExample.java

  1. //parent class  
  2. class Student  
  3. {  
  4. public void methodStudent()  
  5. {  
  6. System.out.println("The method of the class Student invoked.");  
  7. }  
  8. }  
  9. class Science extends Student  
  10. {  
  11. public void methodScience()  
  12. {  
  13. System.out.println("The method of the class Science invoked.");  
  14. }  
  15. }  
  16. class Commerce extends Student  
  17. {  
  18. public void methodCommerce()  
  19. {  
  20. System.out.println("The method of the class Commerce invoked.");  
  21. }  
  22. }  
  23. class Arts extends Student  
  24. {  
  25. public void methodArts()  
  26. {  
  27. System.out.println("The method of the class Arts invoked.");  
  28. }  
  29. }  
  30. public class HierarchicalInheritanceExample  
  31. {  
  32. public static void main(String args[])  
  33. {  
  34. Science sci = new Science();  
  35. Commerce comm = new Commerce();  
  36. Arts art = new Arts();  
  37. //all the sub classes can access the method of super class  
  38. sci.methodStudent();  
  39. comm.methodStudent();  
  40. art.methodStudent();  
  41. }  
  42. }   

Output:

The method of the class Student invoked.
The method of the class Student invoked.
The method of the class Student invoked.
  • Hybrid Inheritance

Hybrid Inheritance

Hybrid means consist of more than one. Hybrid inheritance is the combination of two or more types of inheritance.

Types of Inheritance in Java


Daughter.java

  1. //parent class  
  2. class GrandFather  
  3. {  
  4. public void show()  
  5. {  
  6. System.out.println("I am grandfather.");  
  7. }  
  8. }  
  9. //inherits GrandFather properties  
  10. class Father extends GrandFather  
  11. {  
  12. public void show()  
  13. {  
  14. System.out.println("I am father.");  
  15. }  
  16. }  
  17. //inherits Father properties  
  18. class Son extends Father  
  19. {  
  20. public void show()  
  21. {  
  22. System.out.println("I am son.");  
  23. }  
  24. }  
  25. //inherits Father properties  
  26. public class Daughter extends Father  
  27. {  
  28. public void show()  
  29. {  
  30. System.out.println("I am a daughter.");  
  31. }  
  32. public static void main(String args[])  
  33. {  
  34. Daughter obj = new Daughter();  
  35. obj.show();  
  36. }  
  37. }  

Output:

I am daughter.

Previous Post Next Post