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

Java Notes1

The document provides an overview of Object-Oriented Programming (OOP) principles such as Abstraction, Inheritance, Polymorphism, and Encapsulation, along with a comparison between Procedural Oriented Programming and OOP. It includes explanations of Java's primitive data types, variable declarations, and examples of Java programs that demonstrate these concepts. Additionally, it discusses the advantages of OOP principles and how they enhance code reusability, security, and maintainability.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views19 pages

Java Notes1

The document provides an overview of Object-Oriented Programming (OOP) principles such as Abstraction, Inheritance, Polymorphism, and Encapsulation, along with a comparison between Procedural Oriented Programming and OOP. It includes explanations of Java's primitive data types, variable declarations, and examples of Java programs that demonstrate these concepts. Additionally, it discusses the advantages of OOP principles and how they enhance code reusability, security, and maintainability.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Srishyla Education Trust ®

GM UNIVERSITY
(Established under the Karnataka State Act No. 19 of 2023)
Post Box no-4, PB Road, Davangere-577006
FACULTY OF ENGINEERING AND TECHNOLOGY
School of Computer Science and Technology

An Overview of Object-Oriented Programming: OOPS basic Principles: Abstraction, Inheritance,


Polymorphism and Encapsulation.
Overview of Java: Data Types, Variables, Arrays, Operators.

Q1. Define Object-Oriented Programming. Write the difference between Procedural Oriented Programming &
Object-Oriented Programming (CO2)

OOPS is a programming paradigm that organizes software design around objects, which combine data
(attributes) and methods (behaviors).

Procedural Oriented Programming Object-Oriented Programming


In procedural programming, the program is In object-oriented programming, the program is
divided into small parts called functions. divided into small parts called objects.
Procedural programming follows a top-down Object-oriented programming follows a bottom-
approach. up approach.
There is no access specifier in procedural Object-oriented programming has access
programming. specifiers like private, public, protected, etc.
Procedural programming does not have any Object-oriented programming provides data
proper way of hiding data so it is less secure. hiding so it is more secure.
In procedural programming, there is no concept In object-oriented programming, the concept of
of data hiding and inheritance data hiding and inheritance is used.
Procedural programming is based on the unreal Object-oriented programming is based on
world. the real world
Procedural programming is used for designing Object-oriented programming is used for
medium-sized programs. designing large and complex programs.
Procedural programming uses the concept of Object-oriented programming uses the concept
procedure abstraction. of data abstraction.
Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.
Srishyla Education Trust ®

GM UNIVERSITY
(Established under the Karnataka State Act No. 19 of 2023)
Post Box no-4, PB Road, Davangere-577006
FACULTY OF ENGINEERING AND TECHNOLOGY
School of Computer Science and Technology
Q2: List and Explain the four basic principles of OOPS. (CO2)

Abstraction, Inheritance, Polymorphism, and Encapsulation.


All object-oriented programming languages provide mechanisms that help to implement the object-oriented
model.

➢ Abstraction in Object-Oriented Programming (OOPS) is the process of hiding the internal


implementation details of a system and exposing only the essential features to the user. It allows
programmers to focus on what an object does rather than how it does it, thereby reducing
complexity and making code more modular and maintainable. In Java, abstraction is achieved using
abstract classes and interfaces, where abstract methods define only the method signature, leaving
the actual implementation to the subclasses. For example, when we use an ATM machine, we can
withdraw cash, check balance, or deposit money without knowing the internal banking processes,
database interactions, or encryption methods. Similarly, when driving a car, we use the steering
wheel, accelerator, and brake, but the underlying engine mechanics remain hidden. This separation
between the interface (visible to the user) and the implementation (hidden details) not only
simplifies usage but also enhances security by restricting direct access to sensitive operations.
Abstraction plays a crucial role in large software systems by promoting loose coupling, modularity,
and flexibility, making it one of the core principles of OOPS.

➢ Encapsulation in Java is a fundamental concept in object-oriented programming (OOP) that refers to the
wrapping up of data and methods that operate on that data within a single unit, which is called a class in
Java. Java Encapsulation is a way of hiding the implementation details of a class from outside access and
only exposing a public interface that can be used to interact with the class. Another way to think about
encapsulation is, that it is a protective shield that prevents the data from being accessed by the code
outside this shield.
Srishyla Education Trust ®

GM UNIVERSITY
(Established under the Karnataka State Act No. 19 of 2023)
Post Box no-4, PB Road, Davangere-577006
FACULTY OF ENGINEERING AND TECHNOLOGY
School of Computer Science and Technology

Fig: Encapsulation: public methods can be used to protect private data.


➢ In Java, encapsulation is achieved by declaring the instance variables of a class as private, which means
they can only be accessed within the class.
➢ Technically in encapsulation, the variables or data of a class is hidden from any other class and can be
accessed only through any member function of its own class in which it is declared.
➢ As in encapsulation, the data in a class is hidden from other classes using the data hiding concept which is
achieved by making the members or methods of a class private, and the class is exposed to the end-user or
the world without providing any details behind implementation using the abstraction concept, so it is also
known as a combination of data-hiding and abstraction.
➢ Encapsulation can be achieved by Declaring all the variables in the class as private and writing public
methods in the class to set and get the values of variables.
Advantages of Encapsulation
➢ Data Hiding: it is a way of restricting the access of our data members by hiding the implementation details.
Encapsulation also provides a way for data hiding. The user will have no idea about the inner
implementation of the class. It will not be visible to the user how the class is storing values in the variables.
The user will only know that we are passing the values to a setter method and variables are getting
initialized with that value.
➢ Increased Flexibility: We can make the variables of the class read-only or write-only depending on our
requirements.
➢ Reusability: Encapsulation also improves the re-usability and is easy to change with new requirements.
➢ Testing code is easy: Encapsulated code is easy to test for unit testing.
Srishyla Education Trust ®

GM UNIVERSITY
(Established under the Karnataka State Act No. 19 of 2023)
Post Box no-4, PB Road, Davangere-577006
FACULTY OF ENGINEERING AND TECHNOLOGY
School of Computer Science and Technology
➢ Freedom to programmer in implementing the details of the system: This is one of the major advantage of
encapsulation that it gives the programmer freedom in implementing the details of a system. The only
constraint on the programmer is to maintain the abstract interface that outsiders see.

1. Inheritance
➢ Java, Inheritance is an important pillar of OOP. It is the mechanism in Java by which one class is allowed to
inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes
based on existing ones. A class that inherits from another class can reuse the methods and fields of that
class. In addition, you can add new fields and methods to your current class as well.

Advantages of Inheritance
• Code Reusability: The code written in the Superclass is common to all subclasses. Child classes can
directly use the parent class code.
• Method Overriding: Method Overriding is achievable only through Inheritance. It is one of the ways by
which Java achieves Run Time Polymorphism.
• Abstraction: The concept of abstract where we do not have to provide all details is achieved through
inheritance. Abstraction only shows the functionality to the user.

Important Terminologies Used in Java Inheritance


• Class: Class is a set of objects which shares common characteristics/ behavior and common
properties/ attributes. Class is not a real-world entity. It is just a template or blueprint or prototype
from which objects are created.
Srishyla Education Trust ®

GM UNIVERSITY
(Established under the Karnataka State Act No. 19 of 2023)
Post Box no-4, PB Road, Davangere-577006
FACULTY OF ENGINEERING AND TECHNOLOGY
School of Computer Science and Technology
• Super Class/Parent Class: The class whose features are inherited is known as a superclass (or a base
class or a parent class).
• Sub Class/Child Class: The class that inherits the other class is known as a subclass (or a derived class,
extended class, or child class). The subclass can add its own fields and methods in addition to the
superclass fields and methods.
• Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class
and there is already a class that includes some of the code that we want, we can derive our new class
from the existing class. By doing this, we are reusing the fields and methods of the existing class.

2. 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: In Java Polymorphism is mainly divided into two types

1. Compile-time Polymorphism: In Java It is also known as static polymorphism. This type of polymorphism is
achieved by function overloading: When there are multiple functions with the same name but different
parameters then these functions are said to be overloaded. Functions can be overloaded by changes in the
number of arguments or/and a change in the type of arguments.

2. Runtime Polymorphism: It is also known as Dynamic Method Dispatch. It is a process in which a function
call to the overridden method is resolved at Runtime. This type of polymorphism is achieved by Method
Overriding. Method overriding, on the other hand, occurs when a derived class has a definition for one of
the member functions of the base class. That base function is said to be overridden.

Advantages of Polymorphism in Java


➢ Increases code reusability by allowing objects of different classes to be treated as objects of a common
class.
➢ Improves readability and maintainability of code by reducing the amount of code that needs to be written
and maintained.
➢ Supports dynamic binding, enabling the correct method to be called at runtime, based on the actual class
of the object.
Srishyla Education Trust ®

GM UNIVERSITY
(Established under the Karnataka State Act No. 19 of 2023)
Post Box no-4, PB Road, Davangere-577006
FACULTY OF ENGINEERING AND TECHNOLOGY
School of Computer Science and Technology
➢ Enables objects to be treated as a single type, making it easier to write generic code that can handle
objects of different types.
Q3. Explain Primitive Types in java with suitable examples (CO2)

Data Default
Size Range Example Explanation
Type Value
Used for saving memory
byte 8 bits -128 to 127 0 byte b = 100; in large arrays; faster
than int.
Useful when memory
short 16 bits -32,768 to 32,767 0 short s = 2000; savings matter. Rarely
used.
Default data type for
int 32 bits -2,147,483,648 to 2,147,483,647 0 int age = 25; integers in Java. Most
commonly used.
Used when int is not
-9,223,372,036,854,775,808 to long population
long 64 bits 0L = 7000000000L; sufficient for very large
9,223,372,036,854,775,807
numbers.
Stores fractional numbers
~1.4E-45 to 3.4E+38 (7 digits float price = with less precision
float 32 bits 0.0f 99.99f;
precision) (useful in graphics,
games).
~4.9E-324 to 1.7E+308 (15 digits double pi = Default type for decimal
double 64 bits 0.0d 3.14159;
precision) values; high precision.
Represents characters
char grade =
char 16 bits Unicode (\u0000 to \uFFFF) '\u0000' 'A'; (letters, digits, symbols).
Supports Unicode.
boolean
1 bit (JVM isJavaFun =
Represents logical values
boolean true or false false
dependent) true; only (true/false).
Srishyla Education Trust ®

GM UNIVERSITY
(Established under the Karnataka State Act No. 19 of 2023)
Post Box no-4, PB Road, Davangere-577006
FACULTY OF ENGINEERING AND TECHNOLOGY
School of Computer Science and Technology

Q4. Develop a Java program that uses all primitive data with examples of variable declaration, initialization,
and output. (CO3)

Output:

Q5. Define variable. Develop a java program to declare and print char variables. (CO3)
A variable is a named memory location used to store data.
Srishyla Education Trust ®

GM UNIVERSITY
(Established under the Karnataka State Act No. 19 of 2023)
Post Box no-4, PB Road, Davangere-577006
FACULTY OF ENGINEERING AND TECHNOLOGY
School of Computer Science and Technology

Output:

Q6. Design a java program that accepts the radius as input and computes the area of a circle. (CO3)

Output:

Q7. Apply the concept of variables and arithmetic operations in Java to write a program that computes the
miles traveled by light in a specified number of days. (CO3)

• Variables → to store values like speed of light, number of days, seconds in a day.
• Arithmetic Operations → to perform multiplication and compute the total distance traveled.
• Constants → speed of light is fixed and should be represented as a constant.

The formula used is:


Srishyla Education Trust ®

GM UNIVERSITY
(Established under the Karnataka State Act No. 19 of 2023)
Post Box no-4, PB Road, Davangere-577006
FACULTY OF ENGINEERING AND TECHNOLOGY
School of Computer Science and Technology
Distance=Speed of Light × Seconds in a Day

Output:

Q8. Define Array and Illustrate the use of arrays in Java by providing a simple program.
An array in Java is a collection of elements of the same data type stored in contiguous memory locations.

• Arrays are indexed, meaning each element can be accessed using its position (starting from index 0).
• The size of an array is fixed once declared.

Syntax for array declaration:


type array_name[]=new type[size];

Example 1: Declaring and Using an Array


class ArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50}; // array initialization

[Link]("First Element: " + numbers[0]); // access element


[Link]("Array Length: " + [Link]); // size of
array
}
}
Srishyla Education Trust ®

GM UNIVERSITY
(Established under the Karnataka State Act No. 19 of 2023)
Post Box no-4, PB Road, Davangere-577006
FACULTY OF ENGINEERING AND TECHNOLOGY
School of Computer Science and Technology

Output:

First Element: 10
Array Length: 5

Q9. Explain the different ways of declaring arrays in java (CO2)

1. Declaration + Initialization (with values directly)

You can declare and initialize an array in one step.

int[] numbers = {10, 20, 30, 40, 50};

2. Declaration First, Initialization Later

You can declare an array variable first and then allocate memory later.

int[] numbers; // declaration


numbers = new int[3]; // memory allocation
numbers[0] = 5;
numbers[1] = 15;
numbers[2] = 25;

Sample Program:
class ArrayDeclaration {
public static void main(String[] args) {
// 1. Declaration + Size
int[] arr1 = new int[3];
arr1[0] = 1; arr1[1] = 2; arr1[2] = 3;

// 2. Declaration + Initialization
int[] arr2 = {10, 20, 30, 40};

// 3. Declaration then Initialization


int[] arr3;
arr3 = new int[]{100, 200, 300};

// Printing arrays
[Link]("arr1[0] = " + arr1[0]);
[Link]("arr2[2] = " + arr2[2]);
[Link]("arr3[1] = " + arr3[1]);
}
}

Output:

arr1[0] = 1
arr2[2] = 30
arr3[1] = 200
Srishyla Education Trust ®

GM UNIVERSITY
(Established under the Karnataka State Act No. 19 of 2023)
Post Box no-4, PB Road, Davangere-577006
FACULTY OF ENGINEERING AND TECHNOLOGY
School of Computer Science and Technology

Q10. Differentiate between single-dimensional and multi-dimensional arrays in Java using a tabular format.
(CO3)

Aspect Single-Dimensional Array Multi-Dimensional Array


Stores elements in a linear (one row) Stores elements in multiple rows and columns
Definition
sequence. (matrix form).
Syntax int[] arr = new int[5]; int[][] arr = new int[3][3];
int[][] arr = {{1,2,3}, {4,5,6},
Initialization int[] arr = {10, 20, 30};
{7,8,9}};
Accessed using two or more indices:
Accessing Elements Accessed using one index: arr[2].
arr[1][2].
Can have two or more dimensions (like a table
Dimension Has only one dimension (like a list).
or cube).
Memory Stored in row-major order (rows stored
Stored in contiguous linear memory.
Representation sequentially in memory).
More complex in declaration, initialization, and
Complexity Simple and easy to use.
traversal.
Suitable for storing simple lists: marks, Suitable for storing tabular data: matrices, game
Use Case
ages, salaries. boards, graphs.
Slower and uses more memory due to multiple
Performance Faster and requires less memory.
indices.
Example Output {10, 20, 30} {{1,2,3}, {4,5,6}, {7,8,9}}
Traversal Single loop (for) is sufficient. Nested loops (for inside for) are required.

Q11. Explain Arithmetic Operators with sample programs. (CO2)


Arithmetic operators in Java are used to perform basic mathematical operations on variables and values.

Operator Description Example Result


+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division (quotient) 10 / 3 3
% Modulus (remainder) 10 % 3 1
Example:
class ArithmeticOperatorsDemo {
public static void main(String[] args) {
int a = 15, b = 4;
Srishyla Education Trust ®

GM UNIVERSITY
(Established under the Karnataka State Act No. 19 of 2023)
Post Box no-4, PB Road, Davangere-577006
FACULTY OF ENGINEERING AND TECHNOLOGY
School of Computer Science and Technology
[Link]("Arithmetic Operators in Java");
[Link]("-----------------------------");
[Link]("a + b = " + (a + b));
[Link]("a - b = " + (a - b));
[Link]("a * b = " + (a * b));
[Link]("a / b (integer division) = " + (a / b));
[Link]("a / b (floating division) = " + ((double) a / b));
[Link]("a % b = " + (a % b));
}
}
Q12. Explain Bitwise Operators with sample programs. (CO2)
The Bitwise Operators
Java defines several bitwise operators that can be applied to the integer types: long, int, short, char, and byte.
These operators act upon the individual bits of their operands.
1. The Bitwise Logical Operators

The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome of each operation.

a. The Bitwise NOT


Also called the bitwise complement, the unary NOT operator, ~, inverts all of the bits of its operand. For
example, the number 42, which has the following bit pattern: 00101010 becomes 11010101 after the NOT
operator is applied.
b. The Bitwise AND
The AND operator, &, produces a 1 bit if both operands are also 1. A zero is produced in all other cases.
Srishyla Education Trust ®

GM UNIVERSITY
(Established under the Karnataka State Act No. 19 of 2023)
Post Box no-4, PB Road, Davangere-577006
FACULTY OF ENGINEERING AND TECHNOLOGY
School of Computer Science and Technology
Here is an example:

c. The Bitwise OR
The OR operator, |, combines bits such that if either of the bits in the operands is a 1, then the resultant
bit is a 1, as shown here:

d. The Bitwise XOR


The XOR operator, ^, combines bits such that if exactly one operand is 1, then the result is 1. Otherwise,
the result is zero.

Example:
Srishyla Education Trust ®

GM UNIVERSITY
(Established under the Karnataka State Act No. 19 of 2023)
Post Box no-4, PB Road, Davangere-577006
FACULTY OF ENGINEERING AND TECHNOLOGY
School of Computer Science and Technology
Output:

Q13. Explain the Relational Operators with sample program. (CO2)


Relational Operators
The relational operators determine the relationship that one operand and to the other operand. Specifically, they
determine equality and ordering. The relational operators are shown here:

The outcome of these operations is a boolean value. The relational operators are most frequently used in the
expressions that control the if statement and the various loop statements.
Example 1:
Srishyla Education Trust ®

GM UNIVERSITY
(Established under the Karnataka State Act No. 19 of 2023)
Post Box no-4, PB Road, Davangere-577006
FACULTY OF ENGINEERING AND TECHNOLOGY
School of Computer Science and Technology

Output:

Q14. Explain the Boolean Logical Operators with sample program. (CO2)
Boolean Logical Operators
The Boolean logical operators, operate only on boolean operands. All of the binary logical operators combine two
boolean values to form a resultant boolean value.
Srishyla Education Trust ®

GM UNIVERSITY
(Established under the Karnataka State Act No. 19 of 2023)
Post Box no-4, PB Road, Davangere-577006
FACULTY OF ENGINEERING AND TECHNOLOGY
School of Computer Science and Technology

Example:

Output:

Q15. Explain the Short-Circuit Logical Operators with sample program. (CO2)
Short-Circuit Logical Operators
These are secondary versions of the Boolean AND and OR operators, and are commonly known as short-circuit
logical operators.
1. AND(&&) short circuit:
In the case of AND, the expression is evaluated until we get one false result because the result will always
be false, independent of the further conditions. If there is an expression with &&(logical AND), and the first
operand itself is false, then a short circuit occurs, the further expression is not evaluated, and false is
returned.
2. OR ( || ) short circuit:
In the case of OR, the expression is evaluated until we get one true result because the result will always be
true, independent of the further conditions. If there is an expression with || (logical OR), and the first
operand itself is true, a short circuit occurs, evaluation stops, and true is returned.
Srishyla Education Trust ®

GM UNIVERSITY
(Established under the Karnataka State Act No. 19 of 2023)
Post Box no-4, PB Road, Davangere-577006
FACULTY OF ENGINEERING AND TECHNOLOGY
School of Computer Science and Technology
Example:

Output:

Q16. Explain the ? Operator with sample program. (CO2)


The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then-else statements. The
? has this general form:

Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true, then
expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ?: operation is that of the
expression evaluated.
Example:
Srishyla Education Trust ®

GM UNIVERSITY
(Established under the Karnataka State Act No. 19 of 2023)
Post Box no-4, PB Road, Davangere-577006
FACULTY OF ENGINEERING AND TECHNOLOGY
School of Computer Science and Technology
Output:
Srishyla Education Trust ®

GM UNIVERSITY
(Established under the Karnataka State Act No. 19 of 2023)
Post Box no-4, PB Road, Davangere-577006
FACULTY OF ENGINEERING AND TECHNOLOGY
School of Computer Science and Technology

You might also like