0% found this document useful (0 votes)
2 views77 pages

Java Programming

The document covers the foundations of Object-Oriented Programming (OOP) and Java, detailing principles such as encapsulation, inheritance, and polymorphism, along with Java-specific concepts like JDK, JRE, and JVM. It includes a series of questions and answers related to OOP principles, Java syntax, and programming constructs. Additionally, it explains the advantages of encapsulation, abstraction, and inheritance in enhancing code security, maintainability, and reusability.

Uploaded by

Maha Lakshmi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views77 pages

Java Programming

The document covers the foundations of Object-Oriented Programming (OOP) and Java, detailing principles such as encapsulation, inheritance, and polymorphism, along with Java-specific concepts like JDK, JRE, and JVM. It includes a series of questions and answers related to OOP principles, Java syntax, and programming constructs. Additionally, it explains the advantages of encapsulation, abstraction, and inheritance in enhancing code security, maintainability, and reusability.

Uploaded by

Maha Lakshmi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT-I

Foundations of OOP and Java: Principles of OOP – Java Development Kit(JDK) – Data Types,
Variables and Arrays – Operators – Control Statements –Classes & Objects – Constructors– Method
Overriding – Access specifiers – Static Members – Inheritance

1. OOP stands for


 A) Object Oriented Programming ✅
 B) Object Organized Programming
 C) Operating Oriented Programming
 D) Object Operating Process
2. Which is NOT an OOP principle?
 A) Encapsulation
 B) Inheritance
 C) Compilation ✅
 D) Polymorphism
3. Encapsulation means
 A) Wrapping data and methods together ✅
 B) Copying objects
 C) Executing methods
 D) Deleting objects
4. Which feature allows code reuse?
 A) Inheritance ✅
 B) Abstraction
 C) Encapsulation
 D) Compilation
5. Which OOP feature hides implementation details?
 A) Abstraction ✅
 B) Inheritance
 C) Objects
 D) Variables
6. Runtime polymorphism is achieved by
 A) Method Overriding ✅
 B) Method Overloading
 C) Constructor
 D) Static method
7. Compile-time polymorphism is achieved by
 A) Method Overloading ✅
 B) Method Overriding
 C) Constructor
 D) Class
8. An object is
 A) Instance of a class ✅
 B) Method
 C) Variable
 D) Package
9. Blueprint for creating objects is
 A) Class ✅
 B) Method
 C) Interface
 D) Variable
10. Which keyword creates an object?
 A) new ✅
 B) create
 C) object
 D) class
11. JDK stands for
 A) Java Development Kit ✅
 B) Java Design Kit
 C) Java Documentation Kit
 D) Java Data Kit
12. JRE stands for
 A) Java Runtime Environment ✅
 B) Java Ready Environment
 C) Java Runtime Editor
 D) Java Reading Environment
13. JVM stands for
 A) Java Virtual Machine ✅
 B) Java Variable Method
 C) Java Virtual Memory
 D) Java Visual Machine
14. Which compiles Java code?
 A) javac ✅
 B) java
 C) jvm
 D) jre
15. Which command runs Java bytecode?
 A) java ✅
 B) javac
 C) compile
 D) execute
16. Java source file extension is
 A) .java ✅
 B) .class
 C) .txt
 D) .exe
17. Bytecode extension is
 A) .class ✅
 B) .java
 C) .obj
 D) .exe
18. Which converts bytecode to machine code?
 A) JVM ✅
 B) JDK
 C) JRE
 D) Compiler
19. JDK contains
 A) JRE + Development tools ✅
 B) JVM only
 C) Compiler only
 D) Editor only
20. Java is
 A) Platform Independent ✅
 B) Platform Dependent
 C) OS Dependent
 D) Hardware Dependent
21. Which is NOT a primitive type?
 A) String ✅
 B) int
 C) float
 D) char
22. Size of int
 A) 4 bytes ✅
 B) 2 bytes
 C) 8 bytes
 D) 1 byte
23. Size of char
 A) 2 bytes ✅
 B) 1 byte
 C) 4 bytes
 D) 8 bytes
24. Boolean values are
 A) true/false ✅
 B) 0/1
 C) yes/no
 D) on/off
25. Default value of int instance variable
 A) 0 ✅
 B) 1
 C) null
 D) garbage
26. Which keyword declares constant?
 A) final ✅
 B) const
 C) static
 D) fixed
27. Array index starts from
 A) 0 ✅
 B) 1
 C) -1
 D) 2
28. Array size is
 A) Fixed ✅
 B) Dynamic
 C) Unlimited
 D) Variable
29. Which stores decimal numbers?
 A) float ✅
 B) char
 C) boolean
 D) byte
30. Which stores single character?
 A) char ✅
 B) String
 C) int
 D) byte
31. Assignment operator
 A) = ✅
 B) ==
 C) !=
 D) +=
32. Equality operator
 A) == ✅
 B) =
 C) !=
 D) <=
33. Logical AND operator
 A) && ✅
 B) &
 C) ||
 D) !
34. Logical OR operator
 A) || ✅
 B) &&
 C) &
 D) ^
35. Increment operator
 A) ++ ✅
 B) --
 C) **
 D) %
36. Modulus operator
 A) % ✅
 B) /
 C) *
 D) +
37. Bitwise AND operator
 A) & ✅
 B) &&
 C) |
 D) ||
38. Ternary operator
 A) ?: ✅
 B) ::
 C) ->
 D) ==
39. NOT operator
 A) ! ✅
 B) ~
 C) &
 D) |
40. Relational operator
 A) < ✅
 B) +
 C) *
 D) %
41. Which loop executes at least once?
 A) do-while ✅
 B) while
 C) for
 D) foreach
42. Decision-making statement
 A) if ✅
 B) break
 C) continue
 D) return
43. Exit from loop
 A) break ✅
 B) continue
 C) goto
 D) stop
44. Skip current iteration
 A) continue ✅
 B) break
 C) exit
 D) stop
45. Multiple selection statement
 A) switch ✅
 B) if
 C) while
 D) do
46. Infinite loop
 A) for(;;) ✅
 B) for(i=0;i<10;i++)
 C) while(false)
 D) do while(false)
47. Default block belongs to
 A) switch ✅
 B) if
 C) for
 D) while
48. Condition in if statement returns
 A) boolean ✅
 B) int
 C) char
 D) float
49. Which is an iteration statement?
 A) for ✅
 B) if
 C) switch
 D) break
50. Enhanced for loop is used for
 A) Arrays ✅
 B) Files
 C) Classes
 D) Packages
51. Class contains
 A) Variables and Methods ✅
 B) Arrays only
 C) Objects only
 D) Operators
52. Object occupies
 A) Memory ✅
 B) Disk
 C) CPU
 D) Cache
53. this keyword refers to
 A) Current object ✅
 B) Parent class
 C) Method
 D) Package
54. Object is created using
 A) new ✅
 B) class
 C) this
 D) super
55. Member function is called
 A) Method ✅
 B) Variable
 C) Package
 D) Array
56. Instance variables belong to
 A) Object ✅
 B) Package
 C) Method
 D) JVM
57. Which keyword accesses parent class?
 A) super ✅
 B) this
 C) new
 D) final
58. Java supports
 A) Multiple objects ✅
 B) Multiple inheritance through classes
 C) Operator overloading
 D) Pointers
59. Object initialization occurs through
 A) Constructor ✅
 B) Destructor
 C) Method
 D) Interface
60. Every object has
 A) State and Behavior ✅
 B) Package
 C) Compiler
 D) JVM
61. Constructor name should be
 A) Same as class ✅
 B) Different
 C) Any name
 D) main
62. Constructor has
 A) No return type ✅
 B) int
 C) void
 D) String
63. Default constructor is provided by
 A) Compiler ✅
 B) Programmer
 C) JVM
 D) OS
64. Constructor executes
 A) Object creation ✅
 B) Program end
 C) Method call
 D) Compilation
65. Constructor can be
 A) Overloaded ✅
 B) Overridden
 C) Deleted
 D) Hidden
66. Which keyword invokes another constructor?
 A) this() ✅
 B) super()
 C) new
 D) final
67. Parent constructor is called using
 A) super() ✅
 B) this()
 C) new
 D) static
68. Constructor returns
 A) Nothing ✅
 B) int
 C) Object
 D) String
69. Constructor initializes
 A) Objects ✅
 B) Packages
 C) Arrays
 D) Compiler
70. Constructors cannot be
 A) static ✅
 B) public
 C) private
 D) protected
71. Method overriding occurs in
 A) Inheritance ✅
 B) Constructor
 C) Interface only
 D) Array
72. Overriding requires
 A) Same method signature ✅
 B) Different name
 C) Different return type only
 D) Static method
73. Runtime polymorphism uses
 A) Overriding ✅
 B) Overloading
 C) Constructor
 D) Variable
74. Static methods are
 A) Not overridden ✅
 B) Always overridden
 C) Abstract
 D) Final
75. Final methods
 A) Cannot be overridden ✅
 B) Can be overridden
 C) Are abstract
 D) Are static only
76. @Override annotation indicates
 A) Method overriding ✅
 B) Constructor
 C) Interface
 D) Variable
77. Private methods
 A) Cannot be overridden ✅
 B) Can be overridden
 C) Must be abstract
 D) Are inherited
78. Overridden method is selected at
 A) Runtime ✅
 B) Compile time
 C) Linking
 D) Loading
79. Which keyword accesses overridden method?
 A) super ✅
 B) this
 C) new
 D) static
80. Method overriding supports
 A) Dynamic polymorphism ✅
 B) Encapsulation
 C) Compilation
 D) Arrays
81. Most accessible modifier
 A) public ✅
 B) private
 C) protected
 D) default
82. Least accessible modifier
 A) private ✅
 B) public
 C) protected
 D) default
83. Accessible within same package only
 A) default ✅
 B) private
 C) public
 D) final
84. Accessible in subclass
 A) protected ✅
 B) private
 C) final
 D) default
85. Private members are accessible
 A) Same class ✅
 B) Same package
 C) Subclass
 D) Everywhere
86. Public members are accessible
 A) Everywhere ✅
 B) Same class
 C) Same package
 D) Subclass only
87. Default access modifier is
 A) Package-private ✅
 B) Public
 C) Protected
 D) Private
88. Access modifiers control
 A) Visibility ✅
 B) Compilation
 C) Execution
 D) Variables
89. Which is NOT an access modifier?
 A) static ✅
 B) public
 C) private
 D) protected
90. Which modifier prevents inheritance?
 A) final ✅
 B) static
 C) public
 D) private
91. Static members belong to
 A) Class ✅
 B) Object
 C) Package
 D) JVM
92. Static methods can access directly
 A) Static members only ✅
 B) Instance variables
 C) Constructors
 D) Objects
93. Static block executes
 A) Once ✅
 B) Every method call
 C) Every object creation
 D) Never
94. Which keyword prevents inheritance?
 A) final ✅
 B) static
 C) public
 D) abstract
95. Inheritance uses keyword
 A) extends ✅
 B) implements
 C) inherit
 D) super
96. Java supports multiple inheritance through
 A) Interfaces ✅
 B) Classes
 C) Constructors
 D) Packages
97. Base class is called
 A) Superclass ✅
 B) Subclass
 C) Child class
 D) Object class
98. Derived class is called
 A) Subclass ✅
 B) Superclass
 C) Parent class
 D) Root class
99. Which class is parent of all Java classes?
 A) Object ✅
 B) Main
 C) System
 D) String
100. Inheritance improves
 A) Code Reusability ✅
 B) Memory Usage
 C) Compilation Speed
 D) File Size

1. What is Object-Oriented Programming (OOP)?


Object-Oriented Programming (OOP) is a programming paradigm that organizes programs using
objects and classes. It improves code reusability, security, and maintainability.

2. What are the four principles of OOP?


1. Encapsulation – Wrapping data and methods together.
2. Abstraction – Hiding implementation details.
3. Inheritance – Acquiring properties of another class.
4. Polymorphism – One interface, many implementations.
5.
3. What is Encapsulation?

Encapsulation is the process of combining data and methods into a single unit (class) and restricting
direct access using access modifiers.
Advantages:
 Data security
 Better maintainability
 Easy modification

4. What is Abstraction?

Abstraction hides internal implementation details and shows only essential features to the user.
Advantages:
 Reduces complexity
 Improves security
 Easy maintenance

5. What is Inheritance? Mention its advantages.

Inheritance allows one class to acquire properties and methods of another class using the extends
keyword.
Advantages:
 Code reusability
 Easy maintenance
 Supports method overriding

6. What is Polymorphism?

Polymorphism means "one interface, many forms."


Types:
 Compile-time (Method Overloading)
 Runtime (Method Overriding)
7. What is JDK? Explain its components.

JDK (Java Development Kit) is used to develop Java applications.


Components:
 JRE
 JVM
 Java Compiler (javac)
 Debugger
 Documentation tools

8. Differentiate JDK, JRE and JVM.

JDK JRE JVM


Development Kit Runtime Environment Virtual Machine
Includes compiler Executes Java programs Converts bytecode to machine code
Contains JRE Contains JVM Part of JRE

9. What are primitive data types in Java?

Java has 8 primitive data types:


 byte
 short
 int
 long
 float
 double
 char
 boolean

10. What is an array? Mention its advantages.

An array is a collection of similar data elements stored in contiguous memory locations.


Advantages:
 Easy data management
 Faster access
 Reduces code complexity

11. Explain different types of variables in Java.


1. Local Variable
2. Instance Variable
3. Static Variable
Each has a different scope and lifetime.

12. Explain Arithmetic Operators.

Arithmetic operators perform mathematical operations.


Operators:
 +

o

o
 /
 %
Example:
int c = a + b;

13. Explain Relational Operators.

Relational operators compare two values.


Operators:
 ==
 !=

 <
 =
 <=
Result is always boolean.

14. Explain Logical Operators.

Logical operators combine conditions.


Operators:
 &&
 ||
 !
Used mainly in decision-making statements.

15. Explain if-else statement.

The if-else statement executes one block if the condition is true and another if false.
Syntax:
if(condition)
{
}
else
{
}
16. Explain switch statement.

The switch statement selects one block from multiple choices.


Uses:
 Menu-driven programs
 Multiple selections
Includes:
 case
 break
 default

17. Differentiate while and do-while loops.

while do-while
Entry controlled Exit controlled
May execute zero times Executes at least once

18. What is a class?

A class is a blueprint for creating objects.


It contains:
 Variables
 Methods
 Constructors

19. What is an object?

An object is an instance of a class.


It has:
 State
 Behaviour
 Identity
Objects are created using the new keyword.

20. Differentiate Class and Object.

Class Object
Blueprint Instance
Logical entity Physical entity
No memory Occupies memory

21. What is a constructor?

A constructor initializes an object automatically during object creation.


Features:
 Same name as class
 No return type
 Invoked automatically

22. Explain default constructor and parameterized constructor.

Default Constructor
 No parameters
 Initializes default values
Parameterized Constructor
 Accepts parameters
 Initializes user-defined values

23. What is method overriding?

Method overriding occurs when a subclass provides its own implementation of a method already defined
in the superclass.
Features:
 Same method signature
 Runtime polymorphism
 Uses inheritance

24. Difference between Method Overloading and Method Overriding.

Overloading Overriding
Same class Different classes
Different parameters Same parameters
Compile-time Runtime

25. What are access specifiers?

Access specifiers control the visibility of class members.


Types:
 public
 private
 protected
 default

26. Differentiate public and private access specifiers.

public private
Accessible everywhere Accessible only within class
Maximum visibility Minimum visibility

27. What are static members?


Static members belong to the class rather than objects.
Examples:
 Static variable
 Static method
 Static block
Accessed using class name.

28. What is inheritance? Mention its types.

Inheritance allows one class to inherit properties of another class.


Types:
 Single
 Multilevel
 Hierarchical
(Java supports multiple inheritance through interfaces.)

29. Write the advantages of inheritance.

 Code reusability
 Easy maintenance
 Reduces redundancy
 Supports polymorphism
 Faster development

30. Explain the this and super keywords.

this
 Refers to the current object.
 Invokes current class constructor.
 Accesses current class variables.
super
 Refers to the parent class object.
 Calls parent constructor.
 Accesses parent class methods and variables.

Anna University Exam Tips


The following topics are frequently asked as 3-mark questions:
 Principles of OOP
 JDK, JRE, JVM
 Primitive Data Types
 Arrays
 Operators
 if-else and switch statements
 while vs do-while
 Class vs Object
 Constructors
 Method Overloading vs Overriding
 Access Specifiers
 Static Members
 Inheritance
 this vs super

PART-B

1. Explain the Principles of Object-Oriented Programming (OOP) with Suitable Examples.

Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to
design programs. It helps in developing software that is reusable, secure, modular, and easy to maintain.
The four main principles of OOP are:
1. Encapsulation
2. Abstraction
3. Inheritance
4. Polymorphism
5. Class
6. Object
1. Encapsulation
Encapsulation is the process of wrapping data (variables) and methods (functions) into a single unit
called a class. It also protects data from unauthorized access using access modifiers such as private.
Advantages
 Provides data security.
 Prevents unauthorized access.
 Makes programs easier to maintain.
Example
class Student {
private int age;

public void setAge(int a) {


age = a;
}

public int getAge() {


return age;
}
}

class Demo {
public static void main(String args[]) {
Student s = new Student();
[Link](20);
[Link]([Link]());
}
}

2. Abstraction
Abstraction is the process of hiding implementation details and displaying only the essential
information to the user.
Advantages
 Reduces program complexity.
 Improves security.
 Makes programs easy to use.
Example
A person can drive a car without knowing how the engine works. The driver only uses the steering
wheel, accelerator, and brake. The internal working of the engine is hidden.

3. Inheritance
Inheritance is the process by which one class acquires the properties and methods of another class
using the extends keyword.
Advantages
 Code reusability.
 Reduces code duplication.
 Easy maintenance.
 Supports method overriding.
Example
class Animal {
void sound() {
[Link]("Animal makes sound");
}
}

class Dog extends Animal {


void bark() {
[Link]("Dog barks");
}
}

class Demo {
public static void main(String args[]) {
Dog d = new Dog();
[Link]();
[Link]();
}
}

4. Polymorphism
Polymorphism means "one interface, many forms." The same method can perform different tasks
depending on the object or parameters.
Types
1. Compile-time Polymorphism – Method Overloading.
2. Runtime Polymorphism – Method Overriding.
Example (Method Overloading)
class Add {
int sum(int a, int b) {
return a + b;
}

int sum(int a, int b, int c) {


return a + b + c;
}
}

Advantages of OOP
 Code reusability through inheritance.
 Data security through encapsulation.
 Reduced complexity through abstraction.
 Flexibility through polymorphism.
 Easy maintenance and debugging.
 Modular program design.

Applications of OOP
 Banking systems
 Hospital management systems
 Student management systems
 E-commerce applications
 Mobile applications
 Game development

[Link] about the JDK.

JDK (Java Development Kit) is a software package used to develop, compile, run, and debug Java
applications. It is provided by Oracle and other Java distributors.

What is JDK?
The Java Development Kit (JDK) is a complete toolkit for Java programmers. It contains everything
needed to create Java programs, including the compiler, runtime environment, and development tools.

Components of JDK
1. JRE (Java Runtime Environment)
1. Provides the environment needed to run Java applications.
2. Includes the JVM and standard Java libraries.
2. JVM (Java Virtual Machine)
1. Executes Java bytecode.
2. Makes Java platform-independent ("Write Once, Run Anywhere").
3. Java Compiler (javac)
1. Converts Java source code (.java) into bytecode (.class).
4. Development Tools
1. java – Runs Java applications.
2. javac – Compiles Java source code.
3. javadoc – Generates documentation from source code.
4. jar – Creates and manages Java Archive (JAR) files.
5. jdb – Java debugger.
6. jshell – Interactive Java shell (available in newer JDK versions).
How JDK Works
1. Write Java code in a .java file.
2. Use the javac compiler to compile the code into bytecode (.class file).
3. The JVM executes the bytecode.
4. The program runs on any operating system that has a compatible JVM.
Advantages of JDK
 Enables Java application development.
 Includes all tools required for coding, compiling, debugging, and packaging.
 Supports cross-platform development.
 Provides built-in libraries for networking, file handling, collections, and more.

Difference Between JDK, JRE, and JVM


Feature JDK JRE JVM
Full form Java Development Kit Java Runtime Environment Java Virtual Machine
Purpose Develop and run Java programs Run Java programs Execute Java bytecode
Includes compiler ✅ Yes ❌ No ❌ No
Includes JVM ✅ Yes ✅ Yes It is the JVM itself
Used by Developers End users Runtime execution

Example:
public class Hello {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}

BASIC PROGRAM:

/ Java program to take an integer


// as input and print it
import [Link].*;
import [Link];

// Driver
Class class
GFG {
// main function
public static void main(String[] args)
{
// Declare the
variables int num;

// Input the integer


[Link]("Enter the integer:
");

// Create Scanner object


Scanner s = new Scanner([Link]);

// Read the next integer from the


screen num = [Link]();

// Display the integer


[Link]("Entered integer
is: "
+ num);
}
}
DATA TYPES:

Variable declared in java has a data type. Data types specify the type of data and size needed to
store the data.
1. Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double
2. Non-Primitive Data Type or Object Data type: such as String, Array, etc.

Primitive Data Types in Java


Primitive data are only single values and have no special capabilities. There are 8 primitive data
types. They are depicted below in tabular format below as follows:
Example
Type Description Default Size Literals Range of values

boolean true or false false 1 bit true, false true, false

twos-
complement 0 8 bits (none) -128 to 127
byte integer

‘a’, ‘\u0041’, characters representation of


Unicode \u0000 16 ‘\101’, ‘\\’, ASCII values
char character bits ‘\’, ‘\n’, ‘β’ 0 to 255

twos-
complement 0 16 bits (none) -32,768 to 32,767
short integer

twos- -2,147,483,648
complement 0 32 bits -2,-1,0,1,2 to
int intger 2,147,483,647

-
twos- -2L,- 9,223,372,036,854,775,808
complement 0 64 bits 1L,0L,1L,2L to
long integer 9,223,372,036,854,775,807

IEEE 754 1.23e100f , -


floating 0.0 32 bits 1.23e-100f , upto 7 decimal digits
float point .3f ,3.14F

IEEE 754 1.23456e300d


floating 0.0 64 bits , -123456e- upto 16 decimal digits
double point 300d , 1e1d

Boolean Data Type


The Boolean data type is used to store only two possible values: true and false. This data type is
used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Example:

Boolean one = false

Byte Data Type:

The byte data type is an example of primitive data type. It isan 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is
127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in
place of "int" data type.

Example:

Byte a = 10, byte b = -20

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-range lies between -
32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its
default value is 0.

The short data type can also be used to save memory just like byte data type. A short data type is
2 times smaller than an integer.

Example:

Short s = 10000, short r = -5000

Int Data Type


The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.

Example:

]int a = 100000, int b = -200000

Long Data Type


The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum
value is - 9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its
default value is 0. The long data type is used when you need a range of values more than those
provided by int.

Example:

long a = 100000L, long b = -200000L

Float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating [Link] value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating point numbers. The float data type should never be used for precise
values, such as currency. Its default value is 0.0F.

Example:

float f1 = 234.5f

Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The double
data type also should never be used for precise values, such as currency. Its default value is 0.0d.

Example:

double d1 = 12.3

Char Data Type


The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or
0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.

Example:
char letterA = 'A'

Example program:
Public class datatypes {
public static void main(String args[]){
char a = 'G';
int i = 89:
byte b = 4;
short s =
56;
double d =
4.355453532; float f
= 4.7333434f; long l
= 12121;
[Link]("char: " + a);
[Link]("integer: " + i);
[Link]("byte: " + b);
[Link]("short: " + s);
[Link]("float: " + f);
[Link]("double: " + d);
[Link]("long: " + l);
}
}

[Link] Arrays and Explain about the Types Of Arrays?

Array is an object which contains elements of a similar data type. Additionally, The elements of
an array are stored in a contiguous memory location. It is a data structure where we store similar
elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.

ADVANTAGES

o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
o Random access: We can get any data located at an index position.

DIS ADVANTAGES

o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in Java which grows
automatically.
There are three types of array.

o Single Dimensional Array


o Two Dimensional Array
o Multidimensional Array

SINGLE DIMENSIONAL ARRAY

An array is a group of similar data typed variables that shares a common name. The
elements of the array are accessed by the array index. The array index must begin in zero
to n-1, where n is the number of elements in the array.
SYNTAX:
dataType[] arr;
(or) dataType
[]arr; (or)
dataType arr[]

DECLARATION:
type array-name[ ] = new type[ size];

Example:

 int a[ ] = new int[10 ];


 double n[ ] = new double[5];
 String s[ ] = new String[7];

ARRAY INPUT:

Example:
int a[ ] = { 10, 34,22,56,21};
In the above example the integer values are assigned as a[0]=10, a[1]=34, a[2]=22,
a[3]=56 and a[4]=21.
String s[ ] = { “Anand”, “Bala”, “Jhon Samuel”, “Hayes”};

In the above example the String objects are assigned as s[0]=”Anand”;


s[1]=”Bala”, s[2]=”Jhon Samuel”, s[3]=”Hayes”

ARRAY OUTPUT:

The elements of the array can be accessed with the array index and a loop statement.
Example: int b[ ]= { 34,23, 11, 67,23};
[Link](“ Array Elements”);
for(i=0; i<5; i++) [Link](b[i]);

ARRAY PROCESSING:

The following example illustrates the array processing. int b[


]= { 34,23, 11, 67,23};
int s=0;
for(i=0; i<5;
i++) s=s+b[i];
[Link](“Sum of the elements = “ +s):

EXAMPLE PROGRAM:
public class
TwoDimensionalArrayExample { public
static void main(String[] args) {
// Creating a 2D array with 3 rows and 4 columns
int[][] matrix = new int[3][4];
// Initializing values in the array
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[0][3] = 4;
matrix[1][0] = 5;
matrix[1][1] = 6;
matrix[1][2] = 7;
matrix[1][3] = 8;
matrix[2][0] = 9;
matrix[2][1] = 10;
matrix[2][2] = 11;
matrix[2][3] = 12;
// Accessing and printing
elements for (int i = 0; i < 3; i+
+) {
for (int j = 0; j < 4; j++)
{ [Link](matrix[i][j] + " ");
}
[Link](); // Move to the next row
}
}
}

OUTPUT:
1234
5678
9 10 11 12
MULTIDIMENSIONAL ARRAY
Array is a complex form of a multidimensional array. A three-dimensional array can be seen as an
array of two – dimensional array for easier understanding.

Declaration:
Declaration – Syntax:
data_type[][][] array_name = new data_type[x][y]
[z]; For example: int[][][] arr = new int[10]
[20][30];

Initialization – Syntax:
array_name[array_ index][row_ index][column_index] =
value; For example: arr[0][0][0] = 1;
Example:
import
[Link].*;
class GFG {
public static void main(String[] args)
{

int[][][] arr = new int[10][20][30];


arr[0][0][0] = 1;

[Link]("arr[0][0][0] = " + arr[0][0][0]);


}
}
Output
arr[0][0][0]
=1

VARIABLE IN JAVA

A variable in Java is a named memory location that is used to store data. The value stored in a variable
can be changed during program execution unless it is declared with the final keyword.

Definition

A variable is a name given to a memory location that stores a value of a specific data type.

For example:

int age = 20;

Here:

 int → Data type


 age → Variable name
 20 → Value stored in the variable

Syntax

dataType variableName = value;

Example

int marks = 90;


String name = "John";
double salary = 25000.50;
char grade = 'A';
boolean passed = true;

Types of Variables in Java

Java has three types of variables:

1. Local Variable

A local variable is declared inside a method, constructor, or block. It can only be used within that
method or block.
Example Program

public class LocalVariableExample {


public static void main(String[] args) {
int number = 100; // Local variable
[Link]("Number = " + number);
}
}

Output

Number = 100

Characteristics

 Declared inside methods.


 Accessible only within the method.
 Must be initialized before use.

2. Instance Variable

An instance variable is declared inside a class but outside any method. Every object of the class has its
own copy of the instance variable.

Example Program

class Student {
String name = "Alice"; // Instance variable

void display() {
[Link]("Name = " + name);
}

public static void main(String[] args) {


Student s = new Student();
[Link]();
}
}

Output

Name = Alice
Characteristics

 Declared inside a class.


 Not declared with static.
 Each object has its own value.

3. Static Variable (Class Variable)

A static variable is declared using the static keyword. It is shared by all objects of the class.

Example Program

class Student {
static String college = "ABC College"; // Static variable
String name;

Student(String n) {
name = n;
}

void display() {
[Link](name + " studies at " + college);
}

public static void main(String[] args) {


Student s1 = new Student("John");
Student s2 = new Student("Mary");

[Link]();
[Link]();
}
}

Output

John studies at ABC College


Mary studies at ABC College

Characteristics

 Declared using the static keyword.


 Shared among all objects.
 Memory is allocated only once.
Rules for Naming Variables

 Variable names must begin with a letter, _, or $.


 They cannot start with a number.
 They cannot be Java keywords such as class or int.
 Java is case-sensitive (age and Age are different).
 Use meaningful names like studentName or totalMarks.

Valid Variable Names

int age;
double salary;
String studentName;

Invalid Variable Names

int 1age; // Starts with a number


int class; // Keyword
int student-name; // Hyphen not allowed

Example Program Using Different Variables

public class VariableExample {

static String school = "XYZ School"; // Static variable

String studentName = "Rahul"; // Instance variable

public static void main(String[] args) {

int marks = 95; // Local variable

VariableExample obj = new VariableExample();

[Link]("Student Name : " + [Link]);


[Link]("School : " + school);
[Link]("Marks : " + marks);
}
}
Output

Student Name : Rahul


School : XYZ School
Marks : 95

4. Discuss About the Types of Operators in Java

An operator in Java is a symbol that performs an operation on one or more operands (values or
variables) and produces a result.

Operators are special symbols used to perform mathematical, relational, logical, and other
operations on variables and values.

For example:

int a = 10;
int b = 5;
int sum = a + b;

Here:

 + is the operator.
 a and b are operands.
 The result is 15.

Types of Operators in Java

Java operators are mainly classified into the following types:

1. Arithmetic Operators
2. Relational (Comparison) Operators
3. Logical Operators
4. Assignment Operators
5. Unary Operators
6. Increment and Decrement Operators
7. Bitwise Operators
8. Shift Operators
9. Ternary (Conditional) Operator
1. Arithmetic Operators

These operators perform mathematical calculations.

Operator Description Example


+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulus (Remainder) a % b

Example Program

public class ArithmeticExample {


public static void main(String[] args) {
int a = 20;
int b = 10;

[Link]("Addition = " + (a + b));


[Link]("Subtraction = " + (a - b));
[Link]("Multiplication = " + (a * b));
[Link]("Division = " + (a / b));
[Link]("Remainder = " + (a % b));
}
}

Output

Addition = 30
Subtraction = 10
Multiplication = 200
Division = 2
Remainder = 0

2. Relational (Comparison) Operators

These operators compare two values and return true or false.

Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
Operator Meaning
<= Less than or equal to

Example Program

public class RelationalExample {


public static void main(String[] args) {
int a = 15;
int b = 20;

[Link](a == b);
[Link](a != b);
[Link](a > b);
[Link](a < b);
}
}

Output

false
true
false
true

3. Logical Operators

Logical operators combine or invert boolean values.

Operator Meaning
&& Logical AND
`
! Logical NOT

Example Program

public class LogicalExample {


public static void main(String[] args) {
boolean a = true;
boolean b = false;

[Link](a && b);


[Link](a || b);
[Link](!a);
}
}

Output

false
true
false

4. Assignment Operators

These operators assign values to variables.

Operator Example Meaning


= a = 10 Assign value
+= a += 5 a=a+5
-= a -= 5 a=a-5
*= a *= 2 a=a*2
/= a /= 2 a=a/2
%= a %= 2 a = a % 2

Example Program

public class AssignmentExample {


public static void main(String[] args) {
int a = 10;

a += 5;
[Link](a);

a *= 2;
[Link](a);
}
}

Output

15
30

5. Unary Operators

Unary operators work with only one operand.


Operator Meaning
+ Positive
- Negative
! Logical NOT
~ Bitwise complement

Example Program

public class UnaryExample {


public static void main(String[] args) {
int a = 10;

[Link](-a);

boolean flag = true;


[Link](!flag);
}
}

Output

-10
false

6. Increment and Decrement Operators

These operators increase or decrease a variable by 1.

Operator Meaning
++ Increment
-- Decrement

Example Program

public class IncrementExample {


public static void main(String[] args) {
int a = 5;
a++;
[Link](a);

a--;
[Link](a);
}
}

Output

6
5

7. Bitwise Operators

Bitwise operators work on the binary representation of integers.

Operator Meaning
& Bitwise AND
` `
^ Bitwise XOR
~ Bitwise NOT

Example Program

public class BitwiseExample {


public static void main(String[] args) {
int a = 5;
int b = 3;

[Link](a & b);


[Link](a | b);
[Link](a ^ b);
}
}

Output

1
7
6

8. Shift Operators

Shift operators move the bits of a number left or right.


Operator Meaning
<< Left Shift
>> Right Shift
>>> Unsigned Right Shift

Example Program

public class ShiftExample {


public static void main(String[] args) {
int a = 8;

[Link](a << 1);


[Link](a >> 1);
}
}

Output

16
4

9. Ternary (Conditional) Operator

The ternary operator is a shorthand form of the if-else statement.

Syntax

condition ? value1 : value2;

Example Program

public class TernaryExample {


public static void main(String[] args) {
int age = 20;

String result = (age >= 18) ? "Eligible to Vote" : "Not Eligible";

[Link](result);
}
}

Output

Eligible to Vote
5. Write a short notes on Control statements and its types?

Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. However, Java provides statements that can be used
to control the flow of Java code.
Java provides three types of control flow statements.

1. Decision Making statements


o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop

o for-each loop
3. Jump statements
o break statement
o continue statement

Decision-Making statements:

As the name suggests, decision-making statements decide which statement to execute and when.
Decision-making statements evaluate the Boolean expression and control the program flow
depending upon the result of the condition provided. There are two types of decision-making
statements in Java, i.e., If statement and switch statement

1) If Statement:

In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted
depending upon the specific condition. The condition of the If statement gives a Boolean value,
either true or false. In Java, there are four types of if-statements given below.

1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement

Let's understand the if-statements one by

one. public class IfElseIfLadderExample {


public static void main(String[] args) {
int num = 10;

if (num > 0)
{ [Link]("Number is
positive.");
} else if (num < 0)
{ [Link]("Number is
negative.");
} else {
[Link]("Number is zero.");
}
}
}
NESTED IF SATEMENTS:

public class NestedIfExample {


public static void main(String[]
args) { int num = 10;

if (num > 0) {
if (num % 2 == 0) {
[Link]("Number is positive and even.");
} else {
[Link]("Number is positive and odd.");
}
} else if (num < 0)
{ [Link]("Number is
negative.");
} else {
[Link]("Number is zero.");
}
}
}
Switch Statement:

In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which is
being switched. The switch statement is easier to use instead of if-else-if statements. It also
enhances the readability of the program.

Points to be noted about switch statement:

o The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of expression.
It is optional.
o Break statement terminates the switch block when the condition is
satisfied. It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the same
type as the variable. However, it will also be a constant value.
o EXAMPLE PROGRAM:
public class SwitchExample {

public static void main(String[]


args) { int dayOfWeek = 4;
String dayName;

switch (dayOfWeek)
{ case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName =
"Wednesday"; break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName =
"Friday"; break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName =
"Sunday"; break;
default:
dayName = "Invalid
day"; break;
}

[Link]("Day of the week is: " + dayName);


}
}

6. Explain about the Looping Statements With an Example Program?

In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of instructions in
a repeated order. The execution of the set of instructions depends upon a particular condition.

In Java, we have three types of loops that execute similarly. However, there are differences in
their syntax and condition checking time.

1. for loop
2. while loop
3. do-while loop

public class LoopExample {


public static void main(String[] args) {
// For loop example
[Link]("For
loop:"); for (int i = 0; i < 5; i++)
{ [Link]("Iteration
" + i);
}

// While loop example


[Link]("\nWhile
loop:"); int j = 0;
while (j < 5)
{ [Link]("Iteration " +
j); j++;
}

// Do-while loop example


[Link]("\nDo-while
loop:"); int k = 0;
do {

[Link]("Iteration " +
k); k++;
} while (k < 5);
}
}

FOR-EACH LOOP:

For-each loop is used to traverse array or collection in java. It is easier to use than simple for
loop because we don't need to increment value and use subscript notation. It works on
elements

basis not [Link] returns element one by one in the defined variable.

Syntax:

for(type itr-var : collection) statement-block

Example:

// Use a for-
each style
for loop.
class
ForEach {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
// use for-each style for to display
and sum the valuesfor(int x : nums) {
[Link]
("V alue is: " +
x);sum += x;
}
[Link]("Summation: " + sum);
}
}

Output:

Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 6
Value is: 7
Value is: 8
Value is: 9
Value is: 10
Summation: 55

Nested Loops

Java allows loops to be nested. That is, one loop may be inside another.

Example:

// Loops
public class NestedLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) { // Outer loop
for (int j = 1; j <= 5; j++) { // Inner loop
[Link]("* ");
}
[Link]();
}
}
}

Jump Statements

Jump statements are used to transfer the control of the program to the specific statements. In other
words, jump statements transfer the execution control to the other part of the program. There are
two types of jump statements in Java, i.e., break and continue.

Java break statement

As the name suggests, the break statement is used to break the current flow of the program and
transfer the control to the next statement outside a loop or switch statement. However, it breaks
only the inner loop in the case of the nested loop

Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the
specific part of the loop and jumps to the next iteration of the loop immediately..

In java class consists of instance variables and methods. Methods consist of set of statements
to access the instance variables and to perform a particular task. The general form of a
method is given below.

type method-name(arguments)

{ // Body of method

return value;

CONSTRUCTORS:

 In Java, a Constructor is a block of codes similar to the method.


 It is called when an instance of the class is created. At the time of calling the
constructor, memory for the object is allocated in the memory.
 It is a special type of method that is used to initialize the object.
 Every time an object is created using the new () keyword, at least one constructor is called.

 The constructor(s) of a class must have the same name as the class name in which it resides.
 A constructor in Java cannot be abstract, final, static, or synchronized.
 Access modifiers can be used in constructor declaration to control its access i.e which other
class can call the constructor.

Types of Constructors in Java

 Default Constructor
 Parameterized Constructor

1. Default Constructor in Java


 A constructor that has no parameters is known as default the constructor.
 A default constructor is invisible. And if we write a constructor with no
arguments, the compiler does not create a default constructor.
 It is taken out. It is being overloaded and called a parameterized constructor. The default
constructor changed into the parameterized constructor. But Parameterized constructor
can’t change the default constructor.
 The default constructor can be implicit or explicit. If we don’t define explicitly, we get an
implicit default constructor. If we manually write a constructor, the implicit one is
overridded.

Example:

// Java Program to demonstrate


// Default
Constructor import
[Link].*;

// Driver
class class
GFG {

// Default Constructor
GFG() { [Link]("Default constructor"); }
// Driver function
public static void main(String[] args)
{
GFG hello = new GFG();
}
}

Output

Default constructor

2. Parameterized Constructor in Java

A constructor that has parameters is known as parameterized constructor. If we want to


initialize fields of the class with our own values, then use a parameterized constructor.

Example:

// Java Program for Parameterized


Constructor import [Link].*;
class Geek {
// data members of the
class. String name;
int id;
Geek(String name, int id)
{
[Link] = name;
[Link] = id;
}
}
class GFG {
public static void main(String[] args)
{
// This would invoke the parameterized
constructor. Geek geek1 = new Geek("Avinash",
68); [Link]("GeekName :" +
[Link]
+ " and GeekId :" + [Link]);
}
}

Output

GeekName :Avinash and GeekId :68


EMBER ACCESS CLASS (ACCESS CONTROL):

PUBLIC:

o Members declared as public are accessible from any other class.


o There are no restrictions on accessing public members.

PRIVATE:

o Members declared as private are accessible only within the same class.
o They cannot be accessed from outside the class, not even from subclasses.

PROTECTED:

o Members declared as protected are accessible within the same package


or by subclasses in different packages.
o They can also be accessed in the same package by any other class.

DEFAULT (PACKAGE-PRIVATE):

o If no access modifier is specified, it is considered as default or package-private.


o Members with default access are accessible only within the same package.
o Here's a brief overview of how they are used:

EXAMPLE:

public class MyClass { public int


publicField; private int
privateField;
protected int protectedField;
int defaultField; // Package-private
public void publicMethod() {
// This method can be accessed from any class.
}

private void privateMethod() {


// This method can only be accessed within the same class.
}

protected void protectedMethod() {


// This method can be accessed within the same package or by subclasses.
}

void defaultMethod() {
// This method can be accessed within the same package.
}
}

GARBAGE COLLECTION
 In java, garbage means unreferenced objects.

 Garbage Collection is process of reclaiming the runtime unused


memory automatically. In other words, it is a way to destroy the
unused objects.

 To do so, we were using free() function in C language and delete() in C++.


But, in java it is performed automatically. So, java provides better memory
management.

Advantage of Garbage Collection


 It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
 It is automatically done by the garbage collector(a part of JVM) so we don't
need to make extra efforts.

1. By nulling the reference


2. By assigning a reference to another
3. By anonymous object etc.
4. Java Garbage Collection Scenario
1) By nulling a reference:
Employee e=new Employee(); e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection
3) By anonymous object:
new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in Object class as:
protected void finalize(){} .

Simple Example of garbage collection in java


public class TestGarbage1{
public void finalize(){[Link]("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null; [Link]();
}
}
POLYMORPHISM:

Polymorphism is considered one of the important features of Object-Oriented Programming.


Polymorphism allows us to perform a single action in different ways. In other words,
polymorphism allows you to define one interface and have multiple implementations. The
word “poly” means many and “morphs” means forms, So it means many forms.
Types of Java Polymorphism

 Compile-time Polymorphism
 Runtime Polymorphism

METHOD OVERLOADING:

Method overloading is a type of polymorphism in java. It is a process in which two or more


methods in a class have the same name with different codes. These methods have different
number of arguments, different types of arguments, the order of arguments may differ and they
may have different return type.

//Method Overloading – To calculate Area of a square, Rectangle and Triangle

import [Link].*;
class Ovload
{ double l,b,s,r;
void area(double s1)
{ double a;
a=s1*s1;
[Link]("Side="+s1);
[Link]("Area of Square="+a);

void area(double l1, double b1)


{ double a;
a=l1*b1; [Link]("Length="+l1);

[Link]("Breadth="+b1);
[Link]("Area of Rect="+a);
}

void area(double pi, double r1, double r2)


{ double a;
a=pi*r1*r1;
[Link]("Radius="+r1);
[Link]("Area of Circle="+a);
}

class Movload {

public static void main(String arg[ ])


{ Ovload d1,d2,d3;
d1=new Ovload( );
d2=new Ovload( );
d3=new Ovload( );
[Link](10.0);
[Link](10.0,20.0);

[Link](3.14, 10.0,10.0);

OVERLOADING CONSTRUCTOR:

In java similar to overloading methods, constructors can also be overloaded. If any contains more
than one constructor then the constructors are overloaded. The overloaded constructors have
different types of arguments, different number of arguments and the order of arguments may also
be different.

Example: Java program to demonstrate Constructor Overloading.

import [Link].*;
class Consovload {
double l,b,s,r;
Consovload(double s1) { double
a;
a=s1*s1;
[Link]("Side="+s1);
[Link]("Area of Square="+a);

Consovload(double l1, double b1) { double


a;
a=l1*b1; [Link]("Length="+l1);
[Link]("Breadth="+b1);
[Link]("Area of Rect="+a);

Consovload(double pi, double r1, double r2)


{ double a;
a=pi*r1*r1;
[Link]("Radius="+r1);
[Link]("Area of Circle="+a);
}

class Mconsovload {

public static void main(String arg[]) { Consovload


d1=new Consovload(10); Consovload d2=new
Consovload(10,2); Consovload d3=new
Consovload(3.14,10,10);
}

}
METHOD OVERRIDING
In Inheritance, when a method in a sub class has the same name, same number of arguments, same
type of arguments, arguments in the same order as a method in its super class, then the sub class
method override the super class method. When the sub class method is called, it will always refer to
the sub class method and will not refer the super class method. This mechanism in java is called
method overriding.

Example: Java program to demonstrate method overriding.

import

[Link].*; class
Demo { int x,y;
Demo(int x1,int
y1) {
x=x1;
y=y1;

void display( ) { [Link]("Super x :


"+x); [Link]("Super y : "+y);
}

}
class Demo1 extends Demo { int z;
Demo1(int x1, int y1, int z1) { super(x1,y1);//Calling
super class constructor z=z1;
}

void display( ) {

// [Link]();// To
access supercalss method
[Link]("sub z: "+z);
}
}
class Moverriding1 {

public static void main(String args[ ]) throws IOException


Demo1(15,25,35);
[Link]( );

Dynamic Method Dispatch:( RUN TIME)

Method overriding forms the basis for Dynamic method dispatch. When a overridden method is
called through a super class reference, java determines which method has to be executed at the time
the call occurs. This is based on which sub class object is assigned to the super class reference. This
mechanism is called dynamic method dispatch. In java, run-time polymorphism can be implemented
using Dynamic method dispatch.

Example: Java program to demonstrate Dynamic method dispatch


(Polymorphism).

import [Link].*;
class Demo { int x;
Demo(int x1 ) {
x=x1;
}

void display( ) { [Link]("Demo x :


"+x);
}
}

class Demo1 extends Demo { int y;


Demo1(int x1, int y1) {

super(x1);//Calling super class constructor y=y1;


}

void display( ) {
[Link]("Demo1 y: "+y);
}
}

class Demo2 extends Demo1 { int z,s;


Demo2(int x1, int y1,int z1) { super(x1,y1);//Calling
super class constructor z=z1;
}

void display( )
[Link]("Demo2 Z: "+z);
[Link]("Sum = "+s);
}
}

class Dynmtddispch {

public static void main(String args[ ]) throws IOException


Demo1 d1=new Demo1(12,45);

Demo2 d2= new Demo2(100,200,300); Demo dd;


dd=d; [Link](
); dd=d1;
[Link]( );
dd=d2;
[Link]( );
}
}
}
INHERITANCE:

Inheritance in object-oriented programming (OOP) allows a class (subclass or derived class) to inherit
properties and behaviors from another class (superclass or base class). In Java, inheritance can be
classified into several types based on the relationship between the classes involved. Here are the
common types of inheritance:

1. Single Inheritance:
o In single inheritance, a subclass inherits from only one superclass.

Example:

class Animal {
// Animal class properties and methods
}
class Dog extends Animal {
// Dog class properties and methods
}

2. Multilevel Inheritance:
o In multilevel inheritance, a subclass inherits from another subclass, forming a
chain of inheritance.

Example:

class Animal {
// Animal class properties and methods
}
class Dog extends Animal {
// Dog class properties and methods
}
class Labrador extends Dog {
// Labrador class properties and methods
}

3. Hierarchical Inheritance:
o In hierarchical inheritance, multiple subclasses inherit from a single superclass.

Example:

class Animal {
// Animal class properties and methods
}
class Dog extends Animal {
// Dog class properties and methods
}
class Cat extends Animal {
// Cat class properties and methods
}

INHERITANCE USING SUPER CLASS:

In Java, the super keyword is used to refer to the superclass (or parent class) of the current object. It
can be used in various contexts, including constructors and methods, to access superclass members
and to invoke superclass constructors.
class Animal {
String sound = "Animal Sound";
}

class Dog extends Animal


{ void printSound() {
[Link]([Link]); // Accessing sound field of superclass
}
}

Invoking Superclass Constructors: In a subclass constructor, you can use super() to explicitly call a
constructor of the superclass. This is useful when the superclass constructor needs to be executed
before the subclass constructor.

class Animal
{ Animal() {
[Link]("Animal constructor");
}
}

class Dog extends Animal


{ Dog() {
super(); // Calling superclass
constructor [Link]("Dog
constructor");
}
}

Invoking Superclass Methods: You can use super to invoke superclass methods from within a
subclass method, even if the subclass has overridden the method.

class Animal
{ void eat()
{
[Link]("Animal is eating");
}
}

class Dog extends Animal


{ @Override
void eat() {
[Link](); // Calling superclass
method [Link]("Dog is
eating");
}
}
Superclass Initialization: When a subclass object is created, the superclass constructor is
automatically invoked before the subclass constructor. If no explicit call to super() is made in the
subclass constructor, Java implicitly inserts a call to the no-argument constructor of the superclass.
class Animal {
Animal() {
[Link]("Animal constructor");
}
}
class Dog extends Animal
{ Dog() {
// Implicit call to super() here
[Link]("Dog
constructor");
}
}

PACKAGES:
Packages are containers for classes and interfaces. It is a collection of related classes and interfaces. The
package restricts the visibility for the classes inside a package and naming mechanism. The programmer
can define classes inside a package that are not accessible by the code outside the package or that may
be accessible by the code outside the class.
DEFINING A PACKAGE:
The keyword package is used to create a package. The package statement must be the first statement
in the source file. The classes that are declared within that file will belong to the specified package.
The keyword package defines a name space in which classes are stored. In the absence of package
keyword, the classes are stored in a default package. The general form of package is given blow.
package package-name; Example:
package demopack1;

ADDING A CLASS TO A PACKAGE:

Before adding a class to a package, create a package. The class to be added to the package must
follow the package definition.

Example:
package
student; class
Stu
{
String name; int roll-num;
//Body
}

Example: Program to demonstrate package


package demopack;
class Student { String
name; int rn;
Student(String name1, int rn1) { name=name1;
rn=rn1;
}
void output( ) { [Link]("Name
:"+name); [Link]("RNum :"+rn);
}
}
class Mstudent {
public static void main(String arg[ ]) { Student s=new Student("Raja",1234); [Link]( );
}
}

Static Members in Java

Static members are variables, methods, blocks, or nested classes that belong to the class rather than to
individual objects. They are declared using the static keyword and can be accessed without creating an
object.

Types of Static Members

1. Static Variable (Class Variable)


2. Static Method
3. Static Block
4. Static Nested Class

1. Static Variable

A static variable is shared by all objects of a class.

Example

class Student {
static String college = "ABC College";
String name;

Student(String name) {
[Link] = name;
}

void display() {
[Link](name + " - " + college);
}

public static void main(String[] args) {


Student s1 = new Student("Rahul");
Student s2 = new Student("Priya");

[Link]();
[Link]();
}
}

Output

Rahul - ABC College


Priya - ABC College

2. Static Method

A static method belongs to the class and can be called without creating an object.

Example

class Demo {
static void greet() {
[Link]("Welcome to Java");
}
public static void main(String[] args) {
[Link]();
}
}

Output

Welcome to Java

3. Static Block

A static block is executed only once when the class is loaded into memory.

Example

class Test {
static {
[Link]("Static block executed");
}

public static void main(String[] args) {


[Link]("Main method executed");
}
}

Output

Static block executed


Main method executed

4. Static Nested Class

A static nested class is a class declared with the static keyword inside another class.

Example

class Outer {
static class Inner {
void display() {
[Link]("Static Nested Class");
}
}

public static void main(String[] args) {


[Link] obj = new [Link]();
[Link]();
}
}

Output

Static Nested Class

Advantages of Static Members

 Memory is shared among all objects.


 Can be accessed without creating an object.
 Useful for constants, utility methods, and common data.

Classes and Objects in Java

Class

A class is a blueprint or template for creating objects. It defines the properties (variables) and behaviors
(methods) of an object.

Syntax

class ClassName {
// Data members (variables)
// Methods
}

Example

class Student {
String name;
int age;

void display() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}
Object

An object is an instance of a class. It is used to access the variables and methods of the class.

Syntax

ClassName objectName = new ClassName();

Program Example

class Student {
String name;
int age;

void display() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}

public static void main(String[] args) {


Student s1 = new Student();

[Link] = "Rahul";
[Link] = 20;

[Link]();
}
}

Output

Name: Rahul
Age: 20

Difference Between Class and Object

Class Object
Blueprint or template Instance of a class
Does not occupy memory until objects are created Occupies memory when created
Defines variables and methods Uses the variables and methods
Created using the class keyword Created using the new keyword
Definition

 Class: A user-defined data type that acts as a blueprint for creating objects.
 Object: A real-world entity or instance of a class that contains its own data and can perform the
actions defined by the class.

You might also like