Java Programming
Java Programming
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
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
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?
The if-else statement executes one block if the condition is true and another if false.
Syntax:
if(condition)
{
}
else
{
}
16. Explain switch statement.
while do-while
Entry controlled Exit controlled
May execute zero times Executes at least once
Class Object
Blueprint Instance
Logical entity Physical entity
No memory Occupies memory
Default Constructor
No parameters
Initializes default values
Parameterized Constructor
Accepts parameters
Initializes user-defined values
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
Overloading Overriding
Same class Different classes
Different parameters Same parameters
Compile-time Runtime
public private
Accessible everywhere Accessible only within class
Maximum visibility Minimum visibility
Code reusability
Easy maintenance
Reduces redundancy
Supports polymorphism
Faster development
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.
PART-B
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;
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 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;
}
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
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.
Example:
public class Hello {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
BASIC PROGRAM:
// Driver
Class class
GFG {
// main function
public static void main(String[] args)
{
// Declare the
variables int num;
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.
twos-
complement 0 8 bits (none) -128 to 127
byte integer
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
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Example:
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:
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:
The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.
Example:
Example:
Example:
float f1 = 234.5f
Example:
double d1 = 12.3
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);
}
}
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.
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:
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”};
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:
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)
{
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:
Here:
Syntax
Example
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
Output
Number = 100
Characteristics
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);
}
Output
Name = Alice
Characteristics
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);
}
[Link]();
[Link]();
}
}
Output
Characteristics
int age;
double salary;
String studentName;
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.
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
Example Program
Output
Addition = 30
Subtraction = 10
Multiplication = 200
Division = 2
Remainder = 0
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
[Link](a == b);
[Link](a != b);
[Link](a > b);
[Link](a < b);
}
}
Output
false
true
false
true
3. Logical Operators
Operator Meaning
&& Logical AND
`
! Logical NOT
Example Program
Output
false
true
false
4. Assignment Operators
Example Program
a += 5;
[Link](a);
a *= 2;
[Link](a);
}
}
Output
15
30
5. Unary Operators
Example Program
[Link](-a);
Output
-10
false
Operator Meaning
++ Increment
-- Decrement
Example Program
a--;
[Link](a);
}
}
Output
6
5
7. Bitwise Operators
Operator Meaning
& Bitwise AND
` `
^ Bitwise XOR
~ Bitwise NOT
Example Program
Output
1
7
6
8. Shift Operators
Example Program
Output
16
4
Syntax
Example Program
[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.
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
if (num > 0)
{ [Link]("Number is
positive.");
} else if (num < 0)
{ [Link]("Number is
negative.");
} else {
[Link]("Number is zero.");
}
}
}
NESTED IF SATEMENTS:
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.
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 {
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;
}
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
[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:
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.
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:
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.
Default Constructor
Parameterized Constructor
Example:
// 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
Example:
Output
PUBLIC:
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:
DEFAULT (PACKAGE-PRIVATE):
EXAMPLE:
void defaultMethod() {
// This method can be accessed within the same package.
}
}
GARBAGE COLLECTION
In java, garbage means unreferenced objects.
Compile-time Polymorphism
Runtime Polymorphism
METHOD OVERLOADING:
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);
[Link]("Breadth="+b1);
[Link]("Area of Rect="+a);
}
class Movload {
[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.
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);
class Mconsovload {
}
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.
import
[Link].*; class
Demo { int x,y;
Demo(int x1,int
y1) {
x=x1;
y=y1;
}
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 {
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.
import [Link].*;
class Demo { int x;
Demo(int x1 ) {
x=x1;
}
void display( ) {
[Link]("Demo1 y: "+y);
}
}
void display( )
[Link]("Demo2 Z: "+z);
[Link]("Sum = "+s);
}
}
class Dynmtddispch {
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
}
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";
}
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");
}
}
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");
}
}
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;
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
}
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.
1. Static Variable
Example
class Student {
static String college = "ABC College";
String name;
Student(String name) {
[Link] = name;
}
void display() {
[Link](name + " - " + college);
}
[Link]();
[Link]();
}
}
Output
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");
}
Output
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");
}
}
Output
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
Program Example
class Student {
String name;
int age;
void display() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
[Link] = "Rahul";
[Link] = 20;
[Link]();
}
}
Output
Name: Rahul
Age: 20
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.