“Life is your journey, Goals are your destination and Hard Work is your set of wheels.” 1
Pemmaiah.U.T, HOD, Dept. of BCA, Cauvery College, Gonikoppal JAVA Exam Guide
1. Define arrays? How to create and instantiate a one dimensional array reference variable?
Give Example?
An array is a collection of similar data types. Array is a container object that hold
values of homogenous type. It is also known as static data structure because size
of an array must be specified at the time of its declaration.
To use an array in a program, you must declare a variable to reference the array,
and you must specify the type of array the variable can reference. Here is the
syntax for declaring a one dimensional array variable −
Syntax
dataType[] identifier;
or
dataType identifier [];
Initialization of one dimensional Array new operator is used to initialize an array. Example : int[ ] arr = new int[10]; //10 is the size of array. or int[ ] arr = {10,20,30,40,50};
One More Example :
Following statement declares an array variable, myList, creates an array of 10
elements of double type and assigns its reference to myList −
double[] myList = new double[10];
Following picture represents array myList. Here, myList holds ten double values and the
indices are from 0 to 9.
“Life is your journey, Goals are your destination and Hard Work is your set of wheels.” 2
Pemmaiah.U.T, HOD, Dept. of BCA, Cauvery College, Gonikoppal JAVA Exam Guide
2. Explain the use of for each style of loop with suitable example?
foreach loop is used to access elements of array. Using foreach loop you can access
complete array sequentially without using index of array.
Example :
class Test
{
public static void main(String[] args)
{
int[] arr = {10, 20, 30, 40};
for(int x : arr)
{
System.out.println(x);
}
}
}
Output :
10
20
30
“Life is your journey, Goals are your destination and Hard Work is your set of wheels.” 3
Pemmaiah.U.T, HOD, Dept. of BCA, Cauvery College, Gonikoppal JAVA Exam Guide
40
3. Explain the use of length member in arrays?
The length member is used in array to find the length of the arrays.
For Example:
Class TestArray{
{
public static void main(String args[])
{
Int array[]={1,2,3,4,5};
System.out.println(array.length);
}
}
4. Define String in Java? How to initiate a Strings in java?
String is a Sequence of character in Java, widely used as objects.
Creating a String object
String can be created in number of ways, here are a few ways of creating string object.
1) Using a String literal
String literal is a simple string enclosed in double quotes " ". A string literal is treated as a
String object.
String str1 = "Hello";
Here str1 is an object of string and have assigned a value “Hello”.
2) Using new Keyword
String str3 = new String("Java");
Here str3 is an object of string and have assigned a value “Java”.
“Life is your journey, Goals are your destination and Hard Work is your set of wheels.” 4
Pemmaiah.U.T, HOD, Dept. of BCA, Cauvery College, Gonikoppal JAVA Exam Guide
5. List any five methods associated with Strings?
charAt()
charAt() function returns the character located at the specified index. String str = "studytonight"; System.out.println(str.charAt(2)); Output : u
length()
length() function returns the number of characters in a String.
String str = "Count me";
System.out.println(str.length());
Output : 8
replace()
replace() method replaces occurances of character with a specified new
character.
String str = "Change me";
System.out.println(str.replace('m','M'));
Output : Change Me
toLowerCase()
toLowerCase() method returns string with all uppercase characters
converted to lowercase.
String str = "ABCDEF";
System.out.println(str.toLowerCase());
Output : abcdef
toUpperCase()
This method returns string with all lowercase character changed to
uppercase.
String str = "abcdef";
System.out.println(str.toUpperCase());
Output : ABCDEF
“Life is your journey, Goals are your destination and Hard Work is your set of wheels.” 5
Pemmaiah.U.T, HOD, Dept. of BCA, Cauvery College, Gonikoppal JAVA Exam Guide
6. What are command line arguments?
The java command-line argument is an argument i.e. passed at the time of running the java program. The arguments passed from the console can be received in the java program and it can be used as an input. So, it provides a convenient way to check the behavior of the program for the different values. You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Simple example of command-line argument in java
In this example, we are receiving only one argument and printing it. To run this java
program, you must pass at least one argument from the command prompt.
class CommandLineExample
{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample CrossMove
Output: Your first argument is: CrossMove
7. Define Class and Objects?
Class can be defined as a template/ blueprint that describe the behaviors /states of a
particular entity.
A class defines new data type. Once defined this new type can be used to create object
of that type.
Object is an instance of class. You may also call it as physical existence of a logical template
class.
A class is declared using class keyword. A class contain both data and code that
operate on that data. The data or variables defined within a class are called instance variables
and the code that operates on this data is known as methods.
“Life is your journey, Goals are your destination and Hard Work is your set of wheels.” 6
Pemmaiah.U.T, HOD, Dept. of BCA, Cauvery College, Gonikoppal JAVA Exam Guide
Syntax:
public class class_name { Data Members; Methods; }
8. What is the purpose of new operator?
The new operator dynamically allocates memory for an object.
Student is a class and student's name, roll number, age will be its property. Lets see this
in Java syntax
class Student. { String name; int rollno; int age; }
When a reference is made to a particular student with its property then it becomes an
object, physical existence of Student class.
Student std=new Student();
After the above statement std is instance/object of Student class. Here the new keyword
creates an actual physical copy of the object and assign it to the std variable. It will have
physical existence and get memory in heap area. The new operator dynamically allocates
memory for an object
9. Define Constructors? What is the purpose of Constructors?
A constructor is a special method that is used to initialize an object.
Java constructor is invoked at the time of object creation
There are basically two rules defined for the constructor.
Constructor name must be same as its class name
Constructor must have no explicit return type
“Life is your journey, Goals are your destination and Hard Work is your set of wheels.” 7
Pemmaiah.U.T, HOD, Dept. of BCA, Cauvery College, Gonikoppal JAVA Exam Guide
10. Explain the types of constructors in java?
There are two types of constructors:
Default constructor (no-arg constructor)
Parameterized constructor
Java Default Constructor
A constructor that have no parameter is known as default constructor.
In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.
class Bike1{ Bike1(){System.out.println("Bike is created");} public static void main(String args[]){ Bike1 b=new Bike1(); } } Output: Bike is created Java parameterized constructor
A constructor that have parameters is known as parameterized constructor.
Parameterized constructor is used to provide different values to the distinct objects.
In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor. class Student4{ int id; String name; Student4(int i,String n){ id = i; name = n; } void display(){System.out.println(id+" "+name);}
“Life is your journey, Goals are your destination and Hard Work is your set of wheels.” 8
Pemmaiah.U.T, HOD, Dept. of BCA, Cauvery College, Gonikoppal JAVA Exam Guide
public static void main(String args[]){ Student4 s1 = new Student4(111,"Pradhan"); Student4 s2 = new Student4(222,"Suman"); s1.display(); s2.display(); } } OutPut: 111 Pradhan
222 Suman
11. What is garbage collections?
Automatic Technique used in Java Programming which is used to de-allocate
memory is called as “Garbage Collection“.
Garbage Collection is Done Automatically by JVM.
As soon as compiler detects that – Object is no longer needed inside program,
Garbage Collection Algorithm gets executed automatically to free up memory
from the heap so that free memory may be used by other objects.
12. What is the use of finalize method () in java?
finalize() is called by the garbage collector on an object when garbage collection
determines that there are no more references to the object.
finalize() method is called by garbage collection thread before collecting object.
It’s the last chance for any object to perform cleanup utility.
Syntax of finalize() method
protected void finalize()
{
//finalize-code
}
13. What is the use of this keyword?
In java, this is a reference variable that refers to the current object.
this() keyword can be used to refer current class instance variable.
this() can be used to invoke current class constructor.
this() keyword can be used to invoke current class method (implicitly)
this() can be passed as an argument in the method call.
“Life is your journey, Goals are your destination and Hard Work is your set of wheels.” 9
Pemmaiah.U.T, HOD, Dept. of BCA, Cauvery College, Gonikoppal JAVA Exam Guide
this() can be passed as argument in the constructor call.
this() keyword can also be used to return the current class instance.
14. List different access modifiers in Java?
There are 4 types of java access modifiers:
private
default
protected
public
private access modifier
The private access modifier is accessible only within class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private
data member and private method. We are accessing these private members from
outside the class, so there is compile time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
default access modifier
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing the A
class from outside its package, since A class is not public, so it cannot be accessed from
outside the package.
“Life is your journey, Goals are your destination and Hard Work is your set of wheels.” 10
Pemmaiah.U.T, HOD, Dept. of BCA, Cauvery College, Gonikoppal JAVA Exam Guide
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error } }
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
protected access modifier
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
“Life is your journey, Goals are your destination and Hard Work is your set of wheels.” 11
Pemmaiah.U.T, HOD, Dept. of BCA, Cauvery College, Gonikoppal JAVA Exam Guide
B obj = new B();
obj.msg();
}
}
Output:Hello
public access modifier
The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.
Example of public access modifier
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
15. Explain how to pass objects to methods with suitable example?
We can pass Object of any class as parameter to a method in java.
We can access the instance variables of the object passed inside the called
method.
It is good practice to initialize instance variables of an object before passing object
as parameter to method otherwise it will take default initial values.
Example :
void area(Rectangle r1) {
“Life is your journey, Goals are your destination and Hard Work is your set of wheels.” 12
Pemmaiah.U.T, HOD, Dept. of BCA, Cauvery College, Gonikoppal JAVA Exam Guide
int areaOfRectangle = r1.length * r1.width;
System.out.println("Area of Rectangle : "
+ areaOfRectangle);
}
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle(10, 20);
r1.area(r1);// here we passing entire object as parameters through methods
}
16. What is method overloading? Explain with an Example?
If a class have multiple methods by same name but different parameters, it is
known as Method Overloading.
Compile determine which method to execute automatically.
Example:
class Rectangle {
double length;
double breadth;
void area(int length, int width) {
int areaOfRectangle = length * width;
System.out.println("Area of Rectangle : " + areaOfRectangle);
}
void area(double length, double width) {
double areaOfRectangle = length * width;
System.out.println("Area of Rectangle : " + areaOfRectangle);
}
}
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle();
r1.area(10, 20);
r1.area(10.50, 20.50);
}
“Life is your journey, Goals are your destination and Hard Work is your set of wheels.” 13
Pemmaiah.U.T, HOD, Dept. of BCA, Cauvery College, Gonikoppal JAVA Exam Guide
}
Explanation:
We have defined 2 methods with same name and different type of parameters.
When both integer parameters are supplied to the method then it will execute
method with all integer parameters and if we supply both floating point numbers
as parameter then method with floating numbers will be executed.
17. What is the purpose of Static keyword?
Static is a keyword that acts as a non-access modifiers in java that is used to manage
memory.
18. What is a Static variable? Example?
If you declare any variable as static, it is known static variable.
The static variable can be used to refer the common property of all objects (that
is not unique for each object) e.g. company name of employees, college name of
students etc.
The static variable gets memory only once in class area at the time of class loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value. class Counter2{ static int count=0;//will get memory only once and retain its value Counter2(){ count++; System.out.println(count); } public static void main(String args[]){ Counter2 c1=new Counter2(); Counter2 c2=new Counter2(); Counter2 c3=new Counter2(); } } Output:1
“Life is your journey, Goals are your destination and Hard Work is your set of wheels.” 14
Pemmaiah.U.T, HOD, Dept. of BCA, Cauvery College, Gonikoppal JAVA Exam Guide
2 3
19. What is a Static methods? Example?
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a
class.
static method can access static data member and can change the value of it.
Restrictions for static method
There are two main restrictions for the static method. They are:
The static method cannot use non static data member or call non-static method
directly.
this and super cannot be used in static context.
Example:
class Calculate{
static int cube(int x){
return x*x*x;
}
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result);
}
}
Output: 125
20. Why java main method is static?
Because object is not required to call static method if it were non-static method, jvm
create object first then call main() method that will lead the problem of extra memory
allocation.
21. What is a Static blocks? Example?
Is used to initialize the static data member.
It is executed before main method at the time of class loading.
“Life is your journey, Goals are your destination and Hard Work is your set of wheels.” 15
Pemmaiah.U.T, HOD, Dept. of BCA, Cauvery College, Gonikoppal JAVA Exam Guide
Example:
class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Output:
static block is invoked
Hello main
22. Explain nesting of classes with example?
When we declares a class within the body of another class or interface then class is called
as nested class.
There are two types of nested classes:
Static inner classes and non-static nested classes.
Non-static nested classes are called inner classes.
Three Types of the Inner Classes are listed below –
Member inner classes
Local inner classes
Anonymous inner classes
Example of Nested Class:
public class OuterClass {
class NestedClass {
}
}
In the above example we can say that InnerClass is class which is enclosed in the
OuterClass.
23. Explain about inner classes in java?
Non-static nested classes are called inner classes. Three Types of the Inner Classes are
listed below –
Member inner classes
Local inner classes
Anonymous inner classes
“Life is your journey, Goals are your destination and Hard Work is your set of wheels.” 16
Pemmaiah.U.T, HOD, Dept. of BCA, Cauvery College, Gonikoppal JAVA Exam Guide
Member Inner Classes:
A Member Inner Class is a class whose definition is directly enclosed by another
class or interface declaration
Instance of a Member Inner Class can only be created if we have a reference to an
instance of outer class.
A local Inner Class :
Local Inner Class is not a member class of any other class.
Its declaration is not directly within the declaration of the outer class.
Local Inner Class can be declared inside particular block of code and its scope is
within the block.
Anonymous Inner Classes :
A class which does not have name is called as anonymous inner class. Anonymous
class can be created using two methods :
By using the interface
By using the abstract class
Anonymous Inner Classes are used for writing an interface implementation.
24. Explain how to pass variable length arguments with suitable arguments?
The varrags allows the method to accept zero or muliple arguments. Before
varargs either we use overloaded method or take an array as the method
parameter but it was not considered good because it leads to the maintenance
problem.
If we don't know how many argument we will have to pass in the method, varargs
is the better approach.
Syntax of varargs:
The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows:
return_type method_name(data_type... variableName){}
“Life is your journey, Goals are your destination and Hard Work is your set of wheels.” 17
Pemmaiah.U.T, HOD, Dept. of BCA, Cauvery College, Gonikoppal JAVA Exam Guide
class VarargsExample1{
static void display(String... values){
System.out.println("display method invoked ");
}
public static void main(String args[]){
display();//zero argument
display("my","name","is","varargs");//four arguments
}
}
Output:
display method invoked
display method invoked
25. Define inheritance?
Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another.
The class which inherits the properties of other is known as subclass (derived class,
child class) and the class whose properties are inherited is known as superclass
(base class, parent class).
extends is the keyword used to inherit the properties of a class.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Example:
Class Super{
Int a=10;
}
Class Sub extends Super{
Public static void main(String args[])
{
Int b=20;
System.out.println(a);
“Life is your journey, Goals are your destination and Hard Work is your set of wheels.” 18
Pemmaiah.U.T, HOD, Dept. of BCA, Cauvery College, Gonikoppal JAVA Exam Guide
System.out.println(b);
}
}
Output: 10
20
26. Why use inheritance in java?
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
27. What is the purpose of Keyword extends?
extends is the keyword used to inherit the properties of a class.
28. What is the purpose of super keyword?
The super keyword in java is a reference variable that is used to refer immediate parent
class object.
Usage of java super Keyword
super is used to refer immediate parent class instance variable.
super() is used to invoke immediate parent class constructor.
super is used to invoke immediate parent class method.
class Vehicle{
int speed=50;
}
class Bike4 extends Vehicle{
int speed=100;
void display(){
System.out.println(super.speed);//will print speed of Vehicle now
}
public static void main(String args[]){
Bike4 b=new Bike4();
b.display();
}
}
29. Explain how a super is used to invoke parent class constructor.
The super keyword can also be used to invoke the parent class constructor as given below:
“Life is your journey, Goals are your destination and Hard Work is your set of wheels.” 19
Pemmaiah.U.T, HOD, Dept. of BCA, Cauvery College, Gonikoppal JAVA Exam Guide
class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
class Bike5 extends Vehicle{
Bike5(){
super();//will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike5 b=new Bike5();
} }
As we know well that default constructor is provided by compiler automatically but it also
adds super() for the first statement.If you are creating your own constructor and you don't
have either this() or super() as the first statement, compiler will provide super() as the
first statement of the constructor.
30. Define method overriding?
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.
Or
Method with same name, same parameters and with same return type is known as
method overriding.
Rules for Java Method Overriding
method must have same name as in the parent class
method must have same parameter as in the parent class.
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}
public static void main(String args[]){
Bike2 obj = new Bike2();
obj.run();
}
“Life is your journey, Goals are your destination and Hard Work is your set of wheels.” 20
Pemmaiah.U.T, HOD, Dept. of BCA, Cauvery College, Gonikoppal JAVA Exam Guide
In this example, we have defined the run method in the subclass as defined in the parent
class but it has some specific implementation. The name and parameter of the method is
same and there is IS-A relationship between the classes, so there is method overriding.
31. Difference between method overriding and method overloading?
1) Method overloading is used to increase the readability of the program.
Method overriding is used to provide the specific implementation of the method
that is already provided by its super class.
2) Method overloading is performed within class.
Method overriding occurs in two classes that have IS-A (inheritance) relationship.
3) In case of method overloading, parameter must be different.
In case of method overriding, parameter must be same.
4) Method overloading is the example of compile time polymorphism.
Method overriding is the example of run time polymorphism.
5) In java, Return type can be same or different in method overloading.
Return type must be same in method overriding.
32. Define abstract class? Example?
A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated. To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it. abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run()
{
System.out.println("running safely..");// body implementation
}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
Output: running safely..
In the above example Bike is an abstract class. This class can’t create any objects.
“Life is your journey, Goals are your destination and Hard Work is your set of wheels.” 21
Pemmaiah.U.T, HOD, Dept. of BCA, Cauvery College, Gonikoppal JAVA Exam Guide
The methods declared inside the abstract class is called abstract methods. But those methods can’t define their body over there. The implementation should be done in the derived class. i.e., Honda4 is the derived class above. There we can implements run() method.
33. What is the purpose of final variables?
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
Example of final variable
There is a final variable speedlimit, we are going to change the value of this variable, but
It can't be changed because final variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Output: compile time error
34. What is final Class in Java?
If you make any class as final, you cannot extend it(inheritance is not possible).
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda();
honda.run();
}
}
Output: Compile time error.
In above example Bike class can’t be derived because it is declared as final class .
“Life is your journey, Goals are your destination and Hard Work is your set of wheels.” 22
Pemmaiah.U.T, HOD, Dept. of BCA, Cauvery College, Gonikoppal JAVA Exam Guide
35. What are final methods in Java?
If you make any method as final, you cannot override it. class Bike{ final void run(){System.out.println("running");} } class Honda extends Bike{ void run(){System.out.println("running safely with 100kmph");} public static void main(String args[]){ Honda honda= new Honda(); honda.run(); } } Output: Compile Time Error
36. What is an Object Class? The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java.
37. What is recursion in Java?
Recursion in java is a process in which a method calls itself continuously. A method in java that calls itself is called recursive method. Syntax: returntype methodname(){ //code to be executed methodname();//calling same method } // Program to find factorial public class RecursionExample3 { static int factorial(int n){ if (n == 1) return 1; else return(n * factorial(n-1)); } public static void main(String[] args) { System.out.println("Factorial of 5 is: "+factorial(5)); } } Output:Factorial of 5 is: 120
Top Related