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

Java Bytecode and Control Structures

Encapsulation in Java bundles code and data together, such as wrapping related variables and methods inside a class. This provides benefits like data

Uploaded by

pompom
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)
16 views19 pages

Java Bytecode and Control Structures

Encapsulation in Java bundles code and data together, such as wrapping related variables and methods inside a class. This provides benefits like data

Uploaded by

pompom
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

OBJECT ORIENTED PROGRAMMING and

DESIGN with JAVA

ACTIVITY-04

Questions:

1. Study and present how does bytecode work in java


a) Study and present how does bytecode work in java

What is Java Bytecode ?


Java bytecode is the instruction set for the Java Virtual Machine. It acts similar
to an assembler which is an alias representation of a C++ code. As soon as a
java program is compiled, java bytecode is generated. In more apt terms, java
bytecode is the machine code in the form of a .class file. With the help of java
bytecode we achieve platform independence in java.

How does it work ?


When we write a program in Java, firstly, the compiler compiles that program
and a bytecode is generated for that piece of code. When we wish to run this
.class file on any other platform, we can do so. After the first compilation, the
bytecode generated is now run by the Java Virtual Machine and not the
processor in consideration. This essentially means that we only need to have
basic java installation on any platforms that we want to run our code on.
Resources required to run the bytecode are made available by theJava Virtual
Machine, which calls the processor to allocate the required resources. JVM's
are stack-based so they stack implementation to read the codes.
Advantage of Java Bytecode
Platform independence is one of the sole reasons for which James Gosling
started the formation of java and it is this implementation of bytecode which
helps us to achieve this.
Hence bytecode is a very important component of any java [Link] set
of instructions for the JVM may differ from system to system but all can
interpret the bytecode.
A point to keep in mind is that bytecodes are non-runnable codes and rely on
the availability of an interpreter to execute and thus the JVM comes into play.

Bytecode is essentially the machine level language which runs on the Java
Virtual Machine. Whenever a class is loaded, it gets a stream of bytecode per
method of the class. Whenever that method is called during the execution of a
program, the bytecode for that method gets [Link] not only compiles
the program but also generates the bytecode for the program.

Thus, we have realised that the bytecode implementation makes Java a


platform-independent language. This helps to add portability to Java which is
lacking in languages like C or C++. Portability ensures that Java can be
implemented on a wide array of platforms like desktops, mobile devices,
servers and many more.

Supporting this, Sun Microsystems captioned JAVA as "write once, read


anywhere" or "WORA" in resonance to the bytecode interpretation.
OBJECT ORIENTED PROGRAMMING and
DESIGN with JAVA

ACTIVITY-05

Questions:

1. Present nesting of conditional and iterative statements


considering a use case
Conditional Statements

Conditional Statements come under Control Structures in Java. As the same


suggests, it controls the flow of the execution of the program. Controlling here
means branching, decision-making, and iterating.

Generally, there are 3 types of Control Structures in Java:

● Conditional Statements or Decisional Statements (if, if-else, switch)


● Iteration Statements or Loops (for, while, do-while, for-each)
● Jump Statements (break, continue, return)

Conditional Statements in Java


Conditional statements in Java are the executable block of code (or branch to
a specific code) dependent on certain conditions. These statements are also
known as decision statements or selection statements in Java.

Following are the statements covered under conditional statements in Java:

● If statement
● If else statement
● Switch Statement

Nested If-Else Statements

The nested if-else statements are statements that incorporate more than one
if-else clause.

Syntax

if (condition)
{
//Statements set 1
}
else if (condition 2)
{
//Statements set 2
}
...

else
{
//Statements to be executed if no condition is satisfied.
}

Example

class nested_if_else_condition {
public static void main(String[] args) {
double total_marks = 382;
char grade;
double perc = (total_marks/500)*100;
if (perc >= 80)
{
grade = 'A';
}
else if ((perc >=70) && (perc <80))
{
grade = 'B';
}
else if ((perc >=60) && (perc <70))
{
grade = 'c';
}
else
{
grade = 'D';
}
[Link]("The percentage of the student is: " +perc);
[Link]("\n The grade of the student is: " +grade);
}
}

Output
The percentage of the student: 76.4
The grade of the student is: B
Nested Loop

Nested loop means a loop statement inside another loop statement. That is
why nested loops are also called “loop inside loop“.

Java Nested for Loop

If we have a for loop inside another loop, it is known as nested for loop. The
inner loop executes completely whenever the outer loop executes.

Example

[Link]
1. public class NestedForExample {
2. public static void main(String[] args) {
3. //loop of i
4. for(int i=1;i<=3;i++){
5. //loop of j
6. for(int j=1;j<=3;j++){
7. [Link](i+" "+j);
8. }//end of i
9. }//end of j
10. }
11. }

Output

11
12
13
21
22
23
31
32
33
Nested while loop
When a while loop exists inside the body of another while loop, it is known as
a nested while loop in Java. Initially, the outer loop executes once and the
afterwards inner loop begins to execute. Execution of the inner loop continues
until the condition of the inner loop is satisfied(until the test expression is
false).
Once the Condition of the inner loop is satisfied, the flow of control comes out
to the outer loop for next iteration.

Example

class nestedwhile{
public static void main(String args[]){
int i=1,j=1;
while(i<=10)
{
while(j<=10)
{
[Link](j);
j++;
}
i++;
[Link]("");
j=1;
}
}
}

Output

12345678910
12345678910
12345678910
12345678910
12345678910
12345678910
12345678910
12345678910
12345678910
12345678910
Nested do-while Loop

one do-while loop inside another do-while loop is known as nested do -while
loop

Example

class NestedDoWhile{
public static void main(String args[]){
int row=1,column=1;
int x;
do{
x=4;
do{
[Link]("");
x--;
}while(x>=row);
column=1;
do{
[Link](column+" ");
column++;

}while(column<=5);
[Link](" ");
row++;
}while (row<=5);
}

Output

12345
12345
12345
12345
12345
OBJECT ORIENTED PROGRAMMING and
DESIGN with JAVA

ACTIVITY-06

Questions:

1. Identify advantages and disadvantages of

a) Encapsulation

b) Inheritance

c) Abstraction

d) Polymorphism
a) Encapsulation in Java
Encapsulation in Java is a process of wrapping code and data together into a
single unit, for example, a capsule which is mixed with several medicines.
We can create a fully encapsulated class in Java by making all the data
members of the class private. Now we can use setter and getter methods to
set and get the data in it.
The Java Bean class is the example of a fully encapsulated class.

Advantages of Encapsulation

● Data Protection: The program runner will not be able to identify or see
which methods are present in the code. Therefore he/she doesn’t get
any chance to change any specific variable or data and hinder the
running of the program.

● Flexibility: The code which is encapsulated looks more cleaner and


flexible, and can be changed as per the needs. We can change the
code read-only or write-only by getter and setter methods. This also
helps in debugging the code if needed.

● Reusability: The methods can be changed and the code is reusable.

Disadvantages of Encapsulation
● Code Size:The length of the code increases drastically in the case of
encapsulation as we need to provide all the methods with the specifiers.

● More Instructions: As the size of the code increases, therefore, you


need to provide additional instructions for every method.

● Increased code execution: Encapsulation results in an increase in the


duration of the program execution. It is because more instructions are
added to the code therefore they require more time to execute.
b) Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviours of a parent object. It is an important part of OOPs
(Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that
are built upon existing classes. When you inherit from an existing class, you
can reuse methods and fields of the parent class. Moreover, you can add new
methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a
parent-child relationship.

Advantages of Inheritance

● Minimising duplicate code: Key benefits of Inheritance include


minimising the identical code as it allows sharing of the common code
among other subclasses.

● Flexibility: Inheritance makes the code flexible to change, as you will


adjust only in one place, and the rest of the code will work smoothly.

● Overriding: With the help of Inheritance, you can override the methods
of the base class.

● Data Hiding: The base class in Inheritance decides which data to be


kept private, such that the derived class will not be able to alter it.

Disadvantages of Inheritance

● No Independence: One of the main disadvantages of Inheritance in


Java is that two classes, both the base and inherited class, get tightly
bound by each other. In simple terms, Programmers can not use these
classes independently of each other.

● Decreases Execution Speed: Another con of Inheritance is that it


decreases the execution speed because Inheritance execution takes
time and effort.

● Refactoring the Code: If the user deletes the Super Class, then they
have to refactor it if they have used it.
c) Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only


functionality to the user.

Data Abstraction is the property by virtue of which only the essential details
are displayed to the user. The trivial or the non-essential units are not
displayed to the user. Ex: A car is viewed as a car rather than its individual
components.

Advantages of Abstraction

● It reduces the complexity of viewing things.

● Avoids code duplication and increases reusability.

● Helps to increase the security of an application or program as only


essential details are provided to the user.

● It improves the maintainability of the application.

● It improves the modularity of the application.

Disadvantages of Abstraction in Java:

● Abstraction can make it more difficult to understand how the system


works.

● It can lead to increased complexity, especially if not used properly.

● May limit the flexibility of the implementation.

● Abstraction can add unnecessary complexity to code if not used


appropriately, leading to increased development time and effort.

● Abstraction can make it harder to debug and understand code,


particularly for those unfamiliar with the abstraction layers and
implementation details
d) Polymorphism in Java

The word polymorphism means having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more than
one [Link] allows us to perform a single action in different ways.

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.

● Enables objects to be treated as a single type, making it easier to write


generic code that can handle objects of different types.

Disadvantages of Polymorphism in Java:

● Can make it more difficult to understand the behaviour of an object,


especially if the code is complex.

● May lead to performance issues, as polymorphic behaviour may require


additional computations at runtime.
OBJECT ORIENTED PROGRAMMING and
DESIGN with JAVA

ACTIVITY-07

Questions:

1. Study and report

a) java Arrays class their methods

b) java String class their methods


a) java Arrays class and their methods

The Arrays class in the [Link] package is a part of the Java Collection
Framework. This class provides static methods to dynamically create and
access Java arrays. It consists of only static methods and the methods of
Object class. The methods of this class can be used by the class name itself.

Methods in Java Array Class

The Arrays class of the [Link] package contains several static methods that
can be used to fill, sort, search, etc in arrays.

Methods Action Performed

Returns a fixed-size list backed by the specified


asList()
Arrays

Searches for the specified element in the array


binarySearch()
with the help of the Binary Search Algorithm

Searches a range of the specified array for the


binarySearch(array, fromIndex,
specified object using the Binary Search
toIndex, key, Comparator)
Algorithm

Compares two arrays passed as parameters


compare(array 1, array 2)
lexicographically.

Copies the specified array, truncating or padding


copyOf(originalArray,
with the default value (if necessary) so the copy
newLength)
has the specified length.

copyOfRange(originalArray, Copies the specified range of the specified array


fromIndex, endIndex) into new Arrays.

deepEquals(Object[] a1, Object[] Returns true if the two specified arrays are
a2) deeply equal to one another.
Returns a hash code based on the “deep
deepHashCode(Object[] a)
contents” of the specified Arrays.

Returns a string representation of the “deep


deepToString(Object[] a)
contents” of the specified Arrays.

equals(array1, array2) Checks if both the arrays are equal or not.

fill(originalArray, fillValue) Assigns this fill value to each index of this arrays.

Returns an integer hashCode of this array


hashCode(originalArray)
instance.

Finds and returns the index of the first


mismatch(array1, array2) unmatched element between the two specified
arrays.

parallelPrefix(originalArray,
Performs parallelPrefix for the given range of the
fromIndex, endIndex,
array with the specified functional operator.
functionalOperator)

parallelPrefix(originalArray, Performs parallelPrefix for complete array with


operator) the specified functional operator.

parallelSetAll(originalArray, Sets all the elements of this array in parallel,


functionalGenerator) using the provided generator function.

parallelSort(originalArray) Sorts the specified array using parallel sort.

setAll(originalArray, Sets all the elements of the specified array using


functionalGenerator) the generator function provided.
rt(originalArray) Sorts the complete array in ascending order.

sort(originalArray, fromIndex, Sorts the specified range of array in ascending


endIndex) order.

sort(T[] a, int fromIndex, int Sorts the specified range of the specified array of
toIndex, Comparator< super T> objects according to the order induced by the
c) specified comparator.

sort(T[] a, Comparator< super Sorts the specified array of objects according to


T> c) the order induced by the specified comparator.

Returns a Spliterator covering all of the specified


spliterator(originalArray)
Arrays.

Returns a Spliterator of the type of the array


spliterator(originalArray,
covering the specified range of the specified
fromIndex, endIndex)
arrays.

Returns a sequential stream with the specified


stream(originalArray)
array as its source.

It returns a string representation of the contents


of this array. The string representation consists of
a list of the array’s elements, enclosed in square
toString(originalArray) brackets (“[]”). Adjacent elements are separated
by the characters a comma followed by a space.
Elements are converted to strings as by
[Link]() function.
b) java String class and their methods

A String Array is an Array of a fixed number of String values. A String is a


sequence of characters. Generally, a string is an immutable object, which
means the value of the string can not be changed. The String Array works
similarly to other data types of Array.

Method Description

length Returns the number of elements in the array.

toString Returns a string representation of the array.

equals Compares two arrays for equality.

clone Returns a copy of the array.

copyOf Returns a copy of the array with a specified length.

copyOfRange Returns a copy of a range of elements in the array.

sort Sorts the elements in the array in ascending order.

Searches the array for a specified value using a binary search


binarySearch
algorithm.

fill Fills the array with a specified value.

Returns a List object containing the elements of the array.


asList

Common questions

Powered by AI

Conditional and iterative statements in Java, such as if-else structures and for or while loops, are essential for controlling program flow. They allow the program to make decisions and repeat actions based on specific conditions. For example, a nested if-else structure could be used in a grading system where different conditions determine different grades based on percentage marks. Similarly, nested loops can be used to perform repeated actions for each combination of indices in a matrix. The nested construction helps execute complex logic where multiple conditions or iterations are processed simultaneously .

Polymorphism enhances code readability and maintainability by allowing objects of different classes to be treated as objects of a common superclass. This simplifies code, reducing redundancy and enabling a more general and flexible code architecture. It allows for dynamic method dispatch, where calls to overridden methods are resolved at runtime, facilitating extensibility with minimal modifications. However, challenges include potentially decreased performance due to runtime overhead and the added complexity in understanding which method implementations will execute, especially in complex inheritance hierarchies .

Java's String class methods are powerful for handling text data, providing a range of functions like concatenation, searching, and regular expression matching, crucial for text processing. The immutability of Strings in Java ensures thread safety, enhancing security and reducing errors in concurrent environments. However, this immutability also means that operations producing new strings (e.g., concatenation) can lead to high memory usage and reduced performance when handling large volumes of text, as each modification creates a new string. Careful memory management or using StringBuilder/StringBuffer for intensive operations is often recommended to avoid inefficiencies .

Understanding 'write once, run anywhere' (WORA) is crucial for Java developers as it underscores Java's core strength of platform independence, allowing for the deployment of applications on any system running a JVM without modification. This principle reduces development costs and simplifies application distribution. Bytecode, generated after compiling Java source code, is interpreted by the JVM on any given system, ensuring that Java applications maintain their core logic and functionality regardless of platform differences. This universal adaptability is a key component of Java's widespread adoption .

Nested loops in Java involve placing one loop inside another, allowing for the processing of multi-dimensional data structures like matrices. A practical example is iterating over a 2D array (matrix) to calculate the sum of each row or column. For instance, using a nested for-loop, the outer loop can iterate over rows, while the inner loop iterates over columns within each row, enabling operations such as total computation, data transformation, or formatting tasks .

Encapsulation in Java offers several advantages, including data protection where sensitive data is kept hidden from outside interference through access specifiers like private, thus enhancing security. It promotes flexibility and cleaner code structure by allowing class internals to change without affecting outside code, only exposing getter and setter methods. It also supports code reusability as modular encapsulated units can be reused. However, disadvantages include increased code size, as encapsulation often requires additional boilerplate for getters and setters, and increased execution time due to these additional method calls .

Inheritance in Java significantly enhances code reuse by allowing new classes to inherit methods and attributes from existing 'parent' classes, reducing redundant code. This fosters flexibility, as changes made to the parent class propagate to child classes, aiding maintainability. It also facilitates polymorphism, where inherited methods can be overridden to suit subclass needs. However, drawbacks include a tight coupling between classes, which can restrict class independence and complicate code refactoring or debugging. Additionally, inheritance can reduce performance due to the overhead of function calls across class hierarchies .

Java arrays and the String class serve distinct purposes. Arrays, managed by the Arrays class in the java.util package, are fixed-size data structures that hold elements of the same type and facilitate operations such as sorting, searching, and filling. They are key in managing collections of data that need frequent manipulation or iteration. In contrast, the String class represents immutable sequences of characters, designed for operations like concatenation, comparison, substring extraction, and pattern matching, focusing more on textual data processing. Arrays offer higher efficiency for bulk operations, whereas String provides ease and flexibility for text manipulation .

Java bytecode serves as the machine code for the Java Virtual Machine (JVM), encapsulating the platform-independent instructions derived from Java source code. This code is compiled into bytecode format, which can then be executed on any platform with a JVM instance. The JVM interprets or compiles the bytecode into native machine instructions compatible with the host system, thus decoupling Java programs from any particular hardware architecture. The JVM's ability to interpret bytecode across different systems ensures that Java maintains its 'write once, run anywhere' (WORA) capability .

Abstraction in Java simplifies complex systems by allowing developers to focus on high-level functionality instead of intricate implementation details. By using abstract classes and interfaces, developers can define template methods while hiding the underlying operational complexity. This reduces cognitive load and encourages modular, easily maintainable code structures. However, pitfalls include the risk of over-abstraction, which can lead to increased complexity, hinder understanding, and create maintenance challenges if abstraction layers become too obscure or are not adequately documented .

You might also like