Java25-Unit1and2-Shortnotes
Java25-Unit1and2-Shortnotes
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.
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"); } }
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.
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
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.
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!"); } }