Oops Java Unit 1 Part 1
Oops Java Unit 1 Part 1
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]
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.
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.
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]
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.
● 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]
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]
public static void main(String args []) The Unsigned Right Shift / Shift Zero Fill
{ Explanation:
int a = -1;
System.out.println(a>>>24);
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:
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.
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:
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.
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]
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)
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 + ".");
}
}
}
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.
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]
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]
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);
}
}
}
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]
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]
..........
.........
........
.......
......
.....
....
...
..
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.
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:
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
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]
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:
class BreakErr {
public static void main(String args[]) {
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 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( ).
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.
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.
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.
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.
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.
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
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
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:
(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)
(Declaration and Allocation and initialization in one statement) (Declaration and Allocation and initialization in
- using for loop one statement) - using for each loop
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};
(Declaration and Allocation in the same statement) : using new (Declaration and Allocation in the same statement)
operator - for loop : using new operator - foreach loop
(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 static void main(String args[]) public static void main(String args[])
{ {
int array1 []; int array1 [];
array1 = new int[5]; array1 = new int[5];
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}
(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 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 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 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 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];
11111
22222 Output:
33333 11111
22222
33333
class Testing41 {
public static void main(String args[])
{
int array1 [][][]= new int[3][4][5];
}
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
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 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.
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
• 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
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 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.
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.