Programming 2
Programming 2
Object-oriented programming (OOP) is a way of writing code by making "objects" that store information
and do things. It helps keep the code simple and easy to understand.
Java was introduced in 1995 by Sun Microsystems (which was later acquired by Oracle). It was designed
to be a platform-independent language, meaning it could run on different types of computers without
needing to be rewritten.
Java was created by James Gosling and his team at Sun Microsystems in 1991. James Gosling is often
called the "father of Java
Java has strong security features like sandboxing, bytecode verification, and access control to protect
against malicious activities. It also includes tools for encryption and secure data handling
Flyte is a tool that helps you create and run complex tasks, like data processing or machine learning,
automatically on the cloud. You write code (usually in Python) to define these tasks and how they work
together in a workflow.
File > New Project > Choose Project Type > Name Project > Finish
1. **Add a Class**:
Right-click on the `src` folder > New > Java Class > Enter class name > Click Finish.
2. **Add a Package**:
Right-click on the `src` folder > New > Package > Enter package name > Click Finish.
Using NetBeans:
Click on the project in the Projects window, then go to Run > Build Project or press F11.
Q10.What is package?
A package in Java is a way to organize related classes and interfaces into a folder-like structure. It helps
group similar classes together, making code easier to manage, maintain, and avoid naming conflicts. For
example, java.util is a package that contains utility classes like ArrayList and HashMap.
Q1What is class?
A class in Java is a blueprint or template for creating objects. It defines properties (attributes) and
behaviors (methods) that the objects created from the class will have. For example, a Car class might
have properties like color and speed, and behaviors like drive() and brake().
A class name in Java is the identifier used to represent a class. It typically starts with an uppercase letter
and follows camel case (e.g., Car, StudentRecord, EmployeeDetails). The class name is used to create
objects and to refer to the blueprint that defines the properties and behaviors of those objects.
**Data members** (also called **fields** or **attributes**) in a class are variables that hold the state
or properties of an object. They represent the data that an object will store. For example, in a `Car` class,
data members might include `color`, `model`, and `speed`. These are specific to each object created
from the class.
Q14.Define methods?
Methods in Java are functions defined inside a class that represent the actions or behaviors an object
can perform. They can take input (parameters), perform some task, and return a value. For example, a
Car class might have methods like drive(), brake(), or accelerate(), which define what actions the car can
perform
Comments in Java are non-executable lines of text used to explain and document the code. They are
ignored by the compiler and help programmers understand the code or leave notes for others.
A single-line comment in Java is used to add a note or explanation to a single line of code. It begins
with //, and everything after // on that line is ignored by the compile
Multi-line comments in Java are used to add comments that span multiple lines. They begin with /* and
end with */. Everything between these symbols is ignored by the compiler
UNIT: 2 VARIABLE AND CONSTANTS
Apologies for the confusion! Here's the syntax for declaring a variable in many
programming languages:
<variable_name> = <value>
In Java, literals are constant values that appear directly in the code, such as
numbers, characters, or strings. They represent data used by variables or
operations, like 5, 'A', or "Hello".
In Java, keywords are predefined reserved words that have a specific meaning and
cannot be used as identifiers. Examples include class, public, static, and int, which
define the structure and behavior of the program.
Relational operators in Java are used to compare two values, returning true or false
based on the result. Examples include ==, !=, <, >, <=, and >=.
Logical operators in Java are used to perform logical operations on boolean values,
returning true or false. The common logical operators are && (AND), || (OR), and !
(NOT).
Bitwise operators in Java perform operations on the individual bits of integer values.
Common bitwise operators include & (AND), | (OR), ^ (XOR), ~ (NOT), << (left
shift), and >> (right shift).
The increment operator (++) in Java increases the value of a variable by 1. It can be
used in two forms: prefix (++x) and postfix (x++), affecting when the increment
happens relative to the expression.
Q.9 Define Decrement operator?
The decrement operator (--) in Java decreases the value of a variable by 1. It can be
used as a prefix (--x) or postfix (x--), determining when the decrement occurs.
Example:
int x = 5;
Example:
int x = 5;
int y = x++; // y becomes 5, then x is incremented to 6
Q.12 What is prefix decrement operator?
The prefix decrement operator (--x) in Java decreases the value of a variable by 1
before it is used in an expression.
Example:
int x = 5;
int y = --x; // x is decremented to 4, then y becomes 4
Example:
A unary operator in Java is an operator that works with only one operand to perform
operations like increment, decrement, or negation.
Examples:
++x (increment)
--x (decrement)
-x (negation)
Example:
int x = 10;
int result = (x > 5) ? 100 : 200; // If x is greater than 5, result is 100, else 200
The modulus operator (%) in Java returns the remainder of a division between two
numbers.
Example:
An infinite while loop in Java is a loop that keeps running endlessly because its condition is
always true. For example:
while (true) {
The for-each loop in Java is used to easily go through all items in an array or list without
needing an index. Example:
No, the for-each loop in Java doesn’t have a direct way to access an iteration counter. To track
the index, use a regular for loop instead. Example:
}
Q.4 Advantages of declaring loop variable as final in enhanced
for-loop?
Q.5 Does returning a value from the loop body break the loop?
Yes, returning a value from the loop body immediately exits the loop and the entire method, stopping
further iterations.
Q.6 What happen when we forget break in switch case?
If you forget the break in a switch case, the code will "fall through," meaning it will keep
executing the next cases until it finds a break or the switch ends.
You can exit a loop early using the break statement, which stops the loop immediately when a
condition is met
A flowchart is a diagram that shows the steps in a process using shapes like arrows, circles, and
rectangles. It helps to visualize how something works.
In a switch case, the break statement stops the execution of the current case and exits the
switch, preventing it from running the next cases.
Dead Code:
1. Code that will never run, usually because it's placed after a return or an infinite
loop.
2. It serves no purpose and should be removed to improve code quality.
Unreachable Code:
1. Code that cannot be executed due to the program’s flow (like after a break,
return, or throw).
2. The compiler usually flags unreachable code as an error to indicate a logical
mistake.
A selection statement helps you choose what to do based on a condition, like if or switch.
While loop: The condition is checked before the loop starts, so the code may not run at
all if the condition is false.
Do-while loop: The code runs at least once, as the condition is checked after the loop
runs.
No, in Java, you cannot use a double variable in a switch case. Switch cases only support variables of
types like int, char, byte, short, String, and enum.
UNIT: 5 OBJECT ORIENTED PROGRAMMING
Static members are not inherited by subclasses because they belong to the class, not instances.
However, subclasses can access them using the parent class name.
Q.3 What happens if the parent and the child class have a field with same identifier?
If the parent and child class have a field with the same name, the child’s field hides the parent’s
field. To access the parent’s field, use super.fieldName.
No, constructors and initializers are not inherited by subclasses, but the child class can call the
parent’s constructor using super().
Q.5 How do you restrict a member of a class from inheriting by its subclasses?
To restrict a member from being inherited, declare it as private, so it’s accessible only within
the same class. You can also use final for methods to prevent overriding.
Java does not support multiple inheritance with classes, but it can be achieved using interfaces.
A class can implement multiple interfaces using the implements keyword.
No, a class cannot extend itself in Java because it would create an infinite inheritance loop,
Wqhich is not allowed.
A private method cannot be overridden because it is not accessible outside its own class.
However, a subclass can define a new method with the same name, but it will be a separate
method, not an override.
Inheritance in Java is used to reuse code, reduce redundancy, and establish a relationship
between classes. It helps in better code organization and makes maintenance easier.
Multiple inheritance is not supported in Java to avoid conflicts when two parent classes have
the same method (Diamond Problem). This prevents ambiguity and keeps the code simple and
clear.
Access modifiers are keywords in object-oriented programming that control the visibility of
classes, methods, and variables. They include public, private, protected, and default, defining
how accessible a member is within or outside a class.
nformation hiding is the practice of restricting direct access to an object's data and only allowing
controlled interaction through methods. This helps in improving security, reducing complexity, and
making the code easier to maintain.
A real-life example of method overriding is a Bank's Interest Rate System, where a parent class Bank
has a method getInterestRate(). Different banks like HBLBank and MeezanBank override this
method to provide their specific interest rates.
Q. 24 What is encapsulation?
Encapsulation is the process of wrapping data and methods inside a class while restricting direct access
to the data. It enhances security, reduces complexity, and allows controlled access through getters and
setters.
Q. 25 How we can achieve encapsulation in java?
We achieve encapsulation in Java by declaring variables as private and providing public getter and
setter methods to access and modify them, ensuring controlled data access.
Q. 26 What is abstraction?
Abstraction is the process of hiding implementation details and showing only the essential
features of an object. In Java, it is achieved using abstract classes and interfaces to simplify
complex systems.
An abstract class in Java is a class that cannot be instantiated and is used to provide a base for other
classes. It can have both abstract (unimplemented) and non-abstract (implemented) methods,
allowing subclasses to define specific behaviors.
UNIT : 8 EXCEPTION HANDLING
In Java, exceptions are problems that occur during program execution and can usually be handled by the
program, like input errors or file not found.
Errors are serious problems like system crashes or memory issues, and they cannot be handled by the
program easily.
Yes, we can manually throw an exception in Java using throw. It’s used to trigger custom errors
during code execution.