0% found this document useful (0 votes)
3 views

JAVA Unit 2

The document provides an overview of key concepts in Java programming, including class definitions, constructors, inheritance, and the use of keywords like 'this' and 'super'. It explains various types of inheritance, the differences between methods and constructors, and the characteristics of strings and vectors. Additionally, it covers method overloading and overriding, along with examples to illustrate these concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

JAVA Unit 2

The document provides an overview of key concepts in Java programming, including class definitions, constructors, inheritance, and the use of keywords like 'this' and 'super'. It explains various types of inheritance, the differences between methods and constructors, and the characteristics of strings and vectors. Additionally, it covers method overloading and overriding, along with examples to illustrate these concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

UNIT-II

1. Define a class and write down its syntax?


 Class is a blueprint/template from which objects are created.
 Class is a collection of Data member and Member function.
Syntax:
<access specifier> class class_name
{
// member variables
// class methods
}
2. What is the use of ‘this’ and ‘super’ keyword?
‘This’ Keyword:
 this can be used to refer current class object.
 this can be used to access current class method (implicitly)
 this() can be used to access current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
‘Super’ Keyword:

 super can be used to call the constructor of parent class


 super can be used to invoke immediate parent class method.
3. How multiple inheritances are achieved in Java?
 Multiple inheritance in Java programming is achieved or implemented using
interfaces.
 Java does not support multiple inheritances using classes.
 A class can extend only one class but it can implement multiple interfaces.
4. What is instance variable? Give an example.
 Instance variables are declared in a class, but outside a method. They are also
called member variables.
 Instance variables are created when an object is created and destroyed when the
object is destroyed
 Example:
class Demo
{
public String pageName;
private int pageNumber;
public method1()
{

}
}
5. Write a few points about ‘default constructor’.
 A constructor is called "Default Constructor" when it doesn't have any
parameter.
 Ex:
class A
{
A()
{

}
}
6. What does ‘static’ keyword do in a class?
 A class can be made static only if it is a nested class.
 Nested static class doesn’t need a reference of Outer class. In this case, a static
class cannot access non-static members of the Outer class.

7. What is default constructor and parameterized constructor?


Default constructor: Constructor with no arguments is called as default
Constructor.
Ex:
class A
{
A()
{

}
}
Parameterized constructor: Constructor with arguments is called as parameterized
constructor.
Ex:
class A
{
A(int a)
{

}
}
8. Difference b/w ‘string’ class and ‘string buffer’ class.
String class String Buffer

The String class is immutable. The StringBuffer class is mutable.

String class is slower while performing StringBuffer class is faster while performing
concatenation operation. concatenation operation.

String class uses String constant pool. StringBuffer uses Heap memory

9. What is the difference between constructor and methods?

Key Constructors Methods

Purpose Constructor is used to create and Method is used to


initialize an Object. execute certain
statements.

Invocation A constructor is accessed implicitly by A method is to be


the System. accessed during program
code.

Invocation A constructor is invoked when new A method is invoked


keyword is used to create an object. when it is called.

Return type A constructor cannot have any return A method can have a
type. return type.

Object A constructor initializes an object which A method can be invoked


is not existent. only on existing object.

Name A constructor must have same name as A method name cannot


that of the class. be same as class name.

Inheritance A constructor cannot be inherited by a A method is inherited by a


subclass. subclass.
10. Difference between class and abstract class?

Abstract Class class

Abstract class can have both an abstract A class can only have
as well as concrete methods. concrete methods.

We cannot create object for abstract class class can be created


object using new
keyword.

Abstract class may or may not have class cannot have an


abstract methods. abstract method.

Abstract class cannot be declared as a class can be declared


final class. final.

Abstract class declared using abstract class is not having


keyword. abstract keyword during
declaration.

Abstract class can inherit another class Interface can inherit


using extends keyword and implement an only an interface.
interface.

Abstract class cannot implement an Interface can be


interface alone. A child class is needed to implemented easily.
be able to use the interface for
instantiation.
11. What is an object? How to create an object?
 A java object is an instance of a class.
 It is an entity which has states and behavior.
 The new keyword is used to create an object or instance of the class.
 new keyword allocates memory (heap) for the newly created object and also
returns the reference of that object to that memory.
 Syntax:
ClassName object = new ClassName();
 Example:
public class Demo
{
void show()
{
System.out.println("Welcome to java");
}
public static void main(String[] args)
{
//creating an object using new keyword
demo obj = new demo();
//invoking/accessing method using the object
obj.show();
}
}

12. What is explicit casting?


Converting of a higher data type into a lower data type is called explicit casting. Also
called as narrowing.
13. What is the difference between overloading and overriding?
Method overloading Method overriding

When more than one method having same When the method name and parameters
name with different parameters within the are same in the super class and the child
same class class is called overriding

It is compile time polymorphism It is run-time polymorphism

It occurs between the methods in the It occurs between superclass and sub class
same class
You can use any access modifier The access modifier of super class method
and subclass method must be same.

Higher performance Lesser performance

Inheritance is not required Inheritance is always needed


14. What is a vector?
A vector can be defined as a dynamic array that can grow or shrink on its own.
i.e. vector will grow when more elements are added to it and will shrink when elements
are removed from it.
15. Why strings are called as immutable?
If several references point to the same String without even knowing it, it would be bad if
one of the references modified that String value. That's why String objects are
immutable.(cannot be changed)
16. How is an array created in Java?
To create an array, you have to declare a variable with an array type and then create the
array itself.
Ex: int[] counts;
double[] values;
17. What is constructor? How constructor is overloaded?
 A constructor in Java is a special method that is used to initialize objects.
 The constructor is called when an object of a class is created.
 Constructors can be overloaded in a similar way as function overloading.
Overloaded constructors have the same name (name of the class) but the
different number of arguments.
18. What is inheritance? Explain types of Inheritance.
 Inheritance allows us to create a new class from an existing class.
 The new class that is created is known as subclass (child or derived class) and the
existing class from where the child class is derived is known as superclass (parent
or base class).
 To inherit from a class, use the extends keyword.
 Syntax:
class superclass
{
// superclass data variables
// superclass member functions
}
class subclass extends superclass
{
// subclass data variables
// subclass member functions
}
 Types of inheritance

 Single Inheritance: When a class inherits another class, it is known as a


single inheritance.
Example:
class A
{
int a, b;
void display()
{
System.out.println(“Inside class A values =”+a+” ”+b);
}
}
class B extends A
{
int c;
void show()
{
System.out.println(“Inside Class B values=”+a+” “+b+” “+c);
}
}
class SingleInheritance
{
public static void main(String args[])
{
B obj = new B(); //derived class object
obj.a=10;
obj.b=20;
obj.c=30;
obj.display();
obj.show();
}
}
 Multi-level Inheritance: one sub class inheriting from one super class
and the super class is inheriting form another super class is called
multilevel inheritance.
 Example:

 Multiple inheritance: one subclass inheriting from two or more super


class is called as multiple inheritance. JAVA doesn’t support multiple
inheritance
 Hierarchical Inheritance:
 One super class extends by two or more subclass is called as
hierarchical inheritance.
 Using hierarchical inheritance we can achieve generalization
 Defining the common methods and variables of sub class in one
super class is called generalization.
19. What is vector? Mention its advantages over an array.
A vector can be defined as a dynamic array that can grow or shrink on its own.
Advantages:
 A vector is a dynamic array, whose size can be increased.
 Reserve space can be given for vector.
 A vector is a class whereas an array is a data type.
 Vectors can store any type of objects, whereas an array can store only same type
of values.
20. What is method overriding? Write a program to demonstrate method overriding.
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
Rules for Java Method Overriding
 The method must have the same name as in the parent class
 The method must have the same parameter as in the parent class.
 There must be an IS-A relationship (inheritance).
Ex:
class Vehicle
{
void run()
{
333System.out.println("Vehicle is running"); //defining a method

}
}
//Creating a child class
class Bike2 extends Vehicle
{
//defining the same method as in the parent class
void run()
{
System.out.println("Bike is running safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2(); //creating object
obj.run(); //calling method
}
}
21. What is string and Explain string methods with example.
 A string is an object that represents a sequence of characters or char values.
 The java.lang.String class is used to create a Java string object.
 There are two ways to create a String object:
 string literal : Java String literal is created by using double quotes.
Example: String s=“Welcome”;
 new keyword : Java String is created by using a keyword “new”.
Example: String s=new String(“Welcome”);
 Java String Methods
 Java String length(): The Java String length() method tells the length of
the string. It returns count of total number of characters present in the
String.
Example:
public class Example{
public static void main(String args[]
{
String s1="hello";
String s2="whatsup";
System.out.println("string length is: "+s1.length());
System.out.println("string length is: "+s2.length());
}
}
 Java String compareTo(): The Java String compareTo() method compares
the given string with current string. It is a method of ‘Comparable’
interface which is implemented by String class.
Example:
public class CompareToExample
{
public static void main(String args[])
{
String s1="hello";
String s2="hello";
String s3="hemlo";
String s4="flag";
System.out.println(s1.compareTo(s2)); // 0
System.out.println(s1.compareTo(s3)); //-1
System.out.println(s1.compareTo(s4)); // 2
}
}
 Java String concat() : The Java String concat() method combines a specific
string at the end of another string and ultimately returns a combined
string.
Example:
public class ConcatExample
{
public static void main(String args[])
{
String s1="hello";
s1=s1.concat("how are you");
System.out.println(s1);
}}
 Java String IsEmpty() : This method checks whether the String contains
anything or not.
Example:
public class IsEmptyExample
{
public static void main(String args[])
{
String s1="";
String s2="hello";
System.out.println(s1.isEmpty()); // true
System.out.println(s2.isEmpty()); // false
}}
 Java String Trim() : The java string trim() method removes the leading
and trailing spaces.
Example:
public class StringTrimExample
{
public static void main(String args[])
{
String s1=" hello ";
System.out.println(s1+"how are you"); // without
trim()
System.out.println(s1.trim()+"how are you"); // with trim()
}}
 Java String toLowerCase() : The java string toLowerCase() method
converts all the characters of the String to lower case.
Example:
public class StringLowerExample
{
public static void main(String args[])
{
String s1="HELLO HOW Are You?”;
String s1lower=s1.toLowerCase();
System.out.println(s1lower);}
}
}
 Java String toUpper() : The Java String toUpperCase() method converts
all the characters of the String to upper case.
Example:
public class StringUpperExample
{
public static void main(String args[])
{
String s1="hello how are you";
String s1upper=s1.toUpperCase();
System.out.println(s1upper);
}
}
22. Write a note on inheritance.
 It is a mechanism in which one object acquires all the properties and behaviors of a
parent object.
 When you inherit from an existing class, you can reuse methods and fields of the
parent class.
 We can add new methods and fields in your current class also.
 Inheritance represents the IS-A relationship which is also known as a parent-child
relationship.
Advantages:
 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates a new class that derives from an existing class.
The meaning of "extends" is to increase the functionality.
23. How to create object? What happens when you create objects?
 The new keyword is used to create an object or instance of the class.
 new keyword allocates memory (heap) for the newly created object and also
returns the reference of that object to that memory.
 Syntax:
ClassName object = new ClassName();

 When an object is created, memory is allocated to hold the object properties. An


object reference pointing to that memory location is also created. To use the
object in the future, that object reference has to be stored as a local variable or
as an object member variable.

24. Demonstrate ‘this’ keyword with simple java program.


class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}
class Test
{
public static void main(String args[])
{
Student s1=new Student(111,"narender",5000f);
Student s2=new Student(112,"varun",6000f);
s1.display();
s2.display();
}
}
25. Differentiate component and container class.
Container Component

The class container is the super class for the Component represents an object with
container of AWT graphical representation

Container is a window like component that A component is an object like a button or a


can contain other components scroll bar.

Examples: JPanel, JFrame, JApplet Examples: JLabel, JTextField, JButton

26. Illustrate array declaration and accessing data elements using an example.
public class ArrayDemo
{
public static void main(String[] args)
{
int[] anArray; // declare an array of integers

anArray = new int[10]; // create an array of integers

// assign a value to each array element and print


for (int i = 0; i < anArray.length; i++)
{
anArray[i] = i;
System.out.print(anArray[i] + " ");
}
System.out.println();
}
}
Output: 0 1 2 3 4 5 6 7 8 9
27. Write a program to sort a list of elements in ascending order.
import java.util.Scanner;
public class Ascending _Order
{
public static void main(String[] args)
{
int n, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("Ascending Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
}
}
28. Explain with example:
1. Method overloading
 If a class has more than one methods having same name but different
parameters, it is known as Method Overloading.
 It increases readability of the program.(advantage of method overloading)
 Method overloading done within the same class
 Overloaded method can have different access modifiers and it does not have any
significance in method overloading.
 There are two different ways of method overloading.
1. Different datatype of arguments
2. Different number of arguments
 Different datatype of arguments: the same class we have two methods with
same name but different types of parameters.
 Example:
class Calculate
{
void sum (int a, int b)
{
System.out.println("sum is"+(a+b)) ;
}
void sum (float a, float b)
{
System.out.println("sum is"+(a+b));
}
Public static void main (String[] args)
{
Calculate cal = new Calculate();
cal.sum (8,5); //sum(int a, int b) is method is called.
cal.sum (4.6f, 3.8f); //sum(float a, float b) is called.
}
}
 Different number of arguments: the same class we have two methods with
same name but different types of parameters.
 Example:
class Demo
{
void multiply(int l, int b)
{
System.out.println("Result is"+(l*b)) ;
}
void multiply(int l, int b,int h)
{
System.out.println("Result is"+(l*b*h));
}
public static void main(String[] args)
{
Demo ar = new Demo();
ar.multiply(8,5); //multiply(int l, int b) is method is called
ar.multiply(4,6,2); //multiply(int l, int b,int h) is called
}
}
2. Abstract method.
 A method without body (no implementation) is known as abstract
method.
 An abstract method in Java is declared with the keyword “abstract”.

 A method must always be declared in an abstract class, i.e. if a class has
an abstract method, it should be declared abstract as well.
 This is how an abstract method looks in Java:
abstract public void display();
Rules of abstract method:

 Abstract methods don’t have body, they just have method signature.
 If a class has an abstract method it should be declared abstract, the vice versa is not
true, which means an abstract class doesn’t need to have an abstract method
compulsory.
 If a regular class extends an abstract class, then the class must have to implement all the
abstract methods of abstract parent class
Example:

abstract class Bike


{
abstract void run();
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}

3. Abstract class.
 A class which is declared with the abstract keyword is known as an abstract
class.
 It can have abstract and non-abstract methods (method with the body).
 It needs to be extended and its method implemented.
 It cannot be instantiated(objects cannot be created)
 Syntax:

abstract class A
{
Abstract void display()
{
}
}

Rules of Abstract Class:

 An abstract class must be declared with an abstract keyword.


 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods
Example:

abstract class Bike


{
abstract void run();
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}

29. Differentiate between arrays and vectors.

30. Explain visibility control in java.


 The access modifiers in Java specifies the accessibility or scope of a field,
method, constructor or class
 We can change the access level of fields, constructors, methods, and class by
applying the access modifier on it.
 There are four types of Java access modifiers:
I. Private:
 The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
 The private modifiers specifies the most restrictive access level, it
can apply it to methods and member variables.
 A top level class cannot be declared as private
 Example:
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
}
}

II. Default: The access level of a default modifier is only within the package.
It cannot be accessed from outside the package. If you do not specify any
access level, it will be the default.
Example:
package pack;
class A
{
void msg()
{
System.out.println(“Hello”);
}
}
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();//Compile Time Error
Obj.msg();//Compile Time Error
}
}
III. Protected: The access level of a protected modifier is within the package
and outside the package through child class. If you do not make the child
class, it cannot be accessed from outside the package.
package pack;
public class A
{
protected void msg()
{
System.out.println(“Hello”);
}
}
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
Obj.msg();
}
}
IV. Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package and
outside the package.
 Understanding Java Access Modifiers

Access within within outside outside


Modifier class package package package
by
subclass
only

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y
31. Explain array of object references.
 as name says it stores an array of objects.
 An array that conations class type elements are known as an array of objects. It stores
the reference variable of the object.
 Unlike a traditional array that store values like string, integer, Boolean, etc
 an array is a collection of the same data type that dynamically creates objects and can
have elements of primitive types. Java allows us to store objects in an array.

Creating an Array of objects

ClassName obj[]=new ClassName[array_length];


or
ClassName[] objArray;

32. Why multiple inheritances are not supported in Java?


 The reason behind this is to prevent ambiguity.
 Consider a case where class B extends class A and Class C and both class A and C
have the same method display().
 Now java compiler cannot decide which display method it should inherit. To
prevent such situation, multiple inheritances is not allowed in java.

33. What are the rules of method overriding?


Rules for Java Method Overriding
 The method must have the same name as in the parent class
 The method must have the same parameter as in the parent class.
 There must be an IS-A relationship (inheritance).

34. What is the use of finalize() method?


 The Finalize method is used to perform cleanup operations on unmanaged
resources held by the current object before the object is destroyed.
 The method is protected and therefore is accessible only through this class or
through a derived class.
35. What is wrapper class and How to create wrapper object?
 The wrapper class in Java provides the mechanism to convert primitive into
object and object into primitive.

Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

 We can create an instance(object) of Wrapper Classes by using a new operator.


 Example:

public class WrapperExample1


{
public static void main(String args[])
{
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer expl
icitly
Integer j=a:
System.out.println(a+" "+i+" "+j);
}
}

You might also like