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

Java25-Unit1and2-Shortnotes

The document provides an overview of Java programming, covering its definition, features, and key concepts such as JDK, JRE, JVM, bytecode, variables, data types, arrays, operators, objects, constructors, garbage collection, methods, and the 'this' keyword. It also discusses Java's platform independence, architecture neutrality, and the finalize() method, along with detailed explanations of mutable and immutable strings, String and StringBuffer classes, and control statements. Additionally, it introduces inheritance concepts, access specifiers, and types of inheritance in Java.

Uploaded by

rtkvinayagam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Java25-Unit1and2-Shortnotes

The document provides an overview of Java programming, covering its definition, features, and key concepts such as JDK, JRE, JVM, bytecode, variables, data types, arrays, operators, objects, constructors, garbage collection, methods, and the 'this' keyword. It also discusses Java's platform independence, architecture neutrality, and the finalize() method, along with detailed explanations of mutable and immutable strings, String and StringBuffer classes, and control statements. Additionally, it introduces inheritance concepts, access specifiers, and types of inheritance in Java.

Uploaded by

rtkvinayagam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Java Programming [23UCSCC43 / 23UBCAC43 ]

Unit – I
1. What is Java?
ava is a programming language and computing platform that's used to create applications for many
devices, including smartphones, desktops, and servers. It's a popular choice for developers because
it's fast, secure, and reliable.
Features
• Multi-platform: Java runs on many different operating systems, including Windows, macOS,
and Linux
• Object-oriented: Java is based on the concept of objects
• Network-centric: Java is well-suited for coding applications that use the internet
• Garbage collector: Java automatically frees memory when objects are no longer in use
2. What are the features of java?
1. Simple 7. Architecture neutral
2. Object-Oriented 8. Interpreted
3. Portable 9. High Performance
4. Platform independent 10. Multithreaded
5. Secured 11. Distributed
6. Robust 12. Dynamic
3. Difference between JDK, JRE, and JVM.
JDK is abbreviated as Java Development Kit which has a physical existence. It can be considered as a
kit inside which resides the JRE along with developing tools within it. The programmers and
developers mostly use it.
JVM is abbreviated as Java Virtual Machine, is basically a dummy machine or you can say an abstract
machine which gives Java programmers a runtime environment for executing the Bytecode. For each
execution of your program, the JDK and JRE come into use, and they go within the JVM to run the Java
source code.
JRE is abbreviated as Java Runtime Environment, as the name suggests used as a package that gives
an environment to run the Java program on your machine
4. What is bytecode?
Bytecode is a highly optimized set of instructions designed to be executed by the java run-time
system. Which is called the java virtual machine (JVM). JVM is an interpreter for bytecode.
5. What is a variable? What are the different types of variables? [Remembering]
Variable are locations in the memory that can hold values. Java has three kinds of variable namely,
Instance variable , Local variable , & Class variable
Local variables are used inside blocks as counts or in methods as temporary variables. Once the
block or the method is executed, the variable ceases to exist.
Instance variable are used to define attributes or the state of a particular object. These are used to
store information needed by multiple methods in the objects.
6. What are the difference between static variable and instance variable?
The data or variables, defined within a class are called instance variables.
Instance variables declared as static are, essentially, global variables. When objects of its class are
declared, no copy of a static variable is made.
7.What are primitive datatypes in java?
There are 8 types of primitive data types:
Java Programming [23UCSCC43 / 23UBCAC43 ]
1. boolean data type 4. short data type 7. float data type
2. byte data type 5. int data type 8. double data type
3. char data type 6. long data type
8. Define Array? How to declare an array?
Java array is an object which contains elements of a similar data type. It is a data structure where we
store similar elements. We can store only a fixed set of elements in a Java array.
There are two types of array.
1. Single Dimensional Array
2. Multidimensional Array
int a[]=new int[5];
int b[][]=new int[3][3];
9. List out the operator in Java.
1. Arithmetic Operators 4. Relational Operators
2. Increment and Decrement Operators 5. Logical Operators
3. Bitewise Operators 6. Assignment Operators
10.what is object?
An object is an instance of a class. A class is a template or blueprint from which objects are created.
So, an object is the instance(result) of a class.
1. An object is a real-world entity.
2. An object is a runtime entity.
3. The object is an entity which has state and behavior.
4. The object is an instance of a class.
11.Define Construcor?
Constructor in java is a special type of method that is used to initialize the object. Java constructor is
invoked at the time of object creation. It constructs the values i.e. provides data for the object that is
why it is known as constructor.
12. What are the Types of java constructors?
There are two types of constructors: 1. Default constructor (no-arg constructor) 2. Parameterized
constructor
13.What is meant by garbage collection?
It frees memory allocated to objects that are not being used by the program any more - hence the
name "garbage".In certain languages like C++, dynamically allocated objects must be manually
released by use of a delete operator. In Java deallocation happens automatically. The technique that
accomplishes this is called garbage collection.
14.Define method?
Methods are functions that operates on instances of classes in which they are defined. Objects can
communicate with each other using methods and can call methods in other classes. Just as there are
class and instance variable, there are class and instance methods. Instance methods apply and
operate on an instance of the class while class methods operate on the class.
15. What is the use of ‘this’ Keyword?
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
Java Programming [23UCSCC43 / 23UBCAC43 ]
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
16. What gives java it’s “write once and run anywhere” nature?
All Java programs are compiled into class files that contain byte codes. These byte codes can be run
in any platform and hence java is said to be platform independent.
17. Why Java is Platform Independent.
Java is platform independent because it can run on any platform i.e on windows,mac etc. ... Because
it contains its own virtual machine which have JRE which runs java program as byte code. You may
have different JRE for differentplatforms .Once you installed it in your system you can run any java
application on it.
18. Why Java is Architecture-Neutral.
Java was designed to support applications on networks. To enable a Javaapplication to execute
anywhere on the network, the compiler generates anarchitecture-neutral object file format--the
compiled code is executable on many processors, given the presence of the Java runtime system
19 .What is finalize() method?
Finalize () method is used just before an object is destroyed and can be called just prior to garbage
collection.
20. Define Scope & Lifetime of Variables.
Scope of a variable refers to in which areas or sections of a program can the variable be accessed
and lifetime of a variable refers to how long the variable stays alive in memory.
21. What is Type Conversion & casting?
Type casting is a technique that is used either by the compiler or a programmer to convert one data
type to another in Java. Type casting is also known as type conversion. For example, converting int
to double, double to int, short to int, etc.
There are two types of type casting allowed in Java programming:
• Widening type casting / Implicit Type Conversion
• Narrowing type casting / Explicit Type Conversion
byte > short > char > int > long > float > double - Widening
double > float > long > int > char > short > byte - Narrowing
22. Write the structure of Java Program.

23. What is a static block in Java?


A static block in Java is a set of instructions that runs once when a class is loaded into memory. It's
also known as a static initialization block.
Java Programming [23UCSCC43 / 23UBCAC43 ]
• The Java Virtual Machine (JVM) automatically calls static blocks when the class is loaded.
• Static blocks are executed before the object initialization.
• Static blocks are used to initialize static variables or to call a static method.
• A class can have multiple static blocks, which will execute in the order they appear in the
source code.
24. What are static data and static methods?
Whenever a variable is declared as static, this means there is only one copy of it for the entire class,
rather than each instance having its own copy.
A static method means it can be called without creating an instance of the class.
25. What is String Class?
String is a sequence of characters. The String class represents character strings. All string literals in
Java programs, such as "abc" , are implemented as instances of this class. Strings are constant & their
values cannot be changed after they are created.
public class StringDemo {
public static void main(String args[]) {
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println( helloString ); } }
26. What is StringBuffer Class?
StringBuffer is mutable, its content can be changed through its append(), insert() etc methods.
StringBuffer operations are mutable and don't create new objects on each operation.
27. Write the StringBuffer Class Constructors.
Following is the list of constructors of the StringBuffer class.
Sr.No. Constructor & Description
1 StringBuffer()
This constructs a string builder with no characters in it and an initial capacity of 16
characters.
2 StringBuffer(CharSequence seq)
This constructs a string builder that contains the same characters as the specified
CharSequence.
3 StringBuffer(int capacity)
This constructs a string builder with no characters in it and an initial capacity specified
by the capacity argument.
4 StringBuffer(String str)
This constructs a string builder initialized to the contents of the specified string.

28. What are the methods of StringBuffer Class?


Method Description
append(String s) It is used to append the specified string with this string. The append()
method is overloaded like append(char), append(boolean),
append(int), append(float), append(double) etc.
insert(int offset, String s) It is used to insert the specified string with this string at the specified
position. The insert() method is overloaded like insert(int, char),
Java Programming [23UCSCC43 / 23UBCAC43 ]
insert(int, boolean), insert(int, int), insert(int, float), insert(int,
double) etc.
replace(int startIndex, int It is used to replace the string from specified startIndex and endIndex.
endIndex, String str)
delete(int startIndex, int It is used to delete the string from specified startIndex and endIndex.
endIndex)
reverse() is used to reverse the string.
capacity() It is used to return the current capacity.
charAt(int index) It is used to return the character at the specified position.
length() It is used to return the length of the string i.e. total number of
characters.
substring(int beginIndex, It is used to return the substring from the specified beginIndex and
int endIndex) endIndex.

29. What is a mutable String?


A String that can be modified or changed is known as mutable String. StringBuffer and StringBuilder
classes are used for creating mutable strings.
30. What are the Constructors of String Class?
Constructor
String() - Initializes a newly created String object so that it represents an empty character
sequence.
String(byte[] bytes) - Construct a new String by converting the specified array of bytes using the
platform's default character encoding.
String(char[] value) - Allocates a new String so that it represents the sequence of characters
currently contained in the character array argument.
String(String value) - Initializes a newly created String object so that it represents the same
sequence of characters as the argument; in other words, the newly created string is a copy of the
argument string.

31. What are the important methods of String Class?


Methods
char charAt(int index) - Returns the character at the specified index.
int compareTo(String anotherString) - Compares two strings lexicographically.
String concat(String str) - Concatenates the specified string to the end of this string.
int indexOf(int ch, int fromIndex) - Returns the index within this string of the first
occurrence of the specified character, starting the search at the specified index.
int indexOf(String str) - Returns the index within this string of the first occurrence of
the specified substring.
int length() - Returns the length of this string.
String replace(char oldChar, char newChar) - Returns a new string resulting from replacing
all occurrences of oldChar in this string with newChar.
String substring(int beginIndex, int endIndex)- Returns a new string that is a substring of
this string.
char[] toCharArray() - Converts this string to a new character array.
Java Programming [23UCSCC43 / 23UBCAC43 ]
String toLowerCase() - Converts all of the characters in this String to lower case.
String toString() - This object (which is already a string!) is itself returned.
String toUpperCase() - Converts all of the characters in this String to upper case.
String trim() - Removes white space from both ends of this string.

What are control statements?


A programming language uses control statements to control the flow of execution of a program
based on certain conditions. These are used to cause the flow of execution to advance and branch
based on changes to the state of a program.
Write the syntax and example for simple if
It is used to decide whether a certain statement or block of statements will be executed or not i.e. if a
certain condition is true then a block of statements is executed otherwise not.
Syntax: Flow Chart Example
if(condition) int i=10;
{ if (i < 15) {
coding { System.out.println("Inside If block"); }
} System.out.println("10 is less than 15");

• If the condition is True statement1 executes.


• statement2 runs no matter what because it’s not a part of the if block
Java Programming [23UCSCC43 / 23UBCAC43 ]
Unit 2
1. What is inheritance?
In Object-Oriented programming, inheritance refers to the properties of a class being available to
many other classes. A derived class / sub class is one that has been created from an existing class.
Inheritance is the process of deriving a class from a super class or a base class. No changes are made
to the base class. The derived class has a larger set of properties that its base class. Inheritance has
two advantages
a) Reusability of code
b) Data and methods of a super class are physically available to its subclasses
2. What is a base class?
Base class is the most generalised class in a class structure. Most applications have such root classes.
In Java, Object is the base class for all classes.
3. Define super class and subclass?
Superclass is a class from which another class inherits. Subclass is a class that inherits from one or
more classes.
4. What are the types of inheritance?
1. Single Inheritance
2. Multiple Inheritance (Through Interface)
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance (Through Interface).
5. Define an access specifier ?give example.
Java provides a number of access modifiers to set access levels for classes, variables, methods
and constructors. The four access levels are:
• Visible to the package. The default. No modifiers are needed.
• Visible to the class only (private).
• Visible to the world (public).
• Visible to the package and all subclasses (protected)
6. How to Use Inheritance in Java?
The extends keyword is used for inheritance in Java. Using the extends keyword indicates you are
derived from an existing class. In other words, “extends” refers to increased functionality.
Syntax :
class DerivedClass extends BaseClass
{
//methods and fields
// coding
}
7. Write about Single inheritance.
In single inheritance, a sub-class is derived from only one super class. It inherits the properties and
behavior of a single-parent class. Sometimes, it is also known as simple inheritance. The class ‘B’
inherits all the properties of the class ‘A’.
Example :Single inheritance public class Main {
Java Programming [23UCSCC43 / 23UBCAC43 ]
import java.io.*; public static void
import java.lang.*; main(String[] args) {
import java.util.*; Two g = new Two();
// Parent class g.show();
class One { g.display(); } }
public void show()
{ System.out.print("Hello "); } }
class Two extends One { Output : Hello Everyone
public void display()
{ System.out.print("Everyone"); } }
8. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived
class also acts as the base class for other classes. In the below image, class A serves as a base class for
the derived class B, which in turn serves as a base class for the derived class C. In Java, a class cannot
directly access the grandparent’s members.

Multilevel Inheritance class Three extends Two {


import java.io.*; public void printall() {
import java.lang.*; System.out.println(" Welcome");
import java.util.*; }}
// Parent class One public class Main {
class One { public static void main(String[]
public void show() { args) {
System.out.print("Hello "); } } Three g = new Three();
class Two extends One { g.show();
public void display() { g.display();
System.out.print("Everyone "); g.printall(); } }
}} Output
Hello Everyone Welcome

9. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass.
In the below image, class A serves as a base class for the derived classes B, C, and D.
public class Test {
public static void main(String[] args) {
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();
C obj_C = new C();
obj_C.print_A();
obj_C.print_C();
D obj_D = new D();
class A {
obj_D.print_A();
public void print_A()
obj_D.print_D(); } }
Java Programming [23UCSCC43 / 23UBCAC43 ]
{ System.out.println("Class A"); } } Output
class B extends A { Class A
public void print_B() Class B
{ System.out.println("Class B"); } } Class A
class C extends A { Class C
public void print_C() Class A
{ System.out.println("Class C"); } } Class D
class D extends A {
public void print_D()
{ System.out.println("Class D"); } }

10. How can we achieve multiple inheritance in java?


Way to achieve multiple inheritance through interfaces in java. class A extends B, C // this is not
possible in java directly but can be achieved indirectly. We can implement both of these using the
code below... We CANNOT extend two objects, but we can implement two interfaces.
11. What are Advantages Of Inheritance in Java?
1. Code Reusability: Inheritance allows for code reuse and reduces the amount of code that
needs to be written. The subclass can reuse the properties and methods of the superclass,
reducing duplication of code.
2. Abstraction: Inheritance allows for the creation of abstract classes that define a common
interface for a group of related classes. This promotes abstraction and encapsulation, making
the code easier to maintain and extend.
3. Class Hierarchy: Inheritance allows for the creation of a class hierarchy, which can be used to
model real-world objects and their relationships.
4. Polymorphism: Inheritance allows for polymorphism, which is the ability of an object to take
on multiple forms. Subclasses can override the methods of the superclass, which allows them
to change their behaviour in different ways.
12. What are the Disadvantages of Inheritance in Java?
1. Complexity: Inheritance can make the code more complex and harder to understand. This is
especially true if the inheritance hierarchy is deep or if multiple inheritances is used.
2. Tight Coupling: Inheritance creates a tight coupling between the superclass and subclass,
making it difficult to make changes to the superclass without affecting the subclass.
13. What are access modifiers?
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:
1. Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
2. 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.
3. 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.
Java Programming [23UCSCC43 / 23UBCAC43 ]
4. 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.
14. What is the use of ‘this’ keyword? and its Usage.
The this keyword refers to the current object in a method or constructor.
The most common use of the this keyword is to eliminate the confusion between class attributes and
parameters with the same name (because a class attribute is shadowed by a method or constructor
parameter). If you omit the keyword in the example above, the output would be "0" instead of "5".
‘this’ can also be used to:
• Invoke current class constructor
• Invoke current class method
• Return the current class object
• Pass an argument in the method call
• Pass an argument in the constructor call
Example:
public class Main {
int x;
public Main(int x)
{ this.x = x; }
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println("Value of x = " + myObj.x); } }
Output : 5
15. Definition and Usage of ‘super’ keyword
The super keyword refers to superclass (parent) objects.
It is used to call superclass methods, and to access the superclass constructor.
The most common use of the super keyword is to eliminate the confusion between super classes and
sub classes that have methods with the same name.
Example:
class Animal { // Superclass (parent)
public void animalSound()
{ System.out.println("The animal makes a sound"); } }
class Dog extends Animal { // Subclass (child)
public void animalSound()
{ super.animalSound(); // Call the superclass method
System.out.println("The dog says: bow wow"); } }
public class Main {
public static void main(String args[]) {
Animal myDog = new Dog(); // Create a Dog object
myDog.animalSound(); // Call the method on the Dog object } }
Output: The animal makes a sound
The dog says: bow wow
15b. What is the use of ‘Super’ Keyword? Give an example.
Usage of ‘super’ keyword’
1. The first calls the superclass constructor
Java Programming [23UCSCC43 / 23UBCAC43 ]
2. To access a member of the superclass that has been hidden by a member of a subclass
16. Can you use this () and super () both in a constructor?
We cannot have two statements as first statement, so we either need to call super() or this() but
not the both. We can't use both the keywords in the constructor. In Java there is a rule that this()
and super() must be first statement in the constructor. So we can't use both together in a
constructor.
17. What is Polymorphism?
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.
Types of Polymorphism : There are two types of polymorphism in Java:
1. Compile-time Polymorphism
2. Runtime Polymorphism.
18. What is Static [Compile-time] Polymorphism?
• Static Polymorphism is also known as compile time binding or early binding.
• Static binding happens at compile time.
• Method overloading is an example of static binding where binding of method call to its
definition happens at Compile time.
19. Define method overloading?
In Java it is possible to define two or more methods within the same class that share the same name,
as long as their parameter declarations are different. When this is the case, the methods are said
to be overload, and the process is referred to as method overloading.
Example:
class Calculation {
int add(int a, int b)
{ return a + b; }
double add(double a, double b)
{ return a + b; } }
public class Main {
public static void main(String[] args) {
Calculation calc = new Calculation();
System.out.println("Sum of integers: " + calc.add(5, 3));
System.out.println("Sum of doubles: " + calc.add(2.5, 3.7)); } }
Output:
Sum of integers: 8
Sum of doubles: 6.2
20. What are the 3 ways of Overloading Method?
• Different Number of parameters in argument list.
• Difference in data type of arguments.
• Sequence of data type of arguments
21. What is Runtime Polymorphism in Java?
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time.
Java Programming [23UCSCC43 / 23UBCAC43 ]
In this process, an overridden method is called through the reference variable of a superclass.
The determination of the method to be called is based on the object being referred to by the
reference variable.
Example:
class Bike{
void run(){System.out.println("running");} }
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");} }
public class Main{
public static void main(String args[]){
Bike b = new Splendor();//upcasting
b.run(); } }
Output: running safely with 60km.

22. What is ?Overriding in Java


Overriding in Java occurs when a subclass implements a method which is already defined in
the superclass or Base Class. The method in the subclass must have the same signature as in
the superclass. It allows the subclass to modify the inherited methods.
Example:
class Animal {
// Base class
void move() { System.out.println( "Animal is moving."); }
void eat() { System.out.println( "Animal is eating."); } }
class Dog extends Animal {
@Override void move()
{ // move method from Base class is overriden in this method
System.out.println("Dog is running."); }
void bark() { System.out.println("Dog is barking."); } }
public class runpoly {
public static void main(String[] args) {
Dog d = new Dog();
d.move(); // Output: Dog is running.
d.eat(); // Output: Animal is eating.
d.bark(); // Output: Dog is barking. }
}
Output : Dog is running.
Animal is eating.
Dog is barking.
Java Programming [23UCSCC43 / 23UBCAC43 ]

23. What are the rules for 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).
22. What are the Advantages of Polymorphism?
1. Code Reusability : Polymorphism allows methods in subclasses to override methods in their
superclass, enabling code reuse and maintaining a consistent interface across related classes.
2. Flexibility and Extensibility : Polymorphism allows subclasses to provide their own
implementations of methods defined in the superclass, making it easier to extend and customize
behavior without modifying existing code.
3. Dynamic Method Invocation: Polymorphism enables dynamic method invocation, where the
method called is determined by the actual object type at runtime, providing g flexibility in method
dispatch.
4. Interface Implementation: Interfaces in Java allow multiple classes to implement the same
interface with their own implementations, facilitating polymorphic behavior and enabling objects of
different classes to be treated interchangeably based on a common interface.
5. Method Overloading: Polymorphism is also achieved through method overloading, where
multiple methods with the same name but different parameter lists can be defined within a class or
its subclasses, enhancing code readability and allowing flexibility in method invocation based on
parameter types.
6. Reduced Code Complexity: Polymorphism helps reduce code complexity by promoting a
modular and hierarchical class structure, making it easier to understand, maintain, and extend large-
scale software systems.

23. Difference between method overloading and method overriding in java.


Overloading Overriding

Whenever same method or Constructor is Whenever same method name is existing


existing multiple times within a class either multiple time in both base and derived class
with different number of parameter or with with same number of parameter or same type
different type of parameter or with different of parameter or same order of parameters is
order of parameter is known as Overloading. known as Overriding.
Arguments of method must be different at least Argument of method must be same including
arguments. order.
Method signature must be different. Method signature must be same.

Private, static and final methods can be Private, static and final methods can not be
overloaded. override.
Access modifiers point of view no restriction. Access modifiers point of view not reduced
scope of Access modifiers but increased.
Java Programming [23UCSCC43 / 23UBCAC43 ]
24.Define abstract class?
Abstract classes are classes from which instances are usually not created. It is basically used to
contain common characteristics of its derived classes. Abstract classes are generally higher up the
hierarchy and act as super classes. Methods can also be declared as abstract. This implies that
non-abstract classes must implement these .
Ways to achieve Abstraction : There are two ways to achieve abstraction in Java:
1. Using Abstract Class (0 to 100%)
2. Using Interface (100%)
24. What is meant by an innerclass? .
An inner class is a nested class whose instance exists within an instance of its enclosing class
and has direct access to the instance members of its enclosing instance
class <EnclosingClass>
{
class <InnerClass> { }
}
25. What are the uses of the keyword ‘final’?
• The class can be declared as final, if instances or subclasses are not to be created.
• The variables are declared as final, value of the variable must be provided at the time
of declaration.
• The Method can be declared as final indicating that they cannot be overridden by subclasses.
26. What are static methods?
Static methods and variables can be used independently of any object. To do so, you need only
specify the name of their class following by the dot operator.
27. What is constructor overloading.
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a different
task. They are differentiated by the compiler by the number of parameters in the list and their
types.
28. How to pass object as argument in java?
1. We can pass Object of any class as parameter to a method in java.
2. We can access the instance variables of the object passed inside the called method.
3. 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.
29. List Access Specifiers in java.
Java Access Specifiers (also known as Visibility Specifiers ) regulate access to classes, fields and
methods in Java. There are 4 types of java access modifiers:
1. private
2. default
3. protected
4. public
30. How can we achieve multiple inheritance in java?
Way to achieve multiple inheritance through interfaces in java. class A extends B, C // this is
not possible in java directly but can be achieved indirectly. We can implement both of these
Java Programming [23UCSCC43 / 23UBCAC43 ]
using the code below... We CANNOT extend two objects, but we can implement two
interfaces.
31. What is meant by Nested Class?
Class within another class, such classes are known as nested classes. Nested classes are divided into
two categories:
1. static nested class : Nested classes that are declared static are called static nested classes.
2. inner class : An inner class is a non-static nested class.
32. What is abstract class?
Abstract class is declared with the abstract keyword. It may have both abstract and non-abstract
methods(methods with bodies). An abstract is a Java modifier applicable for classes and methods in
Java but not for Variables. Java abstract class is a class that can not be instantiated by itself, it needs
to be subclassed by another class to use its properties.
Example:
abstract class Shape
{
int color;
// An abstract function
abstract void draw();
}
33. What are the rules to be followed in abstract class?
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the method.
34. Give an example program for abstract class.
abstract class Bike{ abstract void run(); }
class Honda extends Bike{
void run(){System.out.println("running safely");} }
public class Main{
public static void main(String args[]){
Bike obj = new Honda();
obj.run(); } }
35. What is the use of final Keyword In Java
The final keyword in Java is used to restrict the user. The java final keyword can be used in many
context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final
variable that have no value it is called blank final variable or
uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the static block
only.
Java Programming [23UCSCC43 / 23UBCAC43 ]
36. What is mean by Java final variable?
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.
Example
class Bike{
final int speedlimit=90;//final variable
void run(){ speedlimit=400;//we cannot change the final variable }
public static void main(String args[]){
Bike obj=new Bike();
obj.run(); } }//end of class
Output:
Compile Time Error
37. What is meant by Java final method?
If you make any method as final, you cannot override it.
Example
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
38. What is Java final class?
If you make any class as final, you cannot extend it.
Example
final class Bike{}
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
39. What is package?
A Java package is a group of similar types of classes, interfaces and sub-packages. Packages in java
can be categorized in two forms, built-in packages and user-defined packages. There are many built-
in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
40. What are the Advantages of Java Package?
• Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
• Java package provides access protection.
Java Programming [23UCSCC43 / 23UBCAC43 ]
• Java package removes naming collision.

41. Give an example for package.


The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
42. How to compile java package
Syntax: javac -d directory javafilename
For example : javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep
the package within the same directory, you can use . (dot).
43. How to run java package program
Use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination.
The . represents the current folder.
44. How to import [access] package from another package?
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to the
current package.
Java Programming [23UCSCC43 / 23UBCAC43 ]
Example of package that import the packagename.*
//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
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
//save by A.java
package pack;
public class A{ public void msg(){System.out.println("Hello");} }
//save by B.java
package mypack;
import pack.A;
class B{ public static void main(String args[]) {
A obj = new A();
obj.msg(); } }
Output: Hello
45. What is an interface?
An interface in Java is a blueprint of a class. It has static constants and abstract methods. The interface
in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface,
not method body. It is used to achieve abstraction and multiple inheritance in Java. Interfaces can
have abstract methods and variables. It cannot have a method body.
o Java Interface also represents the IS-A relationship.
o It cannot be instantiated just like the abstract class.
o Interface can have default and static methods.
o Interface can have private methods.
46. Why use Java interface?
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
47. How to declare an interface?
An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and final
by default. A class that implements an interface must implement all the methods declared in the
interface.
Java Programming [23UCSCC43 / 23UBCAC43 ]

Syntax: Example:
interface <interface_name>{ interface Animal {
// declare constant fields void eat();
// declare methods that abstract void sleep();
// by default. } }
48. How will you implement interface?
In this example, the Drawable interface has only one method. Its implementation is provided by
Rectangle and Circle classes. In a real scenario, an interface is defined by someone else, but its
implementation is provided by different implementation providers. Moreover, it is used by someone
else. The implementation part is hidden by the user who uses the interface.
Example
//Creating an interface
interface Drawable{ void draw(); }
//Implementation of Interface
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");} }
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");} }
//Using interface
public class Main{
public static void main(String args[]){
Drawable d=new Circle();
d.draw(); } }
Output: drawing circle

49. Multiple Inheritance in Java by Interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as
multiple inheritance.
Example
//Creating two interfaces
interface Printable{
void print(); }
interface Showable{
void show(); }

//Creating a class that implements two interfaces


class Computer implements Printable,Showable{
public void print(){System.out.println("printing data...");}
public void show(){System.out.println("showing data...");} }
//Creating a Main class to create object and call methods
public class Main{
public static void main(String args[]){
Computer c = new Computer();
c.print(); c.show(); } }
Java Programming [23UCSCC43 / 23UBCAC43 ]
Output:
printing data...
showing data...
50. Extending Interface or Interface inheritance
A class implements an interface, but one interface extends another interface.
Example:
interface Printable{ void print(); }
interface Showable extends Printable{
void show(); }
class TestInterface implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
TestInterface obj = new TestInterface();
obj.print();
obj.show(); } }
Output:
Hello
Welcome
51. Explain Java Runnable Interface.
Java runnable is an interface used to execute code on a concurrent thread. It is an interface which is
implemented by any class if we want that the instances of that class should be executed by a thread.
The runnable interface has an undefined method run() with void as return type, and it takes in no
arguments. The method summary of the run() method is given below-
Method Description
public void run() This method takes in no arguments. When the object of a class implementing
Runnable class is used to create a thread, then the run method is invoked in
the thread which executes separately.
• The runnable interface provides a standard set of rules for the instances of classes which wish to
execute code when they are active.
• The most common use case of the Runnable interface is when we want only to override the run
method.
• When a thread is started by the object of any class which is implementing Runnable, then it
invokes the run method in the separately executing thread.
• A class that implements Runnable runs on a different thread without subclassing Thread as it
instantiates a Thread instance and passes itself in as the target.
• This interface is present in java.lang package.
Implementing Runnable
It is the easiest way to create a thread by implementing Runnable. One can create a thread on any
object by implementing Runnable. To implement a Runnable, one has only to implement the run
method.
public void run() : The run method establishes an entry point to a new thread.
Example:
Runnable runnable = new MyRunnable();
Java Programming [23UCSCC43 / 23UBCAC43 ]
Thread thread = new Thread(runnable);
thread.start();
The thread will execute the code which is mentioned in the run() method of the Runnable object
passed in its argument.
A simple thread example using runnable
public class ExampleClass implements Runnable {
@Override
public void run() {
System.out.println("Thread has ended"); }
public static void main(String[] args) {
ExampleClass ex = new ExampleClass();
Thread t1= new Thread(ex);
t1.start();
System.out.println("Hi"); } }

Output: Hi Thread has ended

52 What is an exception?
An exception (or exceptional event) is a problem that arises during the execution of a program. When
an Exception occurs the normal flow of the program is disrupted and the program/Application
terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.
53. Why Exception Occurs?
An exception can occur for many different reasons.
• A user has entered an invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications or the JVM has run out
of memory.
54 Java Exception Categories
1. Checked exceptions
2. Unchecked exceptions
3. Errors
54 What are Java Checked Exceptions?
A checked exception is an exception that is checked (notified) by the compiler at compilation-time,
these are also called as compile time exceptions. These exceptions cannot simply be ignored, the
programmer should take care of (handle) these exceptions.
Example:
import java.io.File;
import java.io.FileReader;
public class FilenotFound_Demo {
public static void main(String args[]) {
File file = new File("E://file.txt");
FileReader fr = new FileReader(file); } }

If you try to compile the above program, you will get the following exceptions.
Output
C:\>javac FilenotFound_Demo.java
Java Programming [23UCSCC43 / 23UBCAC43 ]
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be
caught or declared to be thrown
FileReader fr = new FileReader(file);
^
1 error
55. What are Java Unchecked Exceptions?
An unchecked exception is an exception that occurs at the time of execution. These are also called as
Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an
API. Runtime exceptions are ignored at the time of compilation.
Example:
public class Unchecked_Demo {
public static void main(String args[]) {
int num[] = {1, 2, 3, 4};
System.out.println(num[5]); } }
If you compile and execute the above program, you will get the following exception.
Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
56 What are Java Errors?
These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer. Errors are typically ignored in your code because you can rarely do anything about an
error.
For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of
compilation.
57 What the Keywords used in Exception?
Java provides five keywords that are used to handle the exception. The following table describes each.

Keyword Description

Try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block must be
followed by either catch or finally.

Catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by finally
block later.

Finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.

Throw The "throw" keyword is used to throw an exception.


Java Programming [23UCSCC43 / 23UBCAC43 ]

Throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always
used with method signature.

Example
//Java Program to understand the use of exception handling in Java
public class Main{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code..."); } }
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.
58 What is the use of Finally block in exception?
The finally statement lets you execute code, after try...catch, regardless of the result:
Example
public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished."); }
} }
The output will be:
Something went wrong.
The 'try catch' is finished.
59 What is the use of throw keyword?
The throw statement allows you to create a custom error.
The throw statement is used together with an exception type.
There are many exception types available in
Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityExc
eption, etc:
Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print "Access
granted":
public class Main {
static void checkAge(int age) {
if (age < 18) {
Java Programming [23UCSCC43 / 23UBCAC43 ]
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!"); } }

public static void main(String[] args) {


checkAge(15); // Set age to 15 (which is below 18...)
} }
The output will be:
Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at least 18
years old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)
60 Explain User-Defined Custom Exception in Java
In Java, an Exception is an issue (run time error) that occurred during the execution of a program.
When an exception occurred the program gets terminated abruptly and, the code past the line that
generated the exception never gets executed.
Java provides us the facility to create our own exceptions which are basically derived classes of
Exception. Creating our own Exception is known as a custom exception in Java or user-defined
exception in Java. Basically, Java custom exceptions are used to customize the exception according
to user needs. In simple words, we can say that a User-Defined Custom Exception or custom
exception is creating your own exception class and throwing that exception using the ‘throw’
keyword.
Example: In this example, a custom exception MyException is created and thrown in the program.
// A Class that represents user-defined exception
class MyException extends Exception {
public MyException(String m) {
super(m);
}
}
// A Class that uses the above MyException
public class setText {
public static void main(String args[]) {
try {
// Throw an object of user-defined exception
throw new MyException("This is a custom exception");
}
catch (MyException ex) {
System.out.println("Caught"); // Catch and print message
System.out.println(ex.getMessage()); }
} }
Output : Caught
This is a custom exception
Java Programming [23UCSCC43 / 23UBCAC43 ]

61 What is the use of throws Keyword?


Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print "Access
granted":
public class Main {
static void checkAge(int age) throws ArithmeticException {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!"); } }
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
} }
The throws keyword indicates what exception type may be thrown by a method.
There are many exception types available in
Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityEx
ception, etc.
Differences between throw and throws:
Throw throws
Used to throw an exception for a method Used to indicate what exception type may be thrown by
a method
Cannot throw multiple exceptions Can declare multiple exceptions
Syntax: Syntax:
• throw is followed by an object • throws is followed by a class
(new type) • and used with the method signature
• used inside the method
Java Programming [23UCSCC43 / 23UBCAC43 ]

You might also like