Vous êtes sur la page 1sur 18

JAVA

1. What is object oriented programming?


A programming technique based on the concept of “Class” and “Object”.

2. What is a class?
In manufacturing a blueprint is a descrioption of a device from which many physical
devices are constructed.
In software, a class is a description of an object.
A class describe the data that each object includes (variables).
A class describe the behaviour of that each object exhibit (methods).

3. What is an object?
An object is an instance of the class. Object store data and provides method for accessing
and modifying this data.

4. What is an instance?
At that particular time what ever the values hold by an object of a class is called as
instatnce. It is the state of an object.

5. What are the main concepts of Object Oriented Programming(OOPS) ?


The main Object Oriented Programming concepts are
1. Encapsulation: binding or wrapping or groupting of data and its corresponding
methods in one single unit. The main purpose is data hiding from external classes.
In java, encapsulation is achieved by making members of class as private.

2. Inheritance: process by which properties of one class acquire the another class. The
main purpose is code reusability.
In java, inheritance is achieved by using extends keyword

3. Abstraction:process of hiding the implementation details and providing only


functionality to the user.
In java, abstraction is achieved by using abstract classes and interfaces.

4. Polymorphism: It come from the two greek words poly meaning many and morphs
meaning forms. The ability to exist in different forms is called polymorphism.
In java, Polymorphism is achieved by using method overloading and overriding.

6. What is byte code?

1
Java solves the problem of platform independence by using byte code. The java compiler
does not produce native executable code for a particular machine like a C compiler does.
Instead it produces intermediate code called byte code.

7. What are the data types supported by java?


Java support the following data types.

8. What is the size, range and default values of each primitive data type?

9. What is the difference between instance, static, local variables?

2
Instance variable: if the value of variable varied from object to object such type of
variables are called as instance variables. For every object a separate copy of instance
variables will be created. The scope of instance variables is exactly same as the scope of
object. Instance variables should be declare with in the class directly but outside of any
method or block or constructor. Instance variables can not be accessed from static area
directly. We can access by using object reference. For these variables initialization is not
required explicitly, JVM will provide default values.

Ex: class Test


{
int x=10 ,y=20;
public static void main(String[] args)
{
//System.out.println(x+”---“+y); compile time error
Test t;
System.out.println(t.x+”---“+y);
}
}
Output: 10---20

Static variables: the value of the static variable is not varied from object to object. For all
the objects only one copy will be created at class level and it will be shared by all object
of that class. The scope of static variables is exactly same as the scope of the class i.e.
they will be created at the time of class loading and destroy at the time of class unloading.
Static variables should be declare with in the class directly but out side of any method or
constructor with static modifier. Static variable can be accessed by using class name or
by using object reference but recommended to use class name. For these variables
initialization is not required explicitly, JVM will provide default values.

Ex: class Test


{
Static int x=10;
public static void main(String[] args)
{
Test t1= new Test();
Test t2=new Test();
System.out. println(t1.x+”---“+t2.x);
t2.x=20;
System.out.println(t1.x+”---“+t2.x);
}
}

3
Output: 10---10
20---20

Local variables: to meat the temporary requirements of the program some times we have
to creare variables inside method or block or constructor such type of variables are called
as local variables. These variables will be created while executing the block in which we
declared it and destroy once the block execution completed. For the local variables JVM
wont provide any default value compulsory we should provide initialization before using
them.

Ex: class Test


{
public static void main(String[] args)
{
{
int x=10;
System.out.println(x);
}
// System.out.println(x); Compile time error
}
}

10. Why class name and file name should be same in java?
Java file may contain any number of java classes. If the file doesnt contain any public
class then file name could be anything. But if the file contain a public class (contains
main method) then the file name should be public class name. By which java interpreter
know about the entry point for the program.

11. How to create an object for a java class?

Class name keyword

Student stu1 =new Student();

Object name constructor

12. What is a constructor?

4
It is a special method having same name as that class name and called automatically
when an object is created.The main purpose is to initialize the instance variables.
Ex:
public class Student
{
int roll;
int marks;
Student( )
{
roll=1;
marks=10;
}
public static void main(String[] args)
{
Student s=new Student();
System.out.println(s.roll+”---“+s.marks);
}
}
Output: 1---10

13. What is the return type of a constructor?


Constructor doesn’t have any return type. If we declare return type for a constructor we
wont get any compile time error but it will be treated as a normal method but not
constructor.

14. What is the difference between public, private, protected and default access modifiers ?
These are the keywords used while declaring variables, methods, classes and which will
restrict the accessing scope.
Public: public means accessible and visible to every one in the package and outside the
package.
Protected: protected means accessible and visible to every one in the same package and
only to sub classes outside the package.
Default: default is applied by default. It is package friendly. When we do not apply any
access modifier than it is applied. It means accessible only in the same package.
Private: private means accessible only to the same class.

5
Visibility public Protected Default private
From the same class Yes Yes Yes Yes
From any class in the same Yes Yes Yes No
package
From a subclass in the same Yes Yes Yes No
package
From a subclass outside the Yes Yes, No No
same package through
inheritance
From any no-subclass Yes No No No
outside the package
15. What is a singleton class?
For any java class if we are allowed to create only one object such type of class is called
singleton class.
Ex: Runtime, ActionServlet

16. Write a program to create a singleton class.


class Test
{
private static Test t;
private Test()
{
}
Public static Test getInstance()
{
If(t==null)
{
t=new Test();
}
return t;
}
public object clone()
{
return this;
}
}

17. Describe about System.out.println().


System is a class available in java.lang package
out is a static variable present in System class of the type PrintStream
println is a method present in PrintStream class

6
18. Describe about public static void main (String[] args)
Public access modifier to call main method by JVM from anywhere
static access modifier to call mail method by JVM with out creatin any object to class.
void return type indicates main method wont return anything to JVM
main is a name which is configuried inside JVM
String[] args- command line arguments.

19. What is the difference between method overloading and overriding?


Method overloading: Two methods are said to be overloaded if and only if both the
methods having same name but different arguments. It is also called as compile time
polymorphism or early binding.
Ex: class Test
{
public void m1(int i)
{
}
public void m1(long l)
{
}
}

Method overriding: what ever methods parent has by default available to the child
through inheritance. Some times child may not satisfy with parent method
implementation. Then child is allow to redefine that method based on its requirement.
This process is called overriding. It is also called as runtime polymorphism or late
binding.
Ex: class Test
{
public void m1()
{
System.out.println(“ parent implementation”);
}
}
class Test1 extends Test
{
public void m1()
{
System.out.println(“child implementation”);
}
}

7
20. Can we overload the constructor?
Yes, we can overload the constructor.
Ex:
class Box
{
double width, height, depth;
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
Box()
{
width = height = depth = 0;
}
Box(double len)
{
width = height = depth = len;
}
double volume()
{
return width * height * depth;
}
}
public class Test
{
public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);
vol = mycube.volume();
System.out.println(" Volume of mycube is " + vol);
}
}

8
Output:
Volume of mybox1 is 3000.0
Volume of mybox2 is 0.0
Volume of mycube is 343.0

21. Can we override the constructor?


No , constructor can never be overridden . It's because constructor acts at class level only.

22. What is the use of this keyword?


This refers to current instance of the class. this keyword is used to access other members
of the same class. Using this keyword, you can access methods, fields and constructors of
the same class within the class.

23. What is the use of super keyword?


super keyword is used to access super class members inside the sub class. Using super
keyword, we can access super class methods, super class fields and super class
constructors in the sub classes.
If you want same implementation as that of super class method in the sub class, but want
to add some more extra statements to it, in such cases, super keyword will be very useful.
First call the super class method using super keyword and after it add extra statements
according to requirements in the sub class method.

24. Can we overload main method?


Yes, but JVM always call main method having String[] as a argurment main method. The
other overloaded method we have to call explicitly.

25. Can we override main method?


Yes, but it is called as method hiding not method overriding. If you run the child class,
child class main method will execute and parent method will not execute.

26. What is for-each loop?


This is the convenient loop to retrieve the elements of array and collections
Ex: int a={10, 20, 30, 40, 50}
for(int x:a)
System.out.println(x);

27. What is a var-arg method?


We can declare a method variable number of arguments such type of methods are called
as var-arg methods. var-arg methods declared as follows. We can invoke this method by
passing any number of arguments.

9
Ex: class Test
{
public void sum(int…x)
{
int total=0;
for(int y:x)
{
total=total+y;
}
System.out.println(total);
}
public static void main(string[] args)
{
Test t=new Test();
t.sum();
t.sum(10);
t.sum(10,20);
t.sum(10,20,30);
}
}
Output: 0
10
30
60

28. What is a package?


Pachage is a way of grouping related classes to avoid naming conflicts.
Tha standard java packages are
Java.lang
Java.io
Java.util
Java.awt

29. What is a abstract method?


Method which doesn’t contain any implementation is called abstract method. By placing
keyword abstract infrom of method we can define abstract methods.

30. What is the use of inheritance?


The main advantage of inheritance is Reusability. what ever the properties of parent class
will be obtained by child class with out rewriting the code.

10
31. Why java won’t support multiple inheritance?
When one class extends more than one classes then this is called multiple inheritance.
Java doesn’t allow multiple inheritance to avoid the ambiguity caused by it. If more than
one base class is having same method signature then it creates ambiguity to child class.
i.e. which method it has to access.

32. What is an interface?


It is a collection of abstract methods. If a class implements a interface then it should
implement all the abstract methods.

33. How java supports multiple inheritance through interfaces?


Interfaces consists of abstract methods. Even a class implements more than one interface
having common abstract methods, one method definition is provided by the
implementing class for all interfaces.

34. What is the difference between interface and abstract class?


Interface Abstract class
1. If we don’t know anything about 1. if we have few implementation details
implementation, just we have requirement and few of them not yet implemented then
specification then we should go for we should go for abstract class.
interface
2. every method present inside interface is 2. every method present inside abstract
public and abstract whether we are class need not to be abstract. In addition to
declaring or not abstract methods we can take concrete
methods also.
3. every variable present inside interface is 3. variables present in abstract class need
public, static and final whether we are not to be public , static and final.
declaring or not.

35. What is a marker interface?


It is a interface it doesn’t contain any methods. By implementing these interfaces objects
will get some ability.
Ex: Serializable, Clonable, RandomAccess

36. What is exception?


Unwanted or unexpected event which disturbs normal flow of program is called as
exceptions. Which are like accidents on road.

37. What is the difference between error and exception?


Exceptions are caused by our program and these are recoverable

11
Errors are not caused by our program these are due to lack of system resources and these
are non recoverable.

38. What is the super class for all the exceptions?


Throwable is the super class for all exceptions.

39. What is the difference between checked exceptions and unchecked exceptions?
Checked exceptions: these are the exceptions which are checked by the compiler for
smooth execution of program at runtime.
In the case of checked exceptions compiler will check whether we are handling
exception. If the programmer not handling exception then compiler raise error.
Example: FileNotFoundException, IOException

Unchecked exceptions: these are the exceptions which are not checked by the compiler.
In the case of unchecked exceptions compiler wont chech whether the programmer
hadling exceptions or not.
Example: ArithmeticException, NullpointerException.

40. What is the difference between final, finally and finalize?


final: It is a access modifier applicable for classes, methods and variables.
If a class declared as final then we can’t extend that class. i.e. we can’t create child class
for that class.
If a method declared as final then we can’t override that method in the child class.
If a variable declared as final then it will become constant and we can’t perform re-
assignment for that variable.

finally: It is a block associated with try catch to maintain cleanup code.

fianalize: It is a method which is always invoked by garbage collector just before


destroying an object to perform cleanup code.
Finally meant for cleanup activities related to try block. Where as finalize() meant for
cleanup activities related to object.

41. What is the importance of try-catch-finally?

Try- While writing a program, if you think that certain statements in a program may raise
an exception, enclosed them in try block and handle that exception

Catch- This block must follow the try block, where you handle the exceptions raised in
the try block. A single try block can have several catch blocks associated with it. You can
catch different exceptions in different catch blocks. When an exception occurs in try
block, the corresponding catch block that handles that particular exception executes. For

12
example if an arithmetic exception occurs in try block then the statements enclosed in
catch block for arithmetic exception executes.

Finally block in java can be used to put "cleanup" code such as closing a file, closing
connection etc.

Ex:
class Test
{
public static void main(String args[])
{
int num1, num2;
try
{
num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
System.out.println("end of try block");
}
catch (ArithmeticException e)
{
System.out.println("divide a number by zero is not possible");
}
catch (Exception e) {
System.out.println("Exception occurred");
}
System.out.println("out of try-catch block ");
}
}
Output:
divide a number by zero is not possible
out of try-catch block

42. How to create user defined exceptions?

43. What is a collection?


A group of individual object as a single entity is called as collection.

44. What are the differences between array and collection?

Array Collection
13
1. Arrays are fixed in size and hence once 1. Collections are growable in nature and
we created an array we are not allowed to hence based on our requirement we can
increase or decrease the size based on our increase or decrease the size.
requirement.
2. Performance point of view arrays are 2. Performance point of view collections
recommended to use.(Faster) are not recommended to use.
3. Arrays can hold only homogeneous 3. Collections can hold both homogeneous
elements. and heterogeneous elements.
Arrays can hold both primitives as well as 4. Collections can hold only objects.
objects.
5. Memory point of view arrays are not 5. Memory point of view collections are
recommended to use. recommended to use.

45. What are the interfaces and classes available in Collection framework?

46. What is the difference between == and equals() method in java?

== operator equals()
1. It is a operator applicable for both 1. It is a method applicable for only
primitives and object references references but not for primitives
2. == operator meant for reference 2. It is also meant for reference
comparision comparision but we can override for
content comparision. In String class
equals() is overridden for content
comparision.

47. What is the difference between String, StringBuffer ?

14
String is immutable, where as String is mutable.
Once we create a string object we can’t perform any changes in the existing object. If we
try to perform any changes, with those changes a new object will be created. This non
changeable nature is nothing but immutability of the string object.
Once we create a StringBuffer object we can perform any type of changes in the existing
object. This changeable nature is nothing but mutability of the StringBuffer object.
Ex:
class Test
{
public static void main(String[] args)
{
String s=new String(“amar”);
s.concat(“cse”);
System.out.println(s);
StringBuffer sb=new StringBuffer(“amar”);
s.append(“cse”);
System.out.println(sb);

Output: amar
amarcse

48. What is the default package in java?


Java.lang package. The most commonly required classes & interfaces for any java
program are encapsulated into a separate package whis is nothing but lang package. It is
not required to import explicitly by default it is available to every java program. Some of
the commonly used classes in java.lang package are Object, String , StringBuffer.

49. What is the base class for all the classes in java?
Object class is the parent for all the classes in java

50. What is multi threading?


Thread is a part of a program. Executing several parts of a one program simultaneously is
called multi threading.

51. What are the applications of multi threading?


The main application areas of multi threading are developing video games, multi media
graphics, implementing animations

15
52. How many ways we can implement multi threading in java?
In two ways we can implement multi threading.
i. By extending Thread class
ii. By implementing Runnable interface

53. What is run method?


What ever the functionality has to execute in a thread must be define in run method.

54. What is start method?


Run method is invoked by the start function call. When ever JVM encounter start method
then it redirect the control to corresponding run method definition.

55. What is the importance of static keyword?


If we use static key
56. What is the difference between throw, throws and throwable?

throw throws
1. It is used to create Exception object 1. It is used to deligate the responsibility
manually & hand over that object to the of exception handling to caller methods in
JVM explicityly case of checked exceptions
2. throw new ArithmeticExcepiton(“/by 2. public static void main(String[]
zero”); args)throws ServletException

57. What is garbage collection?

Garbage Collection is process of releasing the runtime unused memory automatically. In


other words, it is a way to destroy the unused objects. To do so, we were using free()
function in C language and delete() in C++. But, in java it is performed automatically. So,
java provides better memory management.

58. What is serialization?


The process of writing state of an object to a file is called serialization. It is a process of
converting an object from java supported form to either file supported form or network
supported form. By using FileOutputStream and ObjectOutputStream classes we can
achieve serialization.

59. What is deserialization?


The process of reading state of an object from a file is called deserialization.It is a
process of converting an object from either network supported form or file supported
form to java supported form. By using FileInputStream and ObjectInputStream classes
we can achieve deserialization.

16
60. Write program to implement serialization and deserialization.
class Test implements Serializable
{
Int i=10;
Int j=20;
}
Class SerializationDemo
{
public static void main(String[] args)
{
Test t=new Test();
FileOutputStream fos=new FileOutputStream(“abc.txt”);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(t);
FileInputStream fis=new FileInputStream(“abc.txt”);
ObjectInputStream ois=new ObjectInputStream(fis);
Test t1=(Test)ois.readObject();
System.out.println(t1.i+”----“+t1.j);
}
}
Output: 10----20

61. What is the use of transient keyword?


At the time of serialization if we don’t want to serialize the value of a variable to meet the
security constraints then we have to declare those variables with “transient” keyword. At
the time of serialization JVM ignores original value of transient variable and saves
default value.

62. Explain command line arguments in java.


The arguments which are passing from command prompt are called command line
arguments.
Ex: class Test
{
public static void main(String[] args)
{
System.out.println(“arguments are”);
for(int i=0; i<args.length; i++)
{
System.out.println(args[i]);
}

17
}
}

Output: java Test x y z


arguments are
x
y
z

18

Vous aimerez peut-être aussi