Core Java

Download as pdf or txt
Download as pdf or txt
You are on page 1of 54

INDEX

S.NO CONTENT PG.NO


1. BASICS/VARIABLES/METHODS 1-7

2. CLASSES & OBJECTS 9-13

3. BLOCKS 14-16

4. CONSTRUCTORS 17-19

5. METHOD OVERLOADING 20-21

6. METHOD OVERRIDING 22-24

7. INHERITANCE 25-30

8. PACKAGES 31-33

9. ABSTRACT METHOD & ABSTRACT CLASS 34-36

10. INTERFACE 37-40

11. TYPECASTING 41-45

12. JAVA BEAN CLASS 46

13. PRIVATE CONSTRUCTOR & SINGLETON CLASS 47-48

14. OBJECT CLASS & ITS METHODS

15. STRING CLASS & ITS METHODS

16. EXCEPTION HANDLING

17. COLLECTION FRAMEWORK LIBRARY

18. THREADS

19. THREAD CLASS


Page |1

BASICS/VARIABLES/METHODS

1.what is JDK /JDK /JVM?

(i). JDK (Java Development kit):


It is responsible for providing all the necessary components that are required to compile an executed
a java program.

(ii). JRE (Java Runtime Environment):


It is responsible for providing all the necessary environment to the JVM so that it can perform its task
without being disturbed.

(iii). JVM (Java Virtual Machine):


It will perform the task like a machine without having any physical existence. The task of the machine
is to process Java executable file to the processor because it cannot be given directly to the processor.

2. What is byte code file?


The File generated after successful compilation of a java source file called as byte code file or class file
or executable file.

3. What is platform independent?


The executable file or bytecode file which is generated after successful compilation in one operating
system can run in another operating system without recompiling is known as platform independent.

4.Difference between C and Java?

C JAVA

1. It is Platform Dependent. 1. It is Platform Independent.


2.It has Pointers. 2.Pointer concept was eliminated.
3.It is Procedure Oriented Language. 3.It is Object Oriented Language.
4.It has less inbuilt libraries. 4.It is rich in libraries.
5.It is not Simple and Secure. 5.It is Simple and Secure.

5.What is WORA Principle?


 In Java the execute file or byte code file or class file which is generated after successful full
compilation can be executed on any operating system all we need to have been the JVM. This
property of a java executable file to be generated only once and to be executed on any platform for
any number of times is known as WORA Principle.
 WORA Stands for WRITE ONCE RUN ANYWHERE.

6.Define
a) KEYWORDS:
 Keywords are set of reserved words or Predefined words for which already some meaning is
defined by the java developers.
 In java there are 52 keywords.
 Every keyword must be represented in lower case.
Ex: class, public, void etc……………
b) IDENTIFIERS:
 Identifiers are used to identify the elements of java (class & method).
 In other words, the names that we give to a class or a method in order to identify them
uniquely are known as identifiers.
Page |2

c) VARIABLES:
 Variables are identifiers in which we store some value.
 The type of value and the length of value to be stored under a variable will be decided by
datatype.
 Datatypes will be used along the variable during variable declaration process.

d) DATATYPES:
 In Java every datatype is the keyword.
 In boolean variable we can store true/false not 1/0.
 In Java String is not a datatype rather it is a Predefined class which is available in inbuilt
library folder.

Datatypes is Two types:

Datatypes

Primitive Datatype Non- Primitive Datatype

Class type
Numeric Datatype Non-numeric Datatype Interface type

Char – 2 bytes
Boolean – 1 bit

Floating Datatype Non-Floating Datatype

Float – 4 bytes Byte – 1 byte


Double – 8 bytes Short – 2 bytes
Int – 4 bytes
Long – 8 bytes

7. What happens if the variable is final?

We can’t reassign final variables. Because declare as final.

8. Can we reassign final variables?

No.

9.What is methods? Its advantages.


Methods are set of written by the programming in order to person some specific work.

Advantages of methods:
a) Code reusability
b) We can achieve Modularity (Structure way of Programming)
Page |3

Syntax: <Access modifier> <modifier> return type method name(arg)


Or
Access specifier
{ static void Any name Ex:
------ (task) abstract int Public static void m1()
} final double
{
public synchronize String
protected | Boolean -------;
private | char }
default | |

Methods have 4 (types):


Type 1: Passing nothing to a method and returning nothing from the method.

Type 2: Passing some value to a method and returning nothing from the method.

Type 3: Passing nothing to a method and returning some value from the method.

(i). whenever a method wants to something back to caller it will make use of return keyword.

(ii). If a method returning some value when the return type of the method will change based on that type of
value the method is returning.

Type 4: Passing values to a method and returns some value from the method.

10. Writing methods by passing/returning arguments from/to methods

Public void int m1(double d)


{
return 10;
}

11. Can we use local variable without assigning a value?

No, it will show Compile Time Error.

Operators: 6 types
1. Arithmetic Operator : + , - , *, / , %
2. Relational Operator : > ,< , >= ,<= , == , !=
3. Logical Operator : && , ||
4. Bitwise Operator : %,|
5. Unary Operator : ++ (increment) ,--(decrement)
6. Shift Operator : >> (right shift) , << (left shift)
Page |4

Control Statements:

Control Statements are used to Control the flow of execution of the program.

Control Statements

Branching Looping
If for
If – else while
Else – if Ladder do while
Nested if
switch

Branching: syntax

(I) If Statement: - if (condition)


{
----------(it will execute when the condition is true)
}

(ii) If – else Statement: - if (condition)


{
----------(it will execute when the condition is true)
}
else
{
----------(it will execute when the condition is true)
}

(iii) Else – if Ladder Statement: -

if (condition)
{
----------
}
else if ( cond ) * out of all blocks any one will execute depending
{ upon the condition.
----------
} * if all the condition fails then else block will be
else if (cond) execution.
{
----------
}
else
{
----------
}
Page |5

(iv) Nested If Statement: -

if (condition)
{
if (condition)
{
------- (it will execute when both outer if and inner if the condition is true)
}
else
{
-------(it will execute outer if condition is true but inner if the
condition is false)
}
}
else
{
----------(it will execute outer if condition is false)
}

(v) Switch Statement: -


Switch (choice)
{
Case 1: --------------
break;
Case 2: --------------
break;
Switch block
Case 3: --------------
break;
|
|
|
default: System.out.println(“Invalid choice);
}

Looping:
If we want to perform the similar task repeatedly then we can make use of any one of the looping
statements.

1. For loop: (Syntax) 2


1 5
For (initialisation; condition; increment (i++) / decrement (i--))
{
--------------; 3 4
}
2. While loop: (syntax)
While (condition)
{
------------;
}
3. Do While loop: (syntax)
do
{
------------;
}
While (condition)
Page |6

Difference between while loop and do while loop.

While loop Do while loop


1.It is also known as Entry Control Loop. 1.It is also known as Exit Control Loop.

2.Here the first condition will be check and 2.Here the first do while loop block will be
then the while loop block will be executed. executed and then condition will be checked.

3.If the condition is false the loop block will 3.The loop bloc will be executed at least one
not get executed even one’s. time even if the initial condition is false.

Ex: int i=7; Ex: int i=7;


While (1<=5) do
{ {
Sop (“Hello World”); Sop (“Hello World”);
} }
While (1<=5)

Structure way of Programming:


Writing the code, one’s and executing the same piece of code multiple times as per the customer the
requirement is known as Structured way of Programming.

As per the IT Standard Structure way of programming is recommended.

Unstructured way of Programming:


Writing the same piece of code multiple times with in the main method as per the customer requirement
is known as Unstructured way of Programming.

According to the IT Standard unstructured way of programming is not recommended.

Taking input from the user:


1. import java. util.Scanner;
2. Scanner sc =new Scanner (System.in);
3. Int a = sc.next Int ();
double b = sc.next Double ();
float c = sc.next Float();
boolean d = sc.next Boolean ();
char e = sc.next().char At(i);
String f= sc.next(); (It will consider space as end of the String)
String g= sc.next Line(); (It will Consider the enter button as end of the String)
Page |7

Basics of String:
 In java String is a pre-defined class which available in the inbuilt library folder.
 Within the inbuilt library folder, the string class in present in java. lang package.
 The String class contains lots of predefined methods which are used to perform operations on string
value.

*** In built methods of String class:


1. int length ();
It is inbuilt method of string class which will return the total no. of characters for a given string value.
Ex: String s1 =” Hello”;
Int len = s1. length ()
System.out.println(s1. length);

2. char char At (int position)


It is inbuilt method of string class which will return the char at the specified the index value.
Ex: String s1 =” Hello”;
char x = s1. char at (0)
System.out.println (x); // H
System.out.println (s1. char At (1)); // E

3. Boolean equals (String s)


It is inbuilt method of string class which is used to compare the content of two String values. If the
content is same then this method will write true else it will write false.
Ex: String s1 =” Hello”;
String s2 =” WELCOME”;
String s3 =” HELLO”;
Boolean x =s1.equals(s2);
System.out.println(x); // False
System.out.println(s1. equals(s2); // False
System.out.println(s1. equals(s3); // True
Page |8
Page |9

OOPS INTERVIEW QUESTIONS


CLASSES & OBJECTS
1.What is Instantiation?
The Process of creating an object or instance of a class is known as instantiation.
Ex: new Demo ();
new Sample ();

2.What is Reference Variable?


It is also an identifier which is used to refer to the object present in the heap memory.
Ex: Sample s1; // s1 is reference variable of sample class.
Demo d1; // d1 is reference variable of sample class.

3.Diff b/w Variable and reference Variable?


In a Variable we can store primitive type values where as to a reference we can assign only object.
Ex: int a; // a is variable
Demo d1; // d1 is reference variable a = 100;
boolean b; // b is Variable d1 = new Demo ();
Sample s1; // s1 is reference variable b = false;
s1 = new Sample ();

4.What is a Class?
A class is the java definition block or a java blue print which will contains different states and behaviour.
 States refers to data members EX:
 Behaviour refers to member function.
Class A
{
Static int x = 10, y = 20;
Public static void m1()
{

Public static void m1()


{

 Class template: Example:

class Demo
Syntax:
{
Int x =100;
class CN Static double y=10.12;
{ public static void m1 ()
variable / data members {
Int a = 10;
static non-static --------
--------
}
public void m1 ()
methods/ member function
{
Int b = 20;
static non-static --------
} --------
}
P a g e | 10

5.What is an object?
 An object is the real-world entity which will have its own states & behaviour.
 States refers to Characteristics and Behaviour refers to functionality.
Ex: object Student
X=10
State / characteristics: height, weight, id, name ……
Behaviour/functionality: write, read, jump, run…. Y=20
M1()
M2()
Object w.r.to java:
 An object is the real-world entity which will have its own states & behaviour.
 States refers to variable or data members.
 Behaviour refers to methods or member function.

Object Initialisation:
 The process of initializing the non-static variables present inside an object is known as object
initialization.
 According to the IT Standard the object initialization should not take place in the main method, if we
want to initialize the non-static variables, we will make use of
I. Non-static block
II. Constructor

6.What is byte code file? How many byte code files will be generated after compiling source file?
 The File generated after successful compilation of a java source file called as byte code file or class file
or executable file.

 A java source file can have any no. of classes in it. The no. of executable file or byte code file or class
file to be generated after successful compilation will be equal to the no.of classes present in the
source file and these byte code files will have some name as that of the class name out of all the
executable file we can pass one at a time to the JVM for the execution.

class A Output 1
A.CLASS
{
--------
} B.CLASS processor Output 2
class B JAVA C
{
C.CLASS Output 3
--------
}

7.What will be the name of byte code file?


 The name of the byte code file will be same as class name

8.Command used to compile & run java program


 Compile - javac filename.java
 Run- java classname
P a g e | 11

9.Can I declare local variable as static?

 No, because local variables are neither static nor non-static

10.Does java allows global variable?


 No java does not allow global variables

11.How many types of variables do java supports?

 Java support 3 types of variables they are local, static and non-static

12.How to access static & non static members explain with an example.
(i). Access static members:

 To access static properties of one class into another class we make use of the below syntax.

classname. static members name;

 During the class loading process that means when we pass a class file to the JVM for execution all the
static properties will be loading into the class memory or class area. which will have the same name as
that of the class name. This is the reason we access static properties of one class into class by using
class name.

Ex: Class Demo


{
Static int a=10;
public static void x1()
{
-----
-----
}
Class sample a=10
{ x1()
Static int a=20;
Public static void x2()
{ b=20
----- x2()
-----
}
Class MainClass Main ()
{
public static void main (String [] args)
{ class memory or class area
System.out.println (Demo.a);
System.out.println(sample.b);
Demo.x1();
Sample.x2();
}
}
P a g e | 12

(ii). Non-static members:

 To access non-static properties of one class into another class the below steps must be follow.
 We need to create an object or instance of the class whose non-static properties should be accessed
by using the below syntax.

new classname ();


Ex: new A () ; // class A object is created.
new Sample (); // class Sample object is created.

 Create a reference variable in order to refers to the object present inside the heap memory or heap
area.
classname ref_varname;

Ex: A a1; // a1 is reference variable of class A


Sample s1; // s1 is a reference variable

 We can combine step 1 and step in a single statement as shown below

classname ref_varname = new classname ();

Reference variable keyword constructor

Object creation
P a g e | 13

13.When to declare data member as static & non static.


 The properties are details which are common from everyone will be declared as static.
Ex: college name
company name
institute name
college address etc……

 The individual properties are the details that differ from person to person will be declared as non-
static.
Ex: id
Name
Marks
Salary etc
Example:

class Faculty
{
int id;
String name; output:
double sal;
static String cname;
} Id Name salary com_name
class MainOfFaculty 111 veerendra 500.0 JSP
{ 112 sai 890.0 JSP
public static void main (String [] args)
{
Faculty.cname="JSP";
Faculty veeru=new Faculty ();
veeru.id=111;
veeru.name="veerendra";
veeru.sal=500.00;

Faculty sai=new Faculty ();


sai.id=112;
sai.name="sai";
sai.sal=890.00;

System.out.println("Id\t\tName\t\tsalary\t\tcom_name");
System.out.println("-------------------------------------------------------------");
System.out.println(veeru.id+"\t\t"+veeru.name+"\t"+veeru.sal+"\t\t"+Faculty.cna
me);
System.out.println(sai.id+"\t\t"+sai.name+"\t\t"+sai.sal+"\t\t"+Faculty.cname);
}
}
P a g e | 14

BLOCKS
1. What is block and how many types of blocks available?
Blocks are set of instructions written by the programmer in order to perform some special tasks.

Static

Types of Blocks: Blocks

Non-static

2.Difference between Methods & Blocks?

METHODS BLOCKS
1. It will have some name. 1. It will not have any name.
2. It will have modifier and return type. 2. It will allow modifier but it will not return type.
3. It will neither except nor return values.
3. It will have except and return values. 4.Ther are used for Special purpose.
4. It is used for writing logics by the
Programmer. 5. It will automatically execute
5. It will execute only when it is called explicitly
by the user.

3.When static block will execute?

 The blocks which one declared using static keyword are known as static block.
 The static block will be executed automatically during class loading time that means when we pass
the class file to the JVM for execution it will first check if the class contains any static block. If present
it will execute and then it will execute the main method.
 A java class can have multiple static blocks in it, they will be executed in the same order in which they
are defined during class loading time.

Ex: class StaticBlock


{
Static Output:
{ O
System.out.println("static block 1 executed"); // 1
} static block 1 executed
public static void main (String [] args) static block 2 executed
{ HELLO MAIN
System.out.println("HELLO MAIN"); // 3
BYE MAIN
System.out.println("BYE MAIN"); // 4
}
static
{
System.out.println("static block 2 executed"); // 2
}
}
P a g e | 15

4.When non-static block will execute?


 The blocks which are declared without using keyword are known as non-static blocks.
 The non-static block will be executed automatically when we create an object or instance of a class.
 Whenever the object creation statement is encountered by the JVM the below steps will be followed.
 A java class can have multiple non-static blocks in it they will be executed in the same order in which
they are defined during object creation.

Step 1: An object will be created in the heap memory.


Step 2: All the non-static properties of the class whose object is created will be loaded into the object.
Step 3: Non- static block will be executed if it is present inside the class whose object is created.
Step 4: Refer the object with the help of reference variable in order to access the properties present insided.

Ex:
class NonStaticBlock
{
{
System.out.println("non-static block 1 executed"); // 2 Output:
}
public static void main (String [] args)
{ HELLO MAIN
System.out.println("HELLO MAIN"); // 1 non-static block 1 executed
new NonStaticBlock (); // object creation non-static block 2 executed
System.out.println("BYE MAIN"); // 5 non-static block 3 executed
} BYE MAIN
{
System.out.println("static block 2 executed"); // 3
}
{
System.out.println("static block 3 executed"); // 4
}
}

5.How many times static block will execute and non-static block will execute?
 A java class can have both static block and non-static block together.
 The static block will be executed only once during class loading time.
 Non-static block will be executed every time when we create an object of a class.

Ex:
class Demo
{
static Output:
{
System.out.println("static block executed");
static block executed
}
HELLO MAIN
{
non-static block executed
System.out.println("non-static block executed");
non-static block executed
}
non-static block executed
public static void main (String [] args)
BYE MAIN
{
System.out.println("HELLO MAIN");
new Demo (); //object created
new Demo (); //object created
new Demo (); //object created
System.out.println("BYE MAIN");
}
}
P a g e | 16

6. Can I initialize static data member inside non-static block?


Yes, when we create an object the static data members will load class memory we can access.

7. Can I initialize non-static member inside static block?


No, because static block will be executed class loading time and we will not be able to create an object of
that class.
P a g e | 17

CONSTR`UCTORS
1.What is a constructor? & Why is it used for?
 Constructors are special method are member function which will have the same name as that of class
name.
 Constructors are used to achieve object initialisation that means they are used to initialise the non-
static variable.
 Constructors will not have any Return type.
 Constructors will not have any Modifier.
 Constructors are used instead of non-static blocks to achieve object initialisation.
 Constructors will be executed automatically when we create an object

Ex: class Constructor


{
public Constructor ()
{
System.out.println("Hello constructor"); Output:
}
} Main Starts
class MainOfConstructor Hello constructor
{ Hello constructor
public static void main (String [] args) Main ends
{
System.out.println("Main Starts");
new Constructor ();
new Constructor ();
System.out.println("Main ends");
}
}

2.When constructors will be executed? Explain


Constructors will be executed automatically when we create an object

Syntax: < Access modifier > class name ()


{
--------
-------- Object initialisation, statement
}

3. When to go for argument constructor? Explain with an example.

If we want to initialize some non-static variables in a class, we will go for argumented constructor.

class A class Main


{ {
int x; public static void (String[] args)
public A (int x) {
{ A a=new A (10);
this.x=x; System.out.println(a.x);
} }
} }
P a g e | 18

4.WAP to demonstrate constructor overloading & what are its advantages.


 The process of having multiple constructors with in the same class which differ argument or
parameter or signature is known as constructor overloading.

The argument of the constructors should differ one of the following:


a. Type of the argument must be different
b. order of occurrence of the argument should be different.
c. Length of the argument must be different

Ex: class A
{
public A ()
{
System.out.println("no arg");
}
public A (int x)
{
System.out.println(x);
} Output:
public A (char ch, int a)
{
System.out.println(ch); 100
System.out.println(a); no arg
} x
public A (int x,char ch) 100
{ 100
System.out.println(x); A
System.out.println(ch);
}
}
class MainOfA
{
public static void main (String [] args)
{
new A (100);
new A ();
new A('x',100);
new A (100,'A');
}
}
P a g e | 19

5.Does the constructor allow return type? If we give what happens


 No, constructor does not allow return type
 If we give return type to a constructor then it will become a method

6.Can the constructor be static?


 No, constructor cannot be static if we define constructor as static, it will give a compile time error

7. Can the constructor be final?


 No, because we use constructor for object initialisation.

8.What is the access modifiers allowed for constructor? (Public, private, protected, default)
 All public, protected, private and default access modifiers are allowed for constructor.

9.What happens when we create an object explain series of steps


 Whenever the object creation class name in encountered by the JVM the below steps will be followed

Step 1: An empty object will be created in the heap memory or heap area.
Step 2: All the non-static properties will be loaded into the object.
Step 3: non-static block will be executed (if present)
Step 4: Constructor will be executed
Step 5: Create a reference variable in order to access the non-static properties present inside the object.
P a g e | 20

METHOD OVERLOADING

1.What is method overloading explain with an example?


The process of having multiple methods with same name which differ in their argument or parameter
or signature with in a class is known as method overloading.
The arguments of the methods should differ in either one of the three ways:
a. Length of the argument should be different
b. Type of the argument should be different
c. order of occurrence of the argument should or will be different.

2.Can we overload static methods? WAP to overload main method.


 Yes, it is possible to overload static method.

 Overloading ‘main’ method means we have multiple method with the name “main” which differ in
their arguments with in a class which will be treated like any other user defined static method. The
JVM is concerned about the main method which is in the following format.

public static void main (String [] args)

If the JVM does not find the main method in the above format then it will throw run time error.

Ex:

class Sample
{
public static void main ()
{ Output:
System.out.println("Hi no arg");
}
public static void main (double a, float b)
{ Hi no arg
System.out.println("hi double and float arg "+a+" "+b); Hi double and float arg 12.12 10.12
} Hi boolean and char arg true, T
public static void main (boolean x, char y)
{
System.out.println("Hi boolean and char arg"+x+" "+y);
}
}
class MainOfSample
{
public static void main (String [] args)
{
Sample.main();
Sample.main(12.12, 10.12f);
Sample.main(true,'T');
}
}
P a g e | 21

3. Explain how to pass arguments to main method explain.


We can pass the arguments to the main method from the command prompt. Any arguments passed from
the command prompt will be internally treated as String only. Hence main method always accepts String array.

Java program1
“10” “20” “30” “40”

“10.11 “ “11.12 “ “12.22”

“a” “e“ “I” “o” “u”

4.WAP to overload non-static methods.

class Demo
{
public void xyz ()
{ Output:
System.out.println("In no arg of xyz");
}
public void xyz (int x)
{
In no arg of xyz
System.out.println("In int arg of xyz"+x);
In int arg of xyz 100
}
In float and String arg of xyz 12.12, Hello World
public void xyz (char a, boolean b)
In char and boolean arg of xyz ‘A’, false
{
System.out.println("In char and boolean arg of xyz"+a+" "+b);
}
public void xyz (float f, String s)
{
System.out.println("In float and String arg of xyz"+f+" "+s);
}
}
class MainOfDemo1
{
public static void main (String [] args)
{
Demo1 d1=new Demo1();
d1.xyz ();
d1.xyz (100);
d1.xyz (12.12f,"Hello World");
d1.xyz ('A’, false);
}
}

5.What are the advantages of method overloading?


 If we want to perform one task in multiple ways we will go for overloading.
 By implementing method overloading concept we can reduce user complexity.
P a g e | 22

Method Overriding

1. What is overriding? Justify how overriding is runtime polymorphism

Changing the task itself is known as overriding.

2. Difference between overloading & overriding

Method overloading Method overriding


1.If we want to perform one task in multiple ways 1.If we want to change the task itself, we will go for
we will go for overloading. overriding.

2.Multiple methods with same name different 2.changing superclass method implementation is
signature is known as overloading. subclass is known as overloading.

3.IS a relationship is not Mandatory. 3.IS a relationship is Mandatory.

4.Constructors can be Overloaded. 4.Constructors cannot be overridden because they


will not get inherited.
5.Static methods can be overloaded.
5.Static methods cannot be overridden.
6.Final methods can be overloaded.
6.Final methods cannot be overridden.

3. Which methods cannot be overridden?

Private method and final methods.

4. Can we override final methods?

No, can’t override a final method of super class in subclass.

5. Can we override static methods?

Override concept is applicable only for object level methods that means in java static methods cannot
be overridden with respect to static method the same concept is known as method hiding.

6. Can we change the access modifier while overriding method?

 while overriding the superclass method in the subclass we can either retained the same visibility of
the method or we can increase it.
 But we cannot decrease the visibility while over hiding.
P a g e | 23

7. Can we change the return type while overriding method?

while overriding the super class in the subclass we cannot change the return type of the method (with
respect to primitive type).

class A
{
public void m1()
{
---
---
}
class B extends A
{
public int m1() // CTE, can’t change return type
{ while overriding.
--
--
}
}

8. Can we override abstract method?

Yes.

9. Can we override concrete method as abstract? Justify its advantages.

No.

10. What is polymorphism? Explain its types with example

 An object showing different states in its different stages of life is known as polymorphism.
 Polymorphism is classified into 2 types.

1.Static polymorphism:

 It is also known as compile time polymorphism.


 In this type of polymorphism binding of method declaration with the method definition is done by the
compiler during compilation time based of the signature and hence the name compile time
polymorphism.

Ex: overloading , method hiding

Constructor Method
Overloading Overloading

2.Dynamic Polymorphism:

 It is also known as Run time polymorphism.


 In this type of polymorphism binding of method declaration with the method definition is done by the
JVM during Run time based on the run time object and hence the name
Run time polymorphism.

Ex: over hiding.


P a g e | 24

11. When to go for overriding? Explain

When we want to change the implementation of a method, we go for overriding.

12. Can we override constructor? Why?

No, because the superclass constructor will not be inherited in its subclass.

13. Difference between compile time & run time polymorphism

Compile time polymorphism Run time polymorphism


1. It is Static polymorphism. 1. It is Dynamic Polymorphism.
2.It is also known as compile time polymorphism. 2.It is also known as Run time polymorphism.
3. In this type of polymorphism binding of method 3. In this type of polymorphism binding of method
declaration with the method definition is done by declaration with the method definition is done by
the compiler during compilation time based of the the JVM during Run time based on the run time
signature. object.
4.Hence the name compile time polymorphism. 4.Hence the name Run time polymorphism.

Ex: overloading, method hiding Ex: over hiding.

14. While overriding, why co-variant type changes allowed & why not contra
variant?
P a g e | 25

INHERITANCE
1.What is inheritance & what are its advantages
 The process of deriving one class property to another class is known as Inheritance
 The class from which we derived the properties is known as present Parent class or Super class or
Base class.
 The class two which we derive the properties is known as child class or sub class or derived class.
 In java inheritance is also known as IS-A Relationship.
 In order to inherit the properties are class into another class into another class we will make use of
“extends “keyword.

Syntax:
Class A class B extends A
{ { sub class Parent class
-------- child class Super class
-------- derived class Base class
} }

Advantages:

a. Code Reusability
b. To achieve dynamic polymorphism.

2.Explain types of inheritance.


1. Single level inheritance
2. Multi-level inheritance
3. Hierarchical inheritance
4. Multiple inheritance
5. Hybrid inheritance

Single level inheritance:


The inheritance in which we will have one super class and single sub class is known as single level
inheritance.

Multi-level inheritance:
The inheritance in which a super class will have a sub class and that sub class will further have another
sub class and so on is known as multi-level inheritance.

Hierarchical inheritance:
 The inheritance in which one super class will have multiple sub classes is known as Hierarchical
inheritance.
 It is the most widely used inheritance in the industry.

Multiple inheritance:
 A sub class having more than one super class is known as multiple inheritance.
 In java multiple inheritance not allowed.

Hybrid inheritance:
Combination of two or more type of inheritance is known as hybrid inheritance.
P a g e | 26

3.Explain why multiple inheritance is not allowed in java?


 In java whenever we create object of a subclass its super class constructor has to be called from the
subclass is order to complete constructor chaining process.
 In multiple inheritance one subclass will be multiple super classes, when we create the object of the
subclass the JVM will get confused to execute with super class constructor first and due to this
confusion, the constructor chaining will remain incomplete. This is the reason multiple inheritance is
not allowed in java.

Object

A B
A A A

B C
B B C
C

4.What is “this “keyword? Why is it used for? Explain with an example


 It is a keyword which is used to refers to the current object.
 An object because of which something is called as current object.
 “This” keyword will refer to only one object at a time.
 It is required is order to differentiate between the local variables and non-static variables.
 It is optional to use this keyword when the local variable names and the non-static variables names
are different.
 It is Mandatory to use this keyword when the local variable names and the non-static variables
names are same.
 Since the keyword is associated with the object it can be use only inside a constructor or non-static
methods.

EX: class A
{
int x; Output:
int y;
public A (int a,int b) 10
{ 20
System.out.println(a); 0
System.out.println(b); 0
System.out.println(x); 100
System.out.println(y); 200
} 0
} 0
class BOfMain
{
public static void main (String [] args)
{
A a1=new A (10,20);
A a2=new A (100,200);
}
}
P a g e | 27

5.What is “super” keyword? Why is it used for? Explain with an example


 It is a keyword which is used to access this super class properties in the sub class.
 Usually, we use super keyword in order to differentiate between the sub class properties and super
class properties.
 Using super keyword, we can access the properties of immediate super class only.
 It is optional to use super keyword when the subclass member names and super class member names
are different.
 It is mandatory to use super keyword when the subclass member names and super class member
names are same.
 Just like this keyword even super keyword is also associated with the object that is why super
keyword can be used only inside a constructor or non-static method.

Ex:
class A
{
int x=100;
int y=200;
} Output:
class B extends A
{
int a=10; 1
int b=20; 2
100
public B () 200
{ 100
int x=1; 200
int y=2;
System.out.println(x);
System.out.println(y);
System.out.println(this.x);
System.out.println(this. y);
System.out.println(super.x);
System.out.println(super. y);
}
}
class COfMain
{
public static void main (String [] args)
{
new B ();
}
}

6. What is the first statement inside default constructor?

It will call its super class constructor. If is called constructor chaining process.

7.Is Object class a final? Justify.


No, object class is not a final class as object class is the super most class for any Java class and the
properties of object class are inherited to its sub class
P a g e | 28

8.Explain constructor calling with an example. What are its advantages?


 The process of calling one constructor from another constructor with in the same class is known as
constructor calling.
 We can perform constructor calling by making use of “this ()”.
 “This ()” can be used only inside a constructor and it must always be the first statement of
constructor body.

class A
Ex: {
public A ()
{
System.out.println("no arg");
Output:
}
public A (int x)
{
this (); no arg
System.out.println(x); 100
}
public A (char ch, String s) x
{
this (100); HELLO
System.out.println(ch);
System.out.println(s);
}
}
class BofMain
{
public static void main (String [] args)
{
new A('x',"HELLO");
}
}

9.What happens if a class is declared as final? Example for final class


If a class is declared as final then the properties of that class cannot be inherited

Ex:
final class A
{
------
}
class B extends A
{
-------- Output:
}
class main Compile time error can’t inherit final class
{
public static void main (String [ ] args)
{
----------
}
}
P a g e | 29

10.Explain constructor chaining with an example? Why constructor chaining required?


 The process of calling super class constructor from the subclass is known as constructor chaining.
 We can perform the constructor chaining process with the help of “super ()”.
 “Super ()” method can be used only inside a constructor and it must always be the first statement of
constructor body.
 To perform constructor chaining is a relationship is mandatory.

class A
Ex: {
public A ()
{
System.out.println("YO A");
}
}
class B extends A
{
public B (int x)
{
super (); Output:
System.out.println("YO B"+x);
}
} Main Starts
class C extends B YO A
{ YO B100
public C (boolean a) YO Cfalse
{ Main Ends
super (100);
System.out.println("YO C"+a);
}
}
class MainOfD
{
public static void main (String [] args)
{
System.out.println("Main Starts");
new C(false);
System.out.println("Main Ends");
}
}

11. Explain what happens when we instantiate subclass.


When we can create an object of a subclass then that object will contain the properties of its class
and also the properties of its super class.

class A class MainClass


{ {
int x; public static void (String [] args)
public static void () {
{ B b1=new B ();
------ System.out.println(b1.a);
------ System.out.println(b1.b);
} b1.m1()
} }
class B }
{
int b=20;
}
P a g e | 30

12.Difference between this, super & this (), super ().

this this () super super ()


1.It is a keyword 1.It is a special method 1.It is a keyword 1.It is a special method

2.It is used to refer the 2.It is used perform 2. It is used to access 2. It is used perform
current object. (Use constructor calling. super class properties in constructor chaining.
differentiate between the sub class.
local variable and non-
static variable)

3.It can be used inside a 3. It can be used only 3.It can be used inside a 3. It can be used only
constructor and non- inside a constructor. constructor and non- inside a constructor.
static block. static block.

4.It can be used 4.It must always be the 4.It can be used 4.. It must always be the
anywhere within first statement of anywhere within first statement of
constructor or non-static constructor body. constructor or non-static constructor body.
methods body. methods body.

5.IS A Relationship is 5.IS A Relationship is 5.IS A Relationship is 5.IS A Relationship is


optional. optional. mandatory. mandatory.

13.Explain diamond ring problem.


 Diamond Ring problem is an Ambiguity that can arrives as a consequence of allowing multiple
inheritance in java.
 As shown in below class diagram class B and class C are having is a relationship with class A. So, the
properties of class A will be given to class B and class. Further class D is extending from class B &class
C so the properties of class B and class C will be inherited to class D. In the end we will end up having
multiple methods with the same name and same signature. In class D which is not allowed in Java,
this problem or issue is known as Diamond Ring problem.
 Diamond ring problem is one of the reasons for multiple inheritance to be no allowed in java.

Void: m1()

B C

m1() m1()
------

m1() m1()

----- ----
P a g e | 31

PACKAGES

1. What is a package? & How to create it?


 Package is a collection of classes and interfaces.
 Package can be created using the keyword “Package”. Package creation statement should be the first
statement in the source file per source file at most one package creation allowed.

Syntax: Package PackageName; Gmail

Ex: package gmail.login;


package gmail. logout; .login . logout
package gmail.inbox; (sub package class)

2. Where to write package creation statement?

The First statement in the source file.

3. Can one source file contain many packages creation statements?

No, because in one source file can only once package can be created.

4. When to use import? Explain with an example

If we want to access properties across the package, we use import.

package Gmail.login
package Gmail.login
import class B extends A;
import Gmail.logout.B;
{
{ public int p=100;
public class A }
public int x=10;
public int y=20; // only x and y are
int z=30; accessible from B class
private int m=40;
}
A.java B.java

5. Can one source file contain many import statements?

YES

6. In which order package & import keyword should exist in a source file?

 First package creation statement should be written and


 Import statement should be written in next line.
P a g e | 32

7. Explain access modifiers provided by java.

1.Private: Private members are accessible only with in the class.

2.Default: It is also known as package level access modifier default members are accessible within the
package from any class.

3.Protected: It is same as default + we can also access protected members outside the provided the class
were trying to access should inherit from the class which that member belongs to

4.Public: They can be accessible with the class with in the package and also outside the package.

8. What is data hiding? & How to achieve it?

Hiding the data members of a class from outside the class is known as data hiding. We can the data
through private data members. To access the hidden data member, we use public methods.

Ex: public class A


{
private int x;
public A (int x)
{
this.x=x;
}
//getter
public int getx ()
{
return x;
}
// setter
public void getx (int x)
{
this.x=x;
}
}
class program1
{
public static void main (String [] args)
{
A a= new A (10);
System.out.println (a. getx ()); // 10

a. setx (100);
System.out.println (a. getx ()); // 100

9. What is encapsulation?
 Binding the data member of class with the methods together in a single entity is known as
Encapsulation.
 A class is encapsulation of data members and methods.
 A package is encapsulation of classes and interfaces.
 A jar file is encapsulation of byte code file.
P a g e | 33

What is Java Bean Class?


 Writing a public class with private data members, public constructor, getters and setters is known as
Java Bean Class.
 Java bean class is an example for both Data hiding and Encapsulation.
 We write Java Bean Class in order to achieve DAO (Data Access Object) or DTO (Data Transfer Object)
layers of project development.

10. What is jar file? Where is rt.jar present? & What it contains?

It containing the executable files of pre-defined classes and interfaces.


 rt.jar – lib – JRE – JDK
 Executable files

11. Does default member gets inherited across the package.

No, because it is a package level access modifier.

12. Can I access public members outside the package if the class is default?

No, because class will not be imported

13. What is the name of byte code file of inner class.

 Outer classname - $
 Inner classname - .class

14.Can I declare a class as private? What access modifiers can I provide for a Class.

 Yes, we can declare class as private, if it is an inner class.


 For outer class public & default.
 For inner class public, private, protected& default.
P a g e | 34

ABSTRACT METHOD & ABSTRACT CLASS

1. What is abstract method?


A method without definition is known as abstract method such methods compulsory needs to be
declared as abstract.

2. What is abstract class?

A class declared as by using abstract keyword is known as Abstract class.

3. Where we provide definition for the abstract methods & what if we failed to provide?

 For all the abstract methods we will provide implementation in the subclass.
 If we fail to provide then we will declare subclass also as abstract.

4.When to declare a method abstract?

 When we don’t know the implementation of a method.


 At a present time but we know we will need it later.
 Then we declare that methods as abstract method.

5.When to go for abstract class?

 If a class contains at least one abstract method then it is mandatory to declare class as abstract.
 If class contains only concrete methods.
 Then it is optional to declare such class as abstract.

6.Can abstract class be final? Why?

No, because we need to provide the implementation of an abstract methods present in


super class in its subclass.

7. Can i declare static method as abstract? Why?

 Static method cannot be declared as abstract and vice versa.


 This is because abstract keyword is applicable only for object level methods not for class level
methods.
Ex: abstract public static void print ();

These two keywords not allowed in same line. Only one keyword only allowed

var (can’t reassign)


Public
final class (can’t inherit) var
Protected static class
Abstract Default
method (can’t override)
method
Private
Static
final

8. Can i change the access modifiers while providing implementation?


For the abstract methods.

While providing implementation in the subclass either we should retain the visibility or increase.
[But cannot decreased].
P a g e | 35

9. Can the abstract class be instantiated? Why

 Abstract class may sometimes contain only abstract methods.


 When we have only abstract methods in the abstract class, even if we create an object, we don’t have
any property keeping the might worst scenario in might java people decided we will not allow to
create an object for abstract class.

abstract class abstract class


{ {
concrete method Only abstract method
+ }
abstract method
}

10. Does abstract class allows constructor? If yes, explain with an


Example it's usage.

 Even though abstract class cannot be created constructors are allowed inside abstract class.
 Abstract class constructor will be executed when we instantiate the subclass through constructor
chaining process.
 Constructor inside the abstract class is used to initialise the data member of abstract class.

package org.jsp. abstracts; package org.jsp. abstracts;

abstract public class Calculator public class MainClass


{ {
public int x,y; public static void main (String []
public Calculator (int x,int y) args)
{ {
this.x=x; C c =new C ();
this.y=y; System.out.println("x = "+c.x);
} System.out.println("y = "+c.y);
abstract public void add (); System.out.println("z = "+c.z);
} c.print ();
c.print (750);
c.disp ();
}
package org.jsp. abstracts; }

public class Addition extends Calculator


{
public Addition (int x, int y)
{
super (x, y);
}
public void add ()
{
System.out.println("Sum="+(x+y));
}
}

11. Can I declare private method as abstract? Why?

No, because the private method will not be inherited in its sub class.
P a g e | 36

12. Does abstract class allows static members? If yes, how to access them?
Write an example.

YES,

package org.jsp.abstracts;
public class A
{
public int x=10;
public static int y=100;
public static void print ()
{
System.out.println(“static concrete method”);
}
package org.jsp. abstracts;
public class MainClass
{
public static void main (String [] args)
System.out.println(“x=+”A.x);
System.out.println(“x=+”A.x);
}
}

13. Advantages of abstract class.


If we don’t know the definition of a method at present. But we know we will need it later.so we use
abstract class.
P a g e | 37

INTERFACE

1. What is an interface, write the template.

 Interface is a java definition block which is used to define data member and methods.
 Data members are by default static and final and methods are by default public and abstract.

interface A
{ interface A
{
same int x=10;
static final int x=10;
void m1();
public abstract void m1(); }

Note:

 Interface cannot be instantiated.


 Constructors are not allowed inside the interface.
 For all the abstract methods of an interface we provide implementation in the implementation class.
 Using implements keyword.

IS-A

Class Interface
| |
| |
| |
| |
| |
Class Class

2. Can an interface extend from another interface? Write an example

Yes.

interface Itr1
{
}
interface Itr2 extends Itr1
{
}
P a g e | 38

3. Can an interface extend from more than 1 interface? Write an example

 An Interface can extend for another interface but not from class.
 A class interface inherits from more than one interface that is multiple inheritance is allowed w.r.to
interface but not respect to interface.

Itr1 Itr2

k:int k:int
print (): void print (): void

I class class I class implements Itr1, Itr2


{
// provide implementation for print ()
}

 A class can behaves as a subclass as well as implementation class at a time simultaneously.

Itr1
object
x:int
print (): void

Implem extends
class I class extends object implementation Itr2
I class
{

both }
sub class & implem class

4. What is marker interface? Examples.

 An Interface which contains nothing is known as marker interface.


 Such as marker interfaces internally used by the JVM for Run Time Validation of an object.

Ex: cloneable (I)


interface A
Serializable (I) pre-defined interfaces
{
Random Access (I)
// empty
}
P a g e | 39

5. What is functional interface? Examples

 An interface having only one Single Abstract Method (SAM) is known as functional interface.

interface Itr1 Ex: comparable (I)


{ Runnable (I)
Void m1(); Action Lister (I)
}

Ex: interface Itr1


{
void m1(); functional interface (SAM)
int x=10;
}
interface Itr2
{
int x=10;
public static void m1() functional interface
{ (SAM)
------
}
void m2();
}
interface Itr3
{ just an interface
void m1(); but not functional interface
void m2();
}

6. Does interface allows concrete methods?

 Interfaces was pure abstract till 1.7 version of java.


 From 1.8 version onwards interface is no more pure abstract that is from 1.8 version concrete methods
are allowed inside the interface.
 These concrete methods must be either static or default.

interface Itr
{
public static void main (String [] args]
{ Compile:
System.out.println(“HELLO WORLD”);
} javac Itr.java
} java Itr

without class using “hello world”


P a g e | 40

7. Difference between abstract class & interface?

Abstract Class Interface


1. Constructor are allowed. 1. Constructor are not allowed.
2. It is not pure abstract class. 2. It is not pure abstract till 1.7 vesrion.from
1.8 version no more pure abstract.
3. Multiple inheritance classes w.r.to not 3. Multiple inheritance w.r.to interface
allowed. allowed.
4. Data Member can be static or non-static. 4. Data Member are by default static or non-
static.

8. Advantages of interfaces.

To achieve abstraction

9.Explain the importance of interface type reference var.

By creating a single interface type reference variable, we can accept any implementation class object.
And we can achieve tight coupling.

10. Can one interface have multiple implementation classes? Write an example

Yes,

Example : (abstraction)

Animal (i) , Browser Factory


P a g e | 41

11. When to go for interface? & When to go for abstract class?


P a g e | 42

Typecasting

1. What is type casting? Explain data typecasting with example.

 Converting from one type of information to another type is known as Type Casting.
 Type Casting is classified into 2 types:

Type Casting

primitive type casting Non-primitive type casting

Narrowing Widening Up Casting Down casting

should be done can be done compiler/user should be done by


Explicitly by user implicitly / explicitly user explicitly

short (2 byte)

Byte

char --- int --- long ---- float ---- double

2 byte 4-byte 8-byte 4-byte 8 byte

Ex: int x=10; int x=100 l; // CTE


long y= 100; // implicit widening
double y=10.11;
int x = (int) 100 l
System.out.println (x); // 10
System.out.println (y); // 10.0
int x=10.11; // CTE

double y=10;
float f=3.14; // CTE
implicitly widening double e = 8.14 f; // implicitly widening
float f = (float )3.14;
int x=(int) 10.11; Explicitly Narrowing System.out.println (e); // 3.14
System.out.println (x); // 10 System.out.println (f); // 8.14
System.out.println (y); // 10.0

2. What is narrowing? Why narrowing should be done by user explicitly.

 Converting higher datatype to smaller datatype is known as narrowing.


 Because there is loss of data so we have to do it explicitly done by the user.
P a g e | 43

3. What is widening? Why compiler will do it implicitly

 Converting smallest datatype to highest datatype is known as widening.


 Because there is no loss of data.

4. Explain class typecasting with an example.

Converting from one class type of information to another class is known as non-primitive type casting.

A a = new A (); A
class A B b= new B (); X: int
{ Print (): void
int x=10; A a=new B ();
public void print ()
Type mismatching
{ B b=new A (); Statements
-----
} B
class B extends A
{ System.out.println (a.x); y: double
double y =10.11; a.print (); disp (): void
public void disp ()
{ B b= (B) new A (); // explicit down casting
-----
}
}

5. What is up casting? & What is down casting?

 Up Casting: When subclass object is referred by super class reference is known as Up casting.

 Down Casting: When super class object is referred by subclass reference is known as Down casting.

6. What is return type of instance of?

It returns Boolean value.

7. When we get ClassCastException (CCE)?

 The class we are trying to convert should contains the properties of the class to which we are trying to
convert.
 If the 1st condition is failed, we will get CTE and 2nd condition is failed we will get ClassCastException
(CCE).
P a g e | 44

8. What is the advantage of class type casting, Explain with an example?

 Without Typecasting: (specialization)

 When we don’t use typecasting, we will end up writing multiple overloaded specialized methods.
 A method which accepts specific type of object is known as “Specialized method “.
 A Program written by using specialised is known as ‘Specialisation’.

A
X: int
Print (): void

B C D
y: double Z: char m: long

class Display
{
public void print (B b)
{
System.out.println (b.x+” “+b.y);
}
public void print (C c)
{
System.out.println (c.z);
}
public void print (D d)
{
System.out.println (d.m);
}
class MainOfDisplay
{
public static void main (String [] args)
{
Display d=new Display ()
d.print (new b ());
d.print (new c ());
d.print (new d ());
}
}
P a g e | 45

 With Typecasting: (Generalization)

 When we use Typecasting, we will able to right one generalized method which can accepts returns
any type of object.
 A program returns by using such generalized methods is known as ‘Generalisation’.

class Display
Ex:
{
public void print (object obj)
{
if (obj instance of A)
{
A a = (A) obj;
System.out.println (a.x);

if (obj instance of B)
{
B b = (B) a;
System.out.println (b.y);
}
if (obj instance of C)
{
C c = (c) a;
System.out.println (c.z);
}
if (obj instance of D)
{
D d = (D) a;
System.out.println (D.m);
}
}
}
}
class MainOfDisplay
{
public static void main (String [] args)
{
Display d=new Display ()
d.print (new B ()); // object obj = new B ()
d.print (new C ()); // object obj = new B ()
d.print (new D ()); // object obj = new B ()
}
}
P a g e | 46

9. Explain instance of operator with an example?

 “instanceof “is a keyword used to check whether the given object contains the properties of any
particular class or not.
 It returns Boolean value.

class A
{
int x=10;
public void main ()
{
-------
}
class B extends A
{
double y=10.11;
public void disp ()
{
----
}
}
class MainOfA
{
public static void main (String [] args)
{
A a=new B ();
System.out.println(a.x);
System.out.println(a.print ());
B.b=(B) new A ();
if (a instanceof B)
{
B b=(B) a; Up casted
System.out.println(b.y);
b.disp ();
}
}

A a = new A ();
If (a instanceof B)
{
B b = (B) a; // CCE
}
Not up casted
P a g e | 47

JAVA BEAN CLASS

1. What is java bean class? Write an example

 Writing public class with private data member, public constructor, getters and setters is known as
Java Bean Class.
 Java Bean Class is an example for both data hiding and encapsulation.
 We write java bean class in order to achieve DAO (Data Access Object) or DTO (Data Transfer Object)
layers of project development.

public class A
{
private int x;
public A (int x);
{
this.x = x;
}
// getter
public int get x ();
{
return x;
}
// setter

public int set x (int x);


{
this.x = x;
}
}
class program 1
{
public static void main (String [] args)
{
A a = new A (10);
System.out.println (a.get x ()); // 10
a.set x (100);
System.out.println (a.get x ()); // 100
}
}

2. What are getters & setters? Write the syntax of it.

Getters: Getters are used to get the values. The values of a private data member from one class to another.

Setters: Setters used to set the values of a private data member from one class to another.

Syntax: // getter
public int get x ()
{
return x;
}

// setter
public void set x (int x)
{
this.x=x;
}
P a g e | 48

PRIVATE CONSTRUCTOR & SINGLETON CLASS

1. What is the default access modifier of constructor?

Public is the default access modifier of constructor

2. Can the constructor be private? Then, how to create an object. Explain


with an example.

Yes, with help of setters

3. What is singleton class? Write an example

 A class whose object can be created only throughout the live of the project.
 This can be achieved by using private constructor, helper method and private data member.
 This is called Single-Ton-class.

Ex: package org.jsp.abstracts;


public class Demo;
{
static Demo d;
private D ()
{
System.out.println (“HELLO”);
}
public static Demo get obj ()
{
if(d==null)
{
D=new Demo ();
}
return d;
}
public class MainDemo
{
public static void main (String [] args)
{
Demo d=Demo.getobj(); //Demo d=new Demo ()
Demo d1 = Demo.getobj();
}
}

4. Advantages of singleton class.

 Duplication of object of that class not allowed.


 Only one object can be created.
P a g e | 49

5. Explain how to achieve constructor chaining in singleton class.


P a g e | 50

You might also like