0% found this document useful (0 votes)
10 views93 pages

Oops Java Unit 1 Part 1

The document provides an overview of Object-Oriented Programming (OOP) principles and their implementation in Java, covering key concepts such as abstraction, encapsulation, inheritance, and polymorphism. It highlights the benefits of OOP, including modularity, reusability, and improved maintainability, as well as the historical context and features of Java. Additionally, it explains the relationships between objects, such as association, aggregation, and composition.

Uploaded by

ghousemohd625
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)
10 views93 pages

Oops Java Unit 1 Part 1

The document provides an overview of Object-Oriented Programming (OOP) principles and their implementation in Java, covering key concepts such as abstraction, encapsulation, inheritance, and polymorphism. It highlights the benefits of OOP, including modularity, reusability, and improved maintainability, as well as the historical context and features of Java. Additionally, it explains the relationships between objects, such as association, aggregation, and composition.

Uploaded by

ghousemohd625
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
You are on page 1/ 93

BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

Object-Oriented Programming: Principles, Benefits of Object-Oriented Programming.


Introduction to Java: Java buzzwords, bytecode. Java Programming Fundamentals: Applet and Application program using simple
java program, data types, variables, operators, expressions, control statements, type conversion and casting, arrays, command-line
arguments, concepts of classes, objects, constructors, methods, garbage collection, overloading methods and constructors, this
keyword.

OOPS Concepts:
● Introduction:
a. Object oriented programming(OOP) is core and integral for Java and it is important to understand its basic principles
before starting to write simple Java programs.
b. Program consists of two elements: code and data. Programs are conceptually organized around data or code.
c. Two programming paradigms govern how programs are constructed:
i. Process-oriented model:
1. Consists of code that is a series of linear steps.
2. It can be called “code acting on data”. Procedural languages such as C employ this model.
3. When programs grow longer and complex then problems are encountered by procedure oriented
models.
ii. Object oriented programming model:
1. OOP was introduced to manage increasing complexity
2. OOP Organizes a program around its data (that is objects) and a set of well defined interfaces to
access that data.
3. OOP is characterized by “data controlling access to code”.
4. By switching the control to “data” many benefits are achieved as mentioned below.
5. Object-oriented concepts form the heart of Java just as they form the basis for human understanding.
It is important to understand how these concepts translate into programs.
6. Object-oriented programming is a powerful and natural paradigm for creating programs that survive
the inevitable changes accompanying the life cycle of any major software project, including
conception, growth, and aging.
7. Once we have well-defined objects and clean, reliable interfaces to those objects, you can gracefully
decommission or replace parts of an older system without fear.
● Abstraction:
a. Essential element of OOP is “abstraction”.
b. Humans manage complexity through abstraction. Eg. To drive a car, one needs to know the steering, accelerator,
brakes, transmission(gears) shifting, driving basics and traffic rules. No need to know automobile engineering for
driving a car and still use the entire car as an object. (This is an abstraction: Making available only the required
information through proper interfaces and hiding the details and complexities).
c. Hierarchical abstractions of complex systems can also be applied to computer programs.
d. The data from a traditional process-oriented program can be transformed by abstraction into its component objects.
A sequence of process steps can become a collection of messages between these objects. Thus, each of these objects
describes its own unique behavior. Objects are treated as concrete entities that respond to messages telling them to
do something. This is the essence of object-oriented programming.
e. Abstraction forms the basis to transform a process oriented program into an object oriented program.
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

OOPS Principles
Three principles of OOPS(or Mechanisms to implement OOPS): Encapsulation, Inheritance, Polymorphism.
● Encapsulation:
a. Encapsulation is the mechanism that binds together code and the data it manipulates.
b. Both data and code are kept safe from outside interference and misuse by encapsulation.
c. Encapsulation is as a protective wrapper that prevents the code and data from being arbitrarily accessed by other
code defined outside the wrapper.
d. Access to the code and data inside the wrapper is tightly controlled through a well-defined interface.
e. In Java, the basis of encapsulation is the class.
f. Class:
i. A class defines the structure and behavior (data and code, that are called members of a class) that will be
shared by a set of objects.
ii. Data inside the class is referred to as member variables or instance variables.
iii. Code inside the class is referred to as member methods or methods. (Note: functions in C/C++ are called
as methods in Java).
iv. A class is a logical construct.
v. Object: Each object of a given class contains the structure and behavior defined by the class.
1. Object is an instance of a class.
2. An object has physical reality.
vi. Behavior and interface of a class is defined by the methods that operate on instance data.
1. Scope/Accessibility:
a. Each method or variable in a class may be marked private or public.
b. The public interface of a class represents everything that external users of the class need to
know, or may know.
c. The private methods and data can only be accessed by code that is a member of the class.
d. Therefore, any other code that is not a member of the class cannot access a private method
or variable.
e. The private members of a class may only be accessed by other parts of your program
through the public methods of class.
f. It can be ensured that no improper actions take place. Hence the public interface should be
carefully designed not to expose too much of the inner workings of a class.

● Inheritance:
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

a.Inheritance is the process by which one object acquires the properties of another object.
b.Supports the concept of hierarchical classification (knowledge managed by top-down approach).
c.Inheritance interacts with encapsulation as well.
d.If a given class (parent class) encapsulates some attributes then a new subclass (child class) inherits all of the
attributes of all of its ancestors/super/parent class plus any attributes that it adds as part of its specialization.
e. Inheritance is a key concept that lets object-oriented programs grow in complexity linearly rather than geometrically.
● Polymorphism:
a. Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface to be used for a general
class of actions. The specific action is determined by the exact nature of the situation.
b. The concept of polymorphism is expressed as “one interface, multiple methods”.
c. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is the
compiler’s job to select the specific action (that is, method) as it applies to each situation. Programmers do not need
to make this selection manually, and need only remember and utilize the general interface.
d. Two types of polymorphism:
i. Compile-time polymorphism (static or early binding): Achieved by method overloading which enables the
coexistence of many methods with the same name but distinct parameter lists within a class, enables Java
to accomplish compile-time polymorphism.
ii. Example for compile-time polymorphism: Consider that two methods with the same name “add” are written
within the Calculator class. The first method takes two integers as arguments and returns their sum as an
integer. The second method takes two doubles as arguments and returns their sum as a double. During
compilation, the Java compiler analyzes the argument types used in the method call and determines the
appropriate method to invoke.
iii. Run-time polymorphism (or Dynamic Method Dispatch): Is a process in which a call to an overridden
method is resolved at runtime rather than compile-time. Achieved by Inheritance and method overriding. In
this process, an overridden method is called through the reference variable of a superclass (through
upcasting: Reference variable of Parent class refers to the object of Child class). The determination of the
method to be called is based on the object being referred to by the reference variable.
iv. Example for run-time polymorphism: Consider a parent class Shape, Shape has a method called draw() that
has no specific implementation. Then consider two child classes that are Rectangle and Circle that are
inherited from class Shape and each child class has a method called draw(). So, when the parent class refers
to a child class (Rectangle) object and the draw() method is called with this reference then, the rectangle is
drawn. And when the parent class refers to a child class (Circle) object and the draw() method is called with
this reference then, the circle is drawn.
e. Benefits of Polymorphism: Improves readability, flexibility and code reusability.
Note: Association, Aggregation and Composition describe the relationship between objects.
● Association:
a. It defines the diversity between objects.
b. All objects have their separate lifecycle, and there is no owner.
c. For example, many students can associate with one teacher while one student can also associate with multiple
teachers.
● Aggregation:
a. All objects have their separate lifecycle.
b. However, there is ownership such that the child object can’t belong to another parent object.
c. For example, consider the class/objects department and teacher. Here, a single teacher can’t belong to multiple
departments. If we delete the department, the teacher object will never be destroyed.
● Composition:
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

a. A composition is a specialized form of Aggregation.


b. It is also called a "death" relationship.
c. Child objects do not have a separate lifecycle. When the parent object is deleted then all child objects will also be
deleted automatically.
d. Example of House and rooms: Any house can have several rooms. One room can’t become part of two different
houses. If the house object is deleted then the room object will also be deleted.
Benefits of OOPS:

1. Modularity
• OOP promotes the division of a software program into distinct modules or classes, each representing a
specific component or functionality.
• This modularity makes the code easier to manage, maintain, and understand.
2. Reusability
• OOP encourages code reuse through inheritance and composition.

• By creating new classes from existing ones, developers can leverage pre-existing code, reducing
redundancy and effort.
3. Encapsulation
• Encapsulation hides the internal implementation details of classes and exposes only the necessary
interfaces.
• This leads to better data protection and reduces the likelihood of unintended interference or misuse of
data.
4. Inheritance
• Inheritance allows new classes to inherit properties and methods from existing classes.

• This promotes code reuse, establishes a natural hierarchy, and enables polymorphism.
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

5. Polymorphism
• Polymorphism allows methods to behave differently based on the object invoking them, enabling
flexibility and scalability in code.
• It simplifies code maintenance and enhances the ability to extend the system with new functionalities
without modifying existing code.
6. Abstraction
• Abstraction simplifies complex systems by modelling classes appropriate to the problem domain.

• It allows focusing on the essential features of an object, reducing complexity and improving code
clarity.
7. Improved Maintainability
• OOP's modularity and encapsulation make updating, modifying, and debugging code easier.

• Changes in one part of the system have minimal impact on other parts, enhancing maintainability.
8. Ease of Troubleshooting
• OOP simplifies the process of debugging and troubleshooting by isolating functionality into separate
classes.
• Problems can be localized and resolved more efficiently.
9. Real-World Modelling
• OOP helps in the modelling of real-world entities and relationships in software.

• This makes the code more intuitive and aligned with human understanding of the problem domain.
10. Enhanced Collaboration
• OOP supports collaborative development by enabling multiple developers to work on different classes
or modules simultaneously.
• Well-defined interfaces and encapsulation improve teamwork and integration.
11. Extensibility
• OOP's principles make it easier to extend and scale software systems.

• New features and functionalities can be added with minimal disruption to existing code.
For both small project and large enterprise application, the structured approach provided by OOP ensures a
clearer, more organized, and sustainable development process.

History of Java:
1. James Gosling is the inventor of JAVA. Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed
Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first working version.
2. Initially the language was named as “Greentalk” as the team in which he was working as part of Sun-Microsystems
was called as “Green Team ''. Later they changed the name to “Oak” named after the tree which was right outside
his office. Due to proprietary issues with “Oak”, they changed it to “JAVA” in 1995, which is still used today even
after two decades.
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

3. Between the initial implementation of Oak in 1992 and the public announcement of Java in 1995, many people
contributed to the design and evolution of the language. Bill Joy, Arthur van Hoff, Jonathan Payne, Frank Yellin,
and Tim Lindholm were the key contributors.
4. Much of Java is inherited from two languages: C & C++. From C, Java derives its syntax and from C++ it took
object-oriented features.
5. JAVA was designed primarily with a motivation to develop a platform independent (Architecture – neutral)
language that could be used to create software for many consumer electronics like microwave ovens and remote
controls.
6. Later with the invention of the World Wide Web (internet) the language was adapted to implement web applications,
where the size and portability of the content matters.

Java Buzzwords or Features of Java:


1. Simple
2. Secure (No pointers, JVM checks for viruses)
3. Portable (Write once and carry it anywhere)
4. Object-oriented
5. Robust (More reliable as Memory management is better and mishandled exception conditions will be handled)
6. Multithreaded (multi-process synchronization, to construct smoothly running interactive systems)
7. Architecture-neutral (write once; run anywhere, any time, forever)
8. Interpreted (Java bytecode is interpreted and compiled into machine dependent code)
9. High performance (Is provided using Just-in-time compiler)
10. Distributed(It can access TCP/IP protocol and RMI-Remote method invocation)
11. Dynamic (Lots of Run-time type information)
1. Simple:
Java was designed to be easy for the professional programmer to learn and use effectively. As many of the JAVA
concepts are inherited from C & C++. Having the prior knowledge of these two languages will make our learning job
easier. One will not find Java hard to learn. Moving to Java will require very little effort.
2. Secure:
When we download a “normal” program, we are taking a risk, because the code we are downloading might contain a
virus, Trojan horse, or other harmful code. Malicious code can cause damage, because it can gain unauthorized access to
system resources. For example, a virus program might gather private information, such as credit card numbers, bank
account balances, and passwords, by searching the contents of any computer local file system. Java achieved this
protection by limiting an applet to the Java execution environment and not allowing it access to other parts of the
computer.
3. Portable:
Portability is a major aspect of the Internet because there are many different types of computers and operating systems
connected to it. A Java program can run on any computer connected to the Internet, there needed to be some way to enable
that program to execute on different systems. The Java Virtual Machine is the solution for providing portability.
4. Object Oriented:
Java manages to maintain a balance between the “everything is an object” paradigm and the non-object model. The object
model in Java is simple and easy to extend, while primitive types, such as integers, are kept as high-performance non-objects.
5. Robust:
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

The multi-platform environment of the Web increases the demands on a robust program, because the program must execute
reliably in a variety of systems. Thus, the ability to create robust programs was given a high priority. Java checks the code
at compile time and also checks it at run time. Many hard-to-track-down bugs are simply impossible to create in Java.
Knowing that what you have written will behave in a predictable way under diverse conditions is a key feature of Java.
6. Multi-Threaded:
Java was designed to meet the real-world requirement of creating interactive, networked programs. To accomplish this, Java
supports multithreaded programming, which allows us to write programs that do many things simultaneously.
7. Architecture-Neutral:
Programmers face a problem that if they write a program today, there is no guarantee that it will run tomorrow—even on
the same machine. Operating system upgrades, processor upgrades, and changes in core system resources can make a
program malfunction. To solve this issue, the Java designers made several hard decisions in the Java language and the Java
Virtual Machine. Their goal was “write once; run anywhere, anytime, forever.” To a great extent, this goal was
accomplished.
8 & 9. Interpreted and High Performance:
Java enables the creation of cross-platform programs by compiling into an intermediate representation called Java bytecode.
This code can be executed on any system that implements the Java Virtual Machine. Many previous attempts were made to
get cross-platform solutions, but resulted in degradation of performance. Java bytecode was designed very carefully so that
it can easily translate directly into native machine code with very high performance by using a just-in-time compiler.
10. Distributed:
Java is designed for the distributed environment of the Internet. It supports TCP/IP protocols for accessing a resource using
a URL and Remote Method Invocation (RMI) to invoke methods across a network.
11. Dynamic
Java programs carry substantial amounts of run-time information with them, which is used to verify and resolve accesses to
objects at run time. This enables a possibility to dynamically link code in a safe manner.
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

Data types:
Primitive data types in Java:
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean. The primitive types are also
commonly referred to as simple types.
Integers: This group includes byte, short, int, and long, which are for whole-valued signed numbers.
Floating-point numbers: This group includes float and double, which represent numbers with fractional precision.
Characters: This group includes char, which represents symbols in a character set, like letters and numbers.
Boolean: This group includes Boolean, which is a special type for representing true/false values.
Integers:
Java defines four integer types: byte, short, int, and long. All of these are signed, positive and negative values.
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

Floating-point types: Floating-point numbers, also known as real numbers, are used when evaluating expressions that
require fractional precision.

● Float is single precision i.e. it will show 6 to 7 decimal digits.


● Double is double precision i.e. it will show 15 to 16 decimal digits.

Character Type:
● In Java, the data type used to store characters is char.
● ‘char’ in Java is not the same as char in C or C++. In C/C++, char is 8 bits wide. This is not the case in Java. Instead,
Java uses Unicode to represent characters. in Java char is a 16-bit type.
● The range of a char is 0 to 65,536. There are no negative chars.

Boolean Type:
● Java has a primitive type, called boolean, for logical values.
● It can have only one of two possible values, true or false.
● This is the type returned by all relational operators, as in the case of a < b. boolean is also the type required by the
conditional expressions that govern the control statements such as if and for.

Variables:
● The variable is the basic unit of storage in a Java program.
● A variable is defined by the combination of an identifier, a type, and an optional initializer.
● In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown
here:
type identifier [ = value ][, identifier [= value ] …];
Examples:
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing d and f.
byte z = 22; // initializes z.
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

double pi = 3.14159; // declares an approximation of pi.


char x = 'x'; // the variable x has the value 'x'.
Dynamic Initialization:
class DynInit {
public static void main(String args[])
{
int a = 3, b = 4;
// c is dynamically initialized
int c = (a *a) + ( b*b);
System.out.println("Hypotenuse is " + c);
}
}

Literals:
Integer literals
Integers are probably the most commonly used type in the typical program. Any whole number value is an integer literal.
Examples are 1, 2, 3, and 42. These are all decimal values, meaning they are describing a base 10 number.
Floating-Point Literals
Floating-point numbers represent decimal values with a fractional component. Examples include 6.022E23, 314159E–05
and 2e+100.
Boolean Literals Boolean literals are simple. There are only two logical values that a Boolean value can have, true and
false. The values of true and false do not convert into any numerical representation.
The true literal in Java does not equal 1, nor does the false literal equal 0.

Scope and Lifetime of variables:


● Java allows variables to be declared within any block. A block is begun with an opening curly brace and ended by
a closing curly brace.
● A block defines a scope. Thus, each time you start a new block, you are creating a new scope.
● A scope determines what objects are visible to other parts of your program. It also determines the lifetime of those
objects.
● In Java, the two major scopes are those defined by a class and those defined by a method.
● The scope defined by a method begins with its opening curly brace. If that method has parameters, they too are
included within the method’s scope.
● Variables declared inside a scope are not visible/accessible to code that is defined outside that scope.
● When we declare a variable within a scope, we are localizing that variable and protecting it from unauthorized access
and/or modification.
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

● Scopes can be nested. For example, each time we create a block of code, we are creating a new, nested scope. When
this occurs, the outer scope encloses the inner scope. This means that objects declared in the outer scope will be
visible to code within the inner scope. The reverse is not true. Objects declared within the inner scope will not be
visible outside it.
Example:
// Demonstrate block scope.
class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y are both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}
Explanation: As the comments indicate, the variable x is declared at the start of main( )’s scope and is accessible to all
subsequent code within main( ). Within the if block, y is declared. Since a block defines a scope, y is only visible to other
code within its block. This is why outside of its block, the line y = 100; is commented out. If you remove the leading comment
symbol, a compile-time error will occur, because y is not visible outside of its block. Within the if block, x can be used
because code within a block (that is, a nested scope) has access to variables declared by an enclosing scope.
Within a block, variables can be declared at any point, but are valid only after they are declared. For example, this fragment
is invalid because count cannot be used prior to its declaration:
count = 100; // oops! cannot use count before it is declared! // This fragment is wrong!
int count;

Lifetime of a variable:
Here is another important point to remember: variables are created when their scope is entered, and destroyed when their
scope is left. This means that a variable will not hold its value once it has gone out of scope. Therefore, variables declared
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

within a method will not hold their values between calls to that method. Also, a variable declared within a block will lose
its value when the block is left. Thus, the lifetime of a variable is confined to its scope. If a variable declaration includes an
initializer, then that variable will be reinitialized each time the block in which it is declared is entered. For example, consider
the next program.
// Demonstrate lifetime of a variable.
class LifeTime {
public static void main(String args[]) {
int x;
for(x = 0; x < 3; x++) {
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}
The output generated by this program is shown here:
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100

y is reinitialized to –1 each time the inner for loop is entered. Even though it
is subsequently assigned the value 100, this value is lost.

When blocks can be nested, you cannot declare a variable to have the same name as one in an outer scope. For example, the
following program is illegal:
// This program will not compile
class ScopeErr {
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

public static void main(String args[]) {


int bar = 1;
{ // creates a new scope
int bar = 2; // Compile-time error – bar already defined!
}
}
}

Operators:
Arithmetic: The operands of the arithmetic operators must be of a numeric type. You cannot use them on boolean types,
but you can use them on char types, since the char type in Java is, essentially, a subset of int.

The following simple example program demonstrates the arithmetic operators. It also
illustrates the difference between floating-point division and integer division.
// Demonstrate the basic arithmetic operators.
class BasicMath {
public static void main(String args[]) {
// arithmetic using integers
System.out.println("Integer Arithmetic");
int a = 1 + 1;
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
// arithmetic using doubles
System.out.println("\nFloating Point Arithmetic");
double da = 1 + 1;
double db = da * 3;
double dc = db / 4;
double dd = dc - a;
double de = -dd;
System.out.println("da = " + da);
System.out.println("db = " + db);
System.out.println("dc = " + dc);
System.out.println("dd = " + dd);
System.out.println("de = " + de);
}
}

OUTPUT:
Integer Arithmetic
a=2
b=6
c=1
d = -1
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

e=1
Floating Point Arithmetic
da = 2.0
db = 6.0
dc = 1.5
dd = -0.5
de = 0.5
The Modulus Operator
The modulus operator, %, returns the remainder of a division operation. It can be applied to
floating-point types as well as integer types. The following example program demonstrates
the %:
// Demonstrate the % operator.
class Modulus {
public static void main(String args[]) {
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}
}
When you run this program, you will get the following output:
x mod 10 = 2
y mod 10 = 2.25
Arithmetic Compound Assignment Operators:
Java provides special operators that can be used to combine an arithmetic operation with
an assignment. As you probably know, statements like the following are quite common in
programming:
a = a + 4;
In Java, you can rewrite this statement as shown here:
a += 4;
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

This version uses the += compound assignment operator. Both statements perform the same
action: they increase the value of a by 4.
Here is another example,
a = a % 2;
which can be expressed as
a %= 2;
In this case, the %= obtains the remainder of a/2 and puts that result back into a.
There are compound assignment operators for all of the arithmetic, binary operators.
Thus, any statement of the form
var = var op expression;
can be rewritten as
var op= expression;
The compound assignment operators provide two benefits. First, they save you a bit of
typing, because they are “shorthand” for their equivalent long forms. Second, they are
implemented more efficiently by the Java run-time system than are their equivalent long
forms. For these reasons, you will often see the compound assignment operators used in professionally written Java
programs.
Here is a sample program that shows several op= assignments in action:
// Demonstrate several assignment operators.
class OpEquals {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c = 3;
a += 5;
b *= 4;
c += a * b;
c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

System.out.println("c = " + c);


}
}
The output of this program is shown here:
a=6
b=8
c=3
Increment and Decrement Operators
The increment operator increases its operand by one. The decrement operator decreases
its operand by one. For example, this statement:
x = x + 1;
can be rewritten like this by use of the increment operator:
x++; OR ++x; // no difference post increment and pre increment
Similarly, this statement:
x = x - 1;
is equivalent to
x--; OR --x; / no difference post-decrement and pre-decrement
For example:
x = 42;
y = ++x;
In this case, y is set to 43 as you would expect, because the increment occurs before x is assigned to y.

Thus, the line y = ++x; is the equivalent of these two statements:


x = x + 1;
y = x;
However, when written like this,
x = 42;
y = x++;
the value of x is obtained before the increment operator is executed, so the value of y is 42.
Of course, in both cases x is set to 43.
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

Here, the line y = x++; is the equivalent of these two statements:


y = x;
x = x + 1;
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. They are summarized in the following table:

The Bitwise Logical Operators


The bitwise logical operators are & (bitwise AND) , | ( bitwise OR) , ^ ( bitwise XOR), and ~( bitwise NOT). The following
table shows the outcome of each operation. In the discussion that follows, keep in mind that the bitwise operators are applied
to each individual bit within each operand.

class TestBO { Output: (NOT)


BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

public static void main(String args []) -43


{
int a = 42; Explanation:
System.out.println(~a);

class TestBO { Output: ( AND)

public static void main(String args []) 10


{
int a = 42, b = 15; Explanation:
System.out.println(a&b);

class TestBO { Output: (OR)


47
public static void main(String args [])
{ Explanation:
int a = 42, b = 15;
System.out.println(a|b);

class TestBO { Output: (XOR)


37
public static void main(String args [])
{ Explanation:
int a = 42, b = 15;
System.out.println(a^b);

class TestBO { Output: 256


BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

The Left Shift


public static void main(String args []) The left shift operator, <<, shifts all of the bits in a
{ value to the left a specified number of times.
byte a = 64; It has this general form:
System.out.println(a<<2); value << num
Here, num specifies the number of positions to left-
} shift the value in value. That is, the <<
moves all of the bits in the specified value to the left
} by the number of bit positions specified
by num.
Since a is promoted to int for the purposes of
evaluation, left-shifting the value 64
(0100 0000) twice results in i containing the value 256
(1 0000 0000).

class TestBO { Output: 8

public static void main(String args []) The Right Shift


{ Explanation:
int a = 35;
System.out.println(a>>2);

class TestBO { Output: 256

public static void main(String args []) The Unsigned Right Shift / Shift Zero Fill
{ Explanation:
int a = -1;
System.out.println(a>>>24);

class OpBitEquals { Bitwise Operator Compound Assignments


public static void main(String args[]) { The output of this program is shown here:
int a = 1; a=3
int b = 2; b=1
int c = 3; c=6
a |= 4;
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

b >>= 1
c <<= 1;
a ^= c;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}

Relational Operators:
The relational operators determine the relationship that one operand has to the other. Specifically, they determine equality
and ordering. 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. Only numeric types can be compared using the
ordering operators.
The relational operators are shown here:

Examples with explanation:

int a = 4;
if(done == 0) ... // This is Java-style.
int b = 1; if (done! = 0) …
boolean c = a < b;
In Java, true and false are non-numeric values that
In this case, the result of a<b (which is false) is do not relate to zero or nonzero. Therefore, to test for
stored in c. zero or nonzero, you must explicitly
employ one or more of the relational operators.

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.
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

The logical Boolean operators, &, |, and ^, operate on boolean values in the same way that they operate on the bits of an
integer. The logical ! operator inverts the Boolean state: !true == false and !false == true. The following table shows the
effect of each logical operation:

class BoolLogic { Output:


public static void main(String args[]) {
boolean a = true; a = true
boolean b = false; b = false
boolean c = a | b; a|b = true
boolean d = a & b; a&b = false
boolean e = a ^ b; a^b = true
boolean f = (!a & b) | (a & !b); a&b|a&!b = true
boolean g = !a; !a = false
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " + d);
System.out.println(" a^b = " + e);
System.out.println("!a&b|a&!b = " + f);
System.out.println(" !a = " + g);
}}

Short-circuit logical operators (&& , ||):


BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

A logical expression results in true when A is true, no matter what B is. Similarly, the AND operator results in false when
A is false, no matter what B is. If you use the || and && forms, rather than the | and & forms of these operators, Java will
not bother to evaluate the right-hand operand when the outcome of the expression can be determined by the left operand
alone. This is very useful when the right-hand operand depends on the value of the left one in order to function properly.

Short-circuit logical operators (&&, ||) - Example

Taking advantage of short-circuit logical evaluation to be sure that a division operation will be valid
before evaluating it:
if (denom != 0 && num / denom > 10)

if denom is equal to 0, then num/denom will never be evaluated thus avoiding runtime error/exception.
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

The Assignment Operator int a = 10; // a is initialized to 10


The assignment operator is the single equal Here, the type of var must be compatible with
sign, =. the type of expression.
It has this general form: var = expression; The assignment operator to create a chain of
assignments
int x, y, z;
x = y = z = 100; // set x, y, and z to 100
This fragment sets the variables x, y, and z to
100 using a single statement. This works
because the = is an operator that yields the
value of the right-hand expression. Thus, the
value of z = 100 is 100, which is then assigned
to y, which in turn is assigned to x. Using a
“chain of assignment” is an easy way to set a
group of variables to a common value.

The ? Operator Here is an example of the way that the ? is


employed:
Java includes a special ternary (three-way)
operator that can replace certain types of if- ratio = denom == 0 ? 0 : num / denom;
then-else statements. The ? has this general
If denom equals zero, then the expression
form:
between the question mark and the colon is
expression1 ? expression2 : expression3 evaluated and used as the value of the entire ?
expression. If denom does not equal zero, then
Here, expression1 can be any expression that
the expression after the colon is evaluated and
evaluates to a boolean value. If expression1 is
used for the value of the entire ? expression.
true, then expression2 is evaluated; otherwise,
The result produced by the ? operator is then
expression3 is evaluated. The result of the ?
assigned to ratio.
operation is that of the expression evaluated.
Both expression2 and expression3 are required
to return the same type, which can’t be void.

Operators’ precedence:
The order of precedence for Java operators, from highest to lowest.
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

Parentheses raise the precedence of the operations that are inside them. This is often necessary to obtain the desired result
. For example, consider the following expression:
a >> b + 3
This expression first adds 3 to b and then shifts a right by that result. That is, this expression can be rewritten using redundant
parentheses like this: a >> (b + 3)
In Order to first shift a right by b positions and then add 3 to that result, parenthesis is needed like this:
(a >> b) + 3
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

Statements:
a. A Java statement is an executable instruction that tells the compiler what to perform.
b. It forms a complete command to be executed and can include one or more expressions.
c. Types of Statements in Java:
i. Expression Statements
1. Expressions that produce a value: For example 1, (6+9), (9%2), (pi*radius) + 2. Note that the
expression enclosed in the parentheses will be evaluated first, after that rest of the expression.
Boolean expression: example 2: if (a%2 == 0), a%2 == 0, first the numeric value of a%2 is
evaluated and compared with 0, and produces a boolean value (true or false) based on which if
statement (executes) or not respectively.
2. Expressions that assign a value: For example, number = 90, pi = 3.14.
3. Expression that neither produces any result nor assigns a value: These expressions modify the value
of a variable or state (memory) of a program. For example, incrementing or decrementing a value
by using increment or decrement operator respectively, method invocation, etc like count++, int
sum = a + b; The expression changes only the value of the variable sum. The value of variables a
and b do not change, so it is also a side effect.
4. Expressions follow operator precedence.
ii. Declaration Statements
1. In declaration statements, we declare variables and constants by specifying their data type and name.
A variable holds a value that is going to be used in the Java program.
2. For example:
i. int quantity;
ii. boolean flag;
iii. String message;
3. Also, variables can be initialized with a value. For example:
i. int quantity = 20;
ii. boolean flag = false;
iii. String message = "Hello";
4. Multiple variables can be declared in a single declaration statement provided that they are of the
same data type and must be separated by a comma (,).
i. int quantity, batch_number, lot_number;
ii. boolean flag = false, isContains = true;
iii. String message = "Hello", question = “how are you”;
iii. Control Statements
1. A programming language uses control statements to cause the flow of execution to advance and
branch based on changes to the state of a program.
2. Java’s program control statements can be put into the following categories:
i. Conditional or Selection statements ( if, nested ifs, if else, if else if, switch)
ii. Loop or Iteration statements (for, while, do-while, for-each)
iii. Flow control or Jump statements (return, break, continue)
i. Conditional or Selection statements: These statements control the flow of program’s execution based
upon conditions known only during run time.
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

Control Statements:
if statement
Java’s conditional branch statement. It can be used to route program execution through two different paths.
General form of the if statement:
if (condition) statement1;
else statement2;

Each statement may be a single statement or a compound statement enclosed in curly braces (that is, a block).
The condition is any expression that returns a boolean value. The else clause is optional.
The if works like this: If the condition is true, then statement1 is executed. Otherwise, statement2 (if it exists)
is executed. In no case will both statements be executed.
For example, consider the following:
int a, b;
a = 1;
b = 2;
if(a < b) a = 0;
else b = 0;

Only one statement can appear directly after the if or else. To include more statements (compound statement) under
if or else, block {} must be created, as in the below code fragment:
boolean dataAvailable:
int x = 1, y = 4;
dataAvailable = true;
if(dataAvailable) {
x++;
y- -;
}
else {
x = x + y;
y = 0;
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

Nested ifs
A nested if is an if statement that is the target of another if or else. Nested ifs are very common in programming.
When you nest ifs, the main thing to remember is that an else statement always refers to the nearest if statement that
is within the same block as the else and that is not already associated with an else. Here is an example:
if(i == 10) {
if(j < 20) a = b; /this if is not associated with any else
if(k > 100) c = d;
else a = c; // this else refers to if (k > 100)
}
else a = d; // this final else refers to if(i == 10)

The if-else-if Ladder


A common programming construct that is based upon a sequence of nested ifs is the
if-else-if ladder
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;
The if statements are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is executed, and the rest of the
ladder is bypassed. If none of the conditions is true, then the final else statement will be
executed.
The final else acts as a default condition; that is, if all other conditional tests fail, then the
last else statement is performed. If there is no final else and all other conditions are false,
then no action will take place.
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

Program that uses an if-else-if ladder to determine which season a particular month is in.
// Demonstrate if-else-if statements.
class IfElse {
public static void main(String args[]) {
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
Here is the output produced by the program:
April is in the Spring.
No matter what value you give for month, one and only one assignment statement within
the ladder will be executed.

switch statement
The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch execution to
different parts of your code based on the value of an expression. As such, it often provides a better alternative than a
large series of if-else-if statements. Here is the general form of a switch statement:

switch (expression) {
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
case valueN:
// statement sequence
break;
default: // default is optional
}
expression: The expression must be of type byte, short, int, or char; each of the values specified in the case
statements must be of a type compatible with the expression. (An enumeration value can also be used to control a
switch statement)
case value: Each case value must be a unique literal (that is, it must be a constant, not a variable). Duplicate case
values are not allowed.
The switch statement works like this: The value of the expression is compared with each of the literal values in the
case statements. If a match is found, the code sequence following that case statement is executed. If none of the
constants matches the value of the expression, then the default statement is executed. However, the default
statement is optional. If no case matches and no default is present, then no further action is taken.
The break statement is used inside the switch to terminate a statement sequence. When a break statement is
encountered, execution branches to the first line of code that follows the entire switch statement. This has the effect
of “jumping out” of the switch.
Here is a simple example that uses a switch statement:
// A simple example of the switch.
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
}
Output:
i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3.
As you can see, each time through the loop, the statements associated with the case constant that matches i are
executed. All others are bypassed. After i is greater than 3, no case statements match, so the default statement is
executed.
The break statement is optional. If you omit the break, execution will continue on into the next case. It is sometimes
desirable to have multiple cases without break statements between them. For example, consider the following
program:
// In a switch, break statements are optional.
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

class MissingBreak {
public static void main(String args[]) {
for(int i=0; i<12; i++)
switch(i) {
case 0:
case 1:
case 2:
case 3:
case 4:
System.out.println("i is less than 5");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
System.out.println("i is less than 10");
break;
default:
System.out.println("i is 10 or more");
}
}
}
This program generates the following output:
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 5
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is 10 or more
i is 10 or more
As you can see, execution falls through each case until a break statement (or the end of the switch) is reached.

Omitting the break statement has many practical applications in real programs. To sample its more realistic usage,
consider the following rewrite of the season example shown earlier. This version uses a switch to provide a more
efficient implementation.
// An improved version of the season program.
class Switch {
public static void main(String args[]) {
int month = 4;
String season;
switch (month) {
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:
season = "Spring";
break;
case 6:
case 7:
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

case 8:
season = "Summer";
break;
case 9:
case 10:
case 11:
season = "Autumn";
break;
default:
season = "Bogus Month";
}
System.out.println("April is in the " + season + ".");
}
}

Nested switch Statements:


switch can be used as part of the statement sequence of an outer switch. This is called a
nested switch. Since a switch statement defines its own block, no conflicts arise between the
case constants in the inner switch and those in the outer switch.
For example, the following fragment is perfectly valid:
switch(count) {
case 1:
switch(target) { // nested switch
case 0:
System.out.println("target is zero");
break;
case 1: // no conflicts with outer switch
System.out.println("target is one");
break;
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

}
break; // break for outer case 1
case 2: // refers to outer case 1
Here, the case 1: statement in the inner switch does not conflict with the case 1: statement in the outer switch. The
count variable is only compared with the list of cases at the outer level. If count is 1, then target is compared with
the inner list cases.

Comparison of if..else..if and switch


Java Compiler when it compiles a switch statement it will inspect each of the case constants to create a “jump
table” that is used for selecting the path of execution depending on the value of the expression.
To select among a large group of values, a switch statement will run much faster than the equivalent logic coded
using a sequence of if-elses. The compiler can do this because it knows that the case constants are all the same type
and simply must be compared for equality with the switch expression. The compiler has no such knowledge of a
long list of if expressions.

Loop or Iteration Statements


Java’s iteration statements are for, while, and do-while. These statements create what we commonly call loops. A
loop repeatedly executes the same set of instructions until a termination condition is met.
while
while loop repeats a statement or block while its controlling expression is true. Here is its general form:
while(condition) {
// body of loop
}
The condition can be any Boolean expression. The body of the loop will be executed as long as the conditional
expression is true. When the condition becomes false, control passes to the next line of code immediately following
the loop. The curly braces are unnecessary if only a single statement is being repeated.
while loop that counts down from 10, printing exactly ten lines of “tick”:
// Demonstrate the while loop.
class While {
public static void main(String args[]) {
int n = 10;
while(n > 0) {
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

System.out.println("tick " + n);


n--;
}
}
}
Output:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
Since the while loop evaluates its conditional expression at the top of the loop, the body of the loop will not execute
even once if the condition is false to begin with. For example, in the following fragment, the call to println( ) is
never executed:

int a = 10, b = 20;


while(a > b)
System.out.println("This will not be displayed");
The body of the while (or any other of Java’s loops) can be empty. This is because a null
statement (one that consists only of a semicolon) is syntactically valid in Java. For example,
consider the following program:
// The target of a loop can be empty.
class NoBody {
public static void main(String args[]) {
int i, j;
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

i = 100;
j = 200;
// find midpoint between i and j
while(++i < --j) ; // no body in this loop
System.out.println("Midpoint is " + i);
}
}
Output:
Midpoint is 150
The value of i increments and value of j decrements and is compared, till i increases to150 and j reduces to 150,
when i = 150 and j =150, the while condition is false and the loop exits and goes to the first line after the while
loop.

do-while
if the conditional expression controlling a while loop is initially false, then the body of the loop will not be executed
at all. However, sometimes it is desirable to execute the body of a loop at least once, even if the conditional
expression is false to begin with. In other words, there are times when you would like to test the termination
expression at the end of the loop rather than at the beginning. Java provides a loop that does just that: the do-while.
The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the
loop. Its general form is
do {
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression.
If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of Java’s loops, condition
must be a Boolean expression. Here is a reworked version of the “tick” program that demonstrates the do-while
loop.
It generates the same output as before.
// Demonstrate the do-while loop.
class DoWhile {
public static void main(String args[]) {
int n = 10;
do {
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

System.out.println("tick " + n);


n--;
} while(n > 0);
}
}
The loop in the preceding program, while technically correct, can be written more
efficiently as follows:
do {
System.out.println("tick " + n);
} while(--n > 0);

The do-while loop is especially useful when you process a menu selection, because you will usually want the body
of a menu loop to execute at least once. Consider the following program, which implements a very simple help
system for Java’s selection and iteration statements:
// Using a do-while to process a menu selection
import java.util.*;
class Menu {
public static void main(String args[])
{
char choice;
do {
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. while");
System.out.println(" 4. do-while");
System.out.println(" 5. for\n");
System.out.println("Choose one:");
Scanner sc = new Scanner(System.in);
choice = sc.next().charAt(0);
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

} while( choice < '1' || choice > '5');


System.out.println("\n");
switch(choice) {
case '1':
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case '3':
System.out.println("The while:\n");
System.out.println("while(condition) statement;");
break;
case '4':
System.out.println("do {");
System.out.println(" statement;");
System.out.println("} while (condition);");
break;
case '5':
System.out.println("The for:\n");
System.out.print("for(init; condition; iteration)");
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

System.out.println(" statement;");
break;
}
}
}
Here is a sample run produced by this program:
Help on:
1. if
2. switch
3. while
4. do-while
5. for
Choose one:
4
The do-while:
do {
statement;
} while (condition);
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

Beginning with JDK 5, there are two forms of the for loop.
The first is the traditional form that has been in use since the original version of Java.
The second is the new “for-each” form.
The traditional for statement:
for(initialization; condition; iteration) {
// body
}
If only one statement is being repeated, there is no need for the curly braces. The for loop operates as follows.
When the loop first starts, the initialization portion of the loop is executed. Generally, this is an expression that sets
the value of the loop control variable, which acts as a counter that controls the loop. It is important to understand
that the initialization expression is only executed once. Next, the condition is evaluated. This must be a Boolean
expression. It usually tests the loop control variable against a target value. If this expression is true, then the body of
the loop is executed. If it is false, the loop terminates.
Next, the iteration portion of the loop is executed. This is usually an expression that increments or decrements the
loop control variable. The loop then iterates, first evaluating the conditional expression, then executing the body of
the loop, and then executing the iteration expression with each pass. This process repeats until the controlling
expression is false.
Here is a version of the “tick” program that uses a for loop:
// Demonstrate the for loop.
class ForTick {
public static void main(String args[]) {
int n;
for(n=10; n>0; n--)
System.out.println("tick " + n);
}
}
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

Declaring loop control variable inside the for loop: The variable n ceases to exist outside the loop:
class ForTick {
public static void main(String args[]) {
// here, n is declared inside of the for loop
for(int n=10; n>0; n--)
System.out.println("tick " + n);
}
}

for loop controlled by interaction of two variables: first way


class Sample {
public static void main(String args[]) {
int a, b;
b = 4;
for(a=1; a<b; a++) {
System.out.println("a = " + a);
System.out.println("b = " + b);
b--;
}
}
}
for loop controlled by interaction of two variables: second way using comma ( is called separator)
public static void main(String args[]) {
int a, b;
for(a=1, b=4; a<b; a++, b--) {
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

}
In this example, the initialization portion sets the values of both a and b. The two comma separated statements in
the iteration portion are executed each time the loop repeats. The program generates the following output:
a=1
b=4
a=2
b=3
The for loop controlling condition need not test only the loop variables, it can be any boolean expression or boolean
value outside the for loop.
boolean done = false;
int k = 10;
if (k==10) k +=91;
for(int i=1; !done; i++) {
if(k >100){ done = true;}
}
Either the initialization or the iteration expression or both may be absent in for loop, as in this next
program:
class ForVar {
public static void main(String args[]) {
int i;
boolean done = false;
i = 0;
for( ; !done; ) {
System.out.println("i is " + i);
if(i == 10) done = true;
i++;
}
}
}
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

if the initial condition is set through a complex expression elsewhere in the program or if the loop control variable
changes in a non sequential manner determined by actions that occur within the body of the loop, it may be
appropriate to leave these parts of the for empty.
Can create an infinite loop (a loop that never terminates) if you leave all three parts of the for empty.
For example:
for( ; ; ) {
}
This loop will run forever because there is no condition under which it will terminate.
The general form of the for-each version of the for is shown here:
Beginning with JDK 5, a second form of for was defined that implements a “for-each” style loop. A foreach style
loop is designed to cycle through a collection of objects, such as an array, in strictly sequential fashion, from start to
finish.
for(type itr-var : collection) statement-block
Here, type specifies the type and itr-var specifies the name of an iteration variable that will receive the elements
from a collection, one at a time, from beginning to end. The collection being cycled through is specified by
collection. In C#, its syntax is foreach, but in java for-each capability is applied by for loop without changing the
name.
The following fragment uses a traditional for loop to compute
the sum of the values in an array:
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int i=0; i < 10; i++) sum += nums[i];
for each style:
It eliminates the need to establish a loop counter, specify a starting and ending value, and manually index the array.
Instead, it automatically cycles through the entire array, obtaining one element at a time, in sequence, from
beginning to end. For example, here is the preceding fragment rewritten using a for-each version of the for:
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x: nums) sum += x;
With each pass through the loop, x is automatically given a value equal to the next element in nums. Thus, on the
first iteration, x contains 1; on the second iteration, x contains 2; and so on.
Not only is the syntax streamlined, but it also prevents boundary errors.
class ForEach {
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

public static void main(String args[]) {


int sum = 0;
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// use for to display and sum the values
for(int x : nums) {
System.out.println("Value is: " + x);
sum += x;
}
System.out.println("Summation is: " + sum);
}
}
Output:
1
2
3
4
5
6
7
8
9
10
Summation of first 5 elements is 55
break statement in for loop:
class ForEach2 {
public static void main(String args[]) {
int sum = 0;
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// use for to display and sum the values
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

for(int x : nums) {
System.out.println("Value is: " + x);
sum += x;
if(x == 5) break; // stop or terminate the loop when 5 is obtained
}
System.out.println("Summation of first 5 elements: " + sum); } }
Output:
1
2
3
4
5
Summation of first 5 elements is 15
foreach style for loop is an excellent choice for searching an unsorted array, computing an average, finding the
minimum or maximum of a set, looking for duplicates, and so on.
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

Nested for loops:


// Loops may be nested.
class Nested {
public static void main(String args[]) {
int i, j;
for(i=0; i<10; i++) {
for(j=i; j<10; j++)
System.out.print(".");
System.out.println();
}
}
}
The output produced by this program is shown here:

..........
.........
........
.......
......
.....
....
...
..

// Use for-each style for on a two-dimensional array.


class ForEach3 {
public static void main(String args[]) {
int sum = 0;
int nums[][] = new int[3][5];
// give nums some values
for(int i = 0; i < 3; i++)for(int j=0; j < 5; j++)
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

nums[i][j] = (i+1)*(j+1);
// use for-each for to display and sum the values
for(int x[] : nums) {
for(int y : x) {
System.out.println("Value is: " + y);
sum += y;
}
}
System.out.println("Summation: " + sum);
}
}
The output from this program is shown here:
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 2
Value is: 4
Value is: 6
Value is: 8
Value is: 10
Value is: 3
Value is: 6
Value is: 9
Value is: 12
Value is: 15
Summation: 90
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

Jump Statements

Java supports three jump statements: break, continue, and return. These statements transfer
control to another part of your program.

Using break
In Java, the break statement has three uses.
1. To terminate a statement sequence in a switch statement.
2. To exit a loop.
3. Can be used as a “civilized” form of goto.

Using break to Exit a Loop

By using break, you can force immediate termination of a loop, bypassing the conditional expression and any
remaining code in the body of the loop. When a break statement is encountered inside a loop, the loop is terminated
and program control resumes at the next statement following the loop. Here is a simple example:

// Using break to exit a loop. Output:

class BreakLoop { i: 0
public static void main(String args[]) { i: 1
for(int i=0; i<100; i++) { i: 2
if(i == 10) break; // terminate loop if i is 10 i: 3
System.out.println("i: " + i); i: 4
} i: 5
System.out.println("Loop complete."); i: 6
} i: 7
} i: 8
i: 9
Loop complete

Using break as a Form of Goto

The general form of the labeled break statement is shown here:

break label;

Most often, a label is the name of a label that identifies a block of code. This can be a stand-alone block of code but
it can also be a block that is the target of another statement. When this form of break executes, control is transferred
out of the named block. The labeled block must enclose the break statement, but it does not need to be the
immediately enclosing block. This means, for example, that you can use a labeled break statement to exit from a set
of nested blocks. But you cannot use break to transfer control out of a block that does not enclose the break
statement
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

// Using break as a civilized form of goto.


class Break {
public static void main(String args[]) {
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break.");
if(t) break second; // break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}

Running this program generates the following output:

Before the break.


This is after the second block.

One of the most common uses for a labeled break statement is to exit from nested loops.
For example, in the following program, the outer loop executes only once:
// Using break to exit from nested loops

class BreakLoop4 {
public static void main(String args[]) {
outer: for(int i=0; i<3; i++) {
System.out.print("Pass " + i + ": ");
for(int j=0; j<100; j++) {
if(j == 10) break outer; // exit both loops
System.out.print(j + " ");
}
System.out.println("This will not print");
}
System.out.println("Loops complete.");
}
}
This program generates the following output:
Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete.

When the inner loop breaks to the outer loop, both loops have been terminated. Notice that this example labels the
for statement, which has a block of code as its target.

Cannot break to any label which is not defined for an enclosing block. For example, the following program is invalid
and will not compile:

// This program contains an error.


BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

class BreakErr {
public static void main(String args[]) {

one: for(int i=0; i<3; i++) {


System.out.print("Pass " + i + ": ");
}

for(int j=0; j<100; j++) {


if(j == 10) break one; // WRONG as “block one” is not in scope of this break.
System.out.print(j + " ");
}
}
}

Since the loop labeled one does not enclose the break statement, it is not possible to transfer
control out of that block.

continue statement

To continue running the loop but stop processing the remainder of the code in its body for this particular iteration.

In while and do-while loops, a continue statement causes control to be transferred directly to the conditional
expression that controls the loop. In a for loop, control goes first to the iteration portion of the for statement and then
to the conditional expression. For all three loops, any intermediate code is bypassed.

class Continue {
public static void main(String args[]) {
for(int i=0; i<10; i++) {
System.out.print(i + " ");
if (i%2 == 0) continue;
System.out.println("");
}
}
}
This code uses the % operator to check if i is even. If it is, the loop continues without printing
a newline. Here is the output from this program:
01
23
45
67
89

continue statement with label:


BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

continue label;

class ContinueLabel {
public static void main(String args[]) {
outer: for (int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
if(j > i) {
System.out.println();
continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}
The continue statement in this example terminates the loop counting j and continues with
the next iteration of the loop counting i. Here is the output of this program:
0
01
024
0369
0 4 8 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 81

return statement:
The last control statement is return. The return statement is used to explicitly return from a method. That is, it causes
program control to transfer back to the caller of the method. As such, it is categorized as a jump statement. At any
time in a method the return statement can be used to cause execution to branch back to the caller of the method.
Thus, the return statement immediately terminates the method in which it is executed. The following example
illustrates this point. Here, return causes execution to return to the Java run-time system, since it is the run-time
system that calls main( ).

System.out.println("Before the return.");


if(t) return; // return to caller
System.out.println("This won't execute.");
}
}

The output from this program is shown here:


Before the return.

As you can see, the final println( ) statement is not executed. As soon as return is executed, control passes back to
the caller. One last point: In the preceding program, the if(t) statement is necessary. Without it, the Java compiler
would flag an “unreachable code” error because the compiler would know that the last println( ) statement would
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

never be executed. To prevent this error, the if statement is used here to trick the compiler for the sake of this
demonstration.

Type conversion and casting:


In any programming language, it is common to assign a value of one type to a variable of another type. If the two types are
compatible, then Java will perform the conversion automatically. For example, it is always possible to assign an int value to a long
variable.
However, not all types are compatible, and thus, not all type conversions are implicitly allowed. For instance, there is no automatic
conversion defined from double to byte. It is still possible to obtain a conversion between incompatible types by using a cast,
which performs an explicit conversion between incompatible types.

Java’s Automatic Conversions:

When one type of data is assigned to another type of variable, an automatic type conversion
will take place if the following two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.

When these two conditions are met, a widening conversion takes place. For example, the int type is always large enough to
hold all valid byte values, so no explicit cast statement is required. For widening conversions, the numeric types, including
integer and floating-point types, are compatible with each other. However, there are no automatic conversions from the
numeric types to char or boolean. Also, char and boolean are not compatible with each other.

Java also performs an automatic type conversion when storing a literal integer constant into variables of type byte, short,
long, or char.

Casting Incompatible Types:

Although the automatic type conversions are helpful, they will not fulfill all needs. For example, what if you want to assign
an int value to a byte variable? This conversion will not be performed automatically, because a byte is smaller than an int.
This kind of conversion is
sometimes called a narrowing conversion, since you are explicitly making the value narrower so that it will fit into the target
type.
To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit type conversion. It
has this general form:

(target-type) value

Here, target-type specifies the desired type to convert the specified value to. For example, the following fragment casts an int
to a byte. If the integer’s value is larger than the range of a byte, it will be reduced modulo (the remainder of an integer
division by the) byte’s range.

int a;
byte b;
// ...
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

b = (byte) a;

A different type of conversion will occur when a floating-point value is assigned to an integer type: truncation.

if the value 1.23 is assigned to an integer, the resulting value will simply be 1. The 0.23 will have been truncated. Of course,
if the size of the whole number component is too large to fit into the target integer type, then that value will be reduced
modulo the target type’s range.

The following program demonstrates some type conversions that require casts:
// Demonstrate casts.
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
This program generates the following output:
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67

Let’s look at each conversion. When the value 257 is cast into a byte variable, the result is the remainder of the division of
257 by 256 (the range of a byte), which is 1 in this case. When the d is converted to an int, its fractional component is lost.
When d is converted to a byte, its fractional component is lost, and the value is reduced modulo 256, which in this case is 67.

Automatic Type Promotion in Expressions.

In addition to assignments, there is another place where certain type conversions may occur: in expressions. To see why,
consider the following. In an expression, the precision required of an intermediate value will sometimes exceed the range of
either operand.
For example, examine the following expression:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
The result of the intermediate term a * b easily exceeds the range of either of its byte operands. To handle this kind of
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

problem, Java automatically promotes each byte, short, or char operand to int when evaluating an expression. This
means that the subexpression a * b is performed using integers—not bytes. Thus, 2,000, the result of the intermediate
expression, 50 * 40, is legal even though a and b are both specified as type byte. As useful as the automatic promotions are,
they can cause confusing compile-time errors.

For example, this seemingly correct code causes a problem:


byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!

Correct Code:
In cases where you understand the consequences of overflow, you should use an explicit cast, such as
byte b = 50;
b = (byte)(b * 2);
which yields the correct value of 100.

Java defines several type promotion rules that apply to expressions. They are as follows:
● First, all byte, short, and char values are promoted to int, as just described.
● Then, if one operand is long, the whole expression is promoted to long.
● If one operand is a float, the entire expression is promoted to float.
● If any of the operands is double, the result is double.

The following program demonstrates how each value in the expression gets promoted to match the second argument to each
binary operator:

class Promote {
public static void main(String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
System.out.println("result = " + result);
}
}

Let’s look closely at the type promotions that occur in this line from the program:
double result = (f * b) + (i / c) - (d * s);

In the first subexpression, f * b, b is promoted to a float and the result of the subexpression is float. Next, in the
subexpression i / c, c is promoted to int, and the result is of type int. Then, in d * s, the value of s is promoted to double, and
the type of the subexpression is double. Finally, these three intermediate values, float, int, and double, are considered. The
outcome of float plus an int is a float. Then the resultant float minus the last double is promoted to double, which is the type
for the final result of the expression.

Example program for implicit and explicit type casting:


BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

public class Testing {


public static void main(String args[])
{
int x = 10;
long y;
y = x; //Implicit type casting - destination type is larger than source type
System.out.println("x= "+ x);
System.out.println("y= "+ y);

byte b;
double d = 3.1468;
b = (byte) d; //Need Explicit type casting - destination type is smaller than source type
System.out.println("b= "+ b);
System.out.println("d= "+ d);

byte b1;
int i1 = 10;
b1 = (byte)i1; //Need Explicit type casting - destination type is smaller than source type
System.out.println("b1= "+ b1);
System.out.println("i1= "+ i1);

byte b2 = 30;
int i2 = 0;
i2 = b2; //Implicit type casting - destination type is larger than source type
System.out.println("b2= "+ b2);
System.out.println("i2= "+ i2);

float f3 = 3.456f;
int i3 = 0;
i3 = (int)f3; //Need Explicit type casting - destination type is smaller than source type

System.out.println("f3= "+ f3);


System.out.println("i3= "+ i3);

byte bb1 = 40;


byte bb2 = 50;
byte bb3 = 100;
byte byted = (byte) ((bb1 * bb2) / bb3); //Need Explicit type casting as the RHS expression is upcasted to int
System.out.println("byted = "+ byted);

int i4 = 5;
f3 = i4;
System.out.println("f3 = "+ f3);
}
}

Output:
javac Testing.java
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

java Testing
x= 10
y= 10
b= 3
d= 3.1468
b1= 10
i1= 10
b2= 30
i2= 30
f3= 3.456
i3= 3
byted = 20
f3 = 5.0

Java Comments: Comments Example:


/*
Comments are used for documenting the code for understanding. Author: Student
There are three types of comments defined by Java. Stream: AI & DS, SEM 3
Section: B
1. Single-line Comment Roll No: 1604-XX-XXX-XX
// Single Line Comment Above is Multi line comment
*/
2. Multiline Comment class AdditionTest{
/* Line – 1 //This method getSum performs addition of two
Line – 2 integers.
Line – 3 Multiline Comments */ //(Above is single line comment)
/**
3. Documentation comment * This is a Documentation Comment.
/** Documentation Comment * @param x
Documentation Comment */ * @param y
* @return
*/
public int getSum(int x, int y)
{
return x+y;
}
public static void main(String args[])
{
AdditionTest at = new AdditionTest();
int s = at.getSum(10,12);
System.out.println(s);
}
}

SEPARATORS:
In Java, there are a few characters that are used as separators.
The most commonly used separator in Java is the semicolon.
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

Arrays:

● An array is a group of like/same-typed variables that are referred to by a common name.


● Arrays of any type can be created and may have one or more dimensions.
● A specific element in an array is accessed by its index.[index starts at 0 and ends at (size -1)]
● Arrays offer a convenient means of grouping related information.

Types of Arrays in Java:

1. Single/One -Dimensional Arrays


2. Multi-Dimensional Arrays (2D, 3D,...) and irregular arrays.
int arr[]; // Declares an integer array
arr = new int[5]; // Allocates memory for integer array of size = 5;
Single/One -Dimensional Arrays Syntax Examples :

Declaration and Allocation of One Dimensional Arrays:


General Form

(Declaration and Allocation in the same statement) : using new int arr[] = new int[5];
operator
datatype arrayname [] = new datatype[size]; // Declares and allocates memory for an integer array
of size = 5
(Declaration and Allocation separately) int arr[]; // Declares an integer array
datatype arrayname []; // (Declaration) arr = new int[5]; //Allocates memory for integer array
arrayname = new datatype[size]; //(Allocation) of size = 5;

(Declaration and Allocation and initialization in one statement) int arr[] = {1, 5, 6, 7};
datatype arrayname [] = {item1, item2, item3, item 4} ;
//item1….item4 must be of same datatype as declared // Declares, allocates memory for an integer array of
size = 5 and also initializes the array with values of 1,
Expressions and literal values can be used inside of array 5, 6 , 7
initializers. (index 0 to index 3)

Array Programs: (One -Dimensional Array)


BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

(Declaration and Allocation and initialization in one statement) (Declaration and Allocation and initialization in
- using for loop one statement) - using for each loop

public class Testing35 { public class Testing355 {

public static void main(String args[]) public static void main(String args[])
{ {
int array1 [] = {1, 2, 3, 4 ,5}; int array1 [] = {1, 2, 3, 4 ,5};

for(int i = 0; i<5;i++) for(int x:array1)


{ System.out.println(x);
System.out.println(array1[i] + " "); }
} }
}
} Output:
1
Output: 2
1 3
2 4
3 5
4
5

(Declaration and Allocation in the same statement) : using new (Declaration and Allocation in the same statement)
operator - for loop : using new operator - foreach loop

public class Testing34 { public class Testing344 {


public static void main(String args[])
{ public static void main(String args[])
int array1 [] = new int[5]; {
int array1 [] = new int[5];
for(int i = 0; i<5;i++)
{ for(int i = 0; i<5;i++)
array1[i] = i+1; {
} array1[i] = i+1;
for(int i = 0; i<5;i++) }
{ for(int x:array1)
System.out.println(array1[i] + " "); System.out.print(x + " ");
} }
} }
}
Output:
Output: 12345
12345

(Declaration and Allocation in the different statements) : using (Declaration and Allocation in the different
new operator - for loop statements) : using new operator - foreach loop
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

public class Testing34 { public class Testing344 {

public static void main(String args[]) public static void main(String args[])
{ {
int array1 []; int array1 [];
array1 = new int[5]; array1 = new int[5];

for(int i = 0; i<5;i++) for(int i = 0; i<5;i++)


{ {
array1[i] = i+1; array1[i] = i+1;
} }
for(int i = 0; i<5;i++) for(int x:array1)
{ System.out.print(x + " ");
System.out.println(array1[i] + " "); }
} }
}
} Output:
12345
Output:
12345

Expressions and literal values can be used inside of array so first row is {1, 1, 1, 1 ,1}
initializers. second row is {2, 2, 2, 2 ,2} and
third row is {3, 3, 3, 3 ,3}

Array Programs: (Two -Dimensional Array)

(Declaration and Allocation and initialization in one statement) (Declaration and Allocation and initialization in
- using for loop one statement) - using for each loop

It is possible to initialize multidimensional arrays. To do so, simply enclose each dimension’s initializer within its own set of
curly braces. The following program creates a matrix where each element contains the product of the row and column
indexes.
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

public class Testing36 { public class Testing36 {

public static void main(String args[]) public static void main(String args[])
{ {
int array1 [][] = {{1, 1, 1, 1 ,1}, {2, 2, 2, 2 ,2}, {3, 3, 3, 3 ,3}}; int array1 [][] = {{1, 1, 1, 1 ,1}, {2, 2, 2, 2 ,2},
{3, 3, 3, 3 ,3}};
for(int i = 0; i<3;i++)
{ for(int x[]:array1)
for(int j = 0; j< 5;j++) {
{ for(int y:x)
System.out.print(array1[i][j] + " "); {
} System.out.print(y + " ");
System.out.println(); }
} System.out.println();
} }
}
Output: }
11111 }
22222 Output:
33333 11111
22222
33333

(Declaration and Allocation in one statements) - using for loop (Declaration and Allocation in one statements) -
using for each loop

public class Testing37 { public class Testing377 {

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

for(int i = 0; i<3;i++) for(int i = 0; i<3;i++)


{ {
for(int j = 0; j< 5;j++) for(int j = 0; j< 5;j++)
{ {
array1[i][j] = i+1; array1[i][j] = i+1;

}
}
}
for(int i = 0; i<3;i++)
{ for(int x[]:array1)
for(int j = 0; j< 5;j++) {
{ for(int y:x)
System.out.print(array1[i][j] + " "); {
} System.out.print(y + " ");
System.out.println(); }
} System.out.println();
} }
} }
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

Output: }
11111
22222 Output:
33333 11111
22222
33333

(Declaration and Allocation in different statements) - using for (Declaration and Allocation in different
loop statements) - using for each loop

public class Testing37 { public class Testing377 {

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

for(int i = 0; i<3;i++) for(int i = 0; i<3;i++)


{ {
for(int j = 0; j< 5;j++) for(int j = 0; j< 5;j++)
{ {
array1[i][j] = i+1; array1[i][j] = i+1;
} }
}
}
for(int i = 0; i<3;i++)
{ for(int x[]:array1)
for(int j = 0; j< 5;j++) {
{ for(int y:x)
System.out.print(array1[i][j] + " "); {
} System.out.print(y + " ");
System.out.println(); }
} System.out.println();
} }
} }
Output: }
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

11111
22222 Output:
33333 11111
22222
33333

Array Programs: (Three (3) -Dimensional Array) 3 by 4 by 5 Array

class Testing41 {
public static void main(String args[])
{
int array1 [][][]= new int[3][4][5];

for (int i = 0; i < 3; i++)


{
for(int j = 0; j < 4; j++)
{
for (int k = 0; k < 5; k++ )
{
array1[i][j][k] = i+1;
}
}
}
for(int x[][]:array1)
{
for(int y[]:x)
{
for(int z:y)
{
System.out.print(z + " ");
}
System.out.println();

}
System.out.println();
}

}
}
Output:

11111
11111
11111
11111

22222
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

22222
22222
22222

33333
33333
33333
33333

Uneven or Irregular - Array (Allocating memory for first dimension,


then later the allocation memory for respective second dimensions)
public class Testing39 {

public static void main(String args[])


{
int [][] array1 = new int[4][];
array1[0] = new int[1];
array1[1] = new int[2];
array1[2] = new int[3];
array1[3] = new int[4];

for(int i = 0; i<4;i++)
{
for(int j = 0; j< i+1;j++)
{
array1[i][j] = i+1;
}

for(int i = 0; i<4;i++)
{
for(int j = 0; j< i+1;j++)
{
System.out.print(array1[i][j] + " ");
}
System.out.println();
}
}
}
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

Output:
1
22
333
4444

The array created by the above program looks like this:

The use of uneven (or, irregular) multidimensional arrays may not be appropriate for many applications, because it runs contrary to
what people expect to find when a multidimensional array is encountered. However, irregular arrays can be used effectively in
some situations. For example, if you need a very large two-dimensional array that is sparsely populated (that is, one in which not
all of the elements will be used), then an irregular array might be a perfect solution.
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

Expressions and literal values can be used inside of array initializers. Below are some programs that implement this
concept.

public class Testing36 {


public static void main(String args[])
{
int array1 [][] = {{1*0, 1*0, 1*0, 1*0 ,1*0}, {2*1, 2*1, 2*1, 2*1 ,2*1}, {3*2, 3*2, 3*2, 3*2,3*2}};

for(int i = 0; i<3;i++)
{
for(int j = 0; j< 5;j++)
{
System.out.print(array1[i][j] + " ");
}
System.out.println();
}
}
}
Output:
00000
22222
66666
public class Testing36 {
public static void main(String args[])
{
int a = 10, b =20;
int array1 [][] = {{1*0, a*b, 1*0, 1*0 ,1*0}, {2*1, 2*1, 2*1, 2*1 ,2*1}, {3*2, 3*2, 3*2, 3*2,3*2}};

for(int i = 0; i<3;i++)
{
for(int j = 0; j< 5;j++)
{
System.out.print(array1[i][j] + " ");
}
System.out.println();
}

}
}
Output:
0 200 0 0 0
22222
66666
length attribute for Arrays:

The size of an array—that is, the number of elements that an array can hold—is found in its length instance variable. All
arrays have this variable, and it will always hold the size of the array. Here is a program that demonstrates this property:
The value of length has nothing to do with the number of elements that are actually in use.
// This program demonstrates the length array member.
class Length {
public static void main(String args[]) {
int a1[] = new int[10];
int a2[] = {3, 5, 7, 1, 8, 99, 44, -10};
int a3[] = {4, 3, 2, 1};
System.out.println("length of a1 is " + a1.length);
System.out.println("length of a2 is " + a2.length);
System.out.println("length of a3 is " + a3.length); } }
This program displays the following output:
length of a1 is 10 length of a2 is 8 length of a3 is 4

Command Line Arguments:


Sometimes you will want to pass information into a program when you run it. This is accomplished by passing
command-line arguments to main( ).

• A command-line argument is the information that directly follows the program’s name on the command line when it is
executed.
class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}
}
java CommandLine
this is a test 100 -1
Output:
args[0]: this
args[1]: is
args[2]: a
args[3]: test
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

args[4]: 100
args[5]: -1

Add two integers using Command Line Arguments.

class CommandLine {
public static void main(String args[]) {
System.out.println("sum = "+Integer.parseInt(args[0]) + Integer.parseInt(args[1]));
}
}

Output:
PS E:\OJ> javac CommandLine.java
PS E:\OJ> java CommandLine 2 3
Output:
sum = 5
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]

It is important to understand that finalize( ) is only called just prior to garbage collection. It is not called when an object
goes out-of-scope, for example. This means that you cannot know when—or even if—finalize( ) will be executed. Therefore,
your program should provide other means of releasing system resources, etc., used by the object. It must not rely on finalize(
) for normal program operation.
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
____________________________________________________________
}

class CallByRef {
public static void main(String
args[]) { Test ob = new Test(15,
20);
System.out.println("ob.a and ob.b before
call: " + ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after
call: " + ob.a + " " + ob.b);
}

This program generates the following output:


ob.a and ob.b before call:
15 20 ob.a and ob.b after
call: 30 10
As you can see, in this case, the actions inside meth( ) have affected the object used as an argument

this keyword
Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines this keyword. this
can be used inside any method to refer to the current object. That is, this is always a reference to the object on which
the method was invoked. You can use this anywhere a reference to an object of the current class’ type is permitted.
To better understand what this refers to, consider the following version of Box( ):
// A redundant use of this.

// A redundant use of this.


Box(double w, double h, double d) {
this.width = w;
BE CSE (AI & AIML) III SEM OOPS Using Java: PC 303 CS [Unit 1: Part 1]
____________________________________________________________
this.height = h;
this.depth = d;
}

This version of Box( ) operates exactly like the earlier version. The use of this is redundant, but perfectly correct.
Inside Box( ), this will always refer to the invoking object.

Instance Variable Hiding


There is another version of Box( ), which uses width, height, and depth for parameter names and
then uses this to access the instance variables by the same name:

*************END OF UNIT 1- PART 1*************

You might also like