Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Oop CH 1-2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

Object Oriented Programming -I B.E.

4th

Chapter 1 : Introduction To Java And


Elementary Programming
 Introduction
 A brief history of Java
 The history of Java begins in the early 1990s when a team of developers at Sun
Microsystems, led by James Gosling, started working on a project originally named
"Oak." The project aimed to create a language and platform-independent programming
environment for consumer electronics, particularly set-top boxes.
 1) 1991-1992: James Gosling and his team began working on the Oak language, inspired
by C and C++. It was designed to be simple, portable, and reliable for embedded systems.
 2) 1994: Oak was renamed "Java" due to trademark issues. The name was inspired by the
coffee consumed in large quantities by the development team. The first public release of
Java (Java 1.0) was made available in May 1995.
 3) 1995: Java 1.0 was officially released, along with the first version of the Java
Development Kit (JDK). This release included the core Java libraries, the Java Virtual
Machine (JVM), and the Java compiler.
 4) 1996: Java 1.1 was released, introducing significant improvements and new features
such as JDBC (Java Database Connectivity) for database access and inner classes.
 5) 1997: Java 1.2, also known as Java 2, was released with major enhancements,
including the Swing GUI toolkit, the Collections Framework, and the JIT (Just-In-Time)
compiler for improved performance.
 Throughout its history, Java has become one of the most popular programming languages
worldwide, known for its portability, versatility, and robustness. It's used in a wide range
of applications, from web development and enterprise systems to mobile apps, IoT
devices, and large-scale distributed systems.

 Java Language

 Java is programming language ,which allow a programmer to create and compile a


program on one machine that will run on computers with different operating system.
 Java is a widely-used programming language for coding web applications. It has been a
popular choice among developers for over two decades, with millions of Java applications
in use today.

 Features of java

1. Object-Oriented : Java is a purely object-oriented programming language, emphasizing


the concept of objects and classes. It supports encapsulation, inheritance, and
polymorphism, enabling developers to create modular and reusable code.

SREZ Page 1
Object Oriented Programming -I B.E. 4th

2. Platform Independent : Java programs are compiled into bytecode, which can be
executed on any device with a Java Virtual Machine (JVM). This "write once, run
anywhere" capability allows Java applications to be platform-independent, making them
highly portable.

3. Secure : Java places a strong emphasis on security, with features such as bytecode
verification, runtime security checks, and a robust security model. These features help
prevent various security vulnerabilities and protect against malicious attacks.

4. Architectural- neutral : Java compiler generates an architecture-neutral object file


format which makes the compiled code to be executable on many processors with the
presence Java runtime system.

5. Portable: being architectural neutral and having no implementation dependent aspects of


the specification makes Java portable. Compiler and Java is write ANSI C with a clean
portability boundary which is a POSIX subset.

6. Robust : Java makes an effort to eliminate error prone situations by emphasizing mainly
on compile time error checking and runtime checking.

7. Multi-threaded: With Java.s multi-threaded feature it is possible to write program that


can do many tasks simultaneously. This design feature allows developers construct
smoothly running interactive applications.

8. Interpreted: Java byte code is translated on the fly to native machine instruction
and is not stored anywhere. The development process is more rapid and analytic
since the linking is an incremental and light weight process.

9. High Performance: With the use of Just-In-Time compilers Java enables high
performance.

10. Distributed: Java is designed for the distributed environment of the internet.

11. Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to
adapt to an evolving environment. Java programs can carry extensive amount of a run-
time information that can be used to verify and resolve accesses to objects an run-time.

 How does Java work?


 All programming languages are a means to communicate with machines. Machine
hardware only responds to electronic communication.
 High-level programming languages like Java act as a bridge between human language and
hardware language.
 To use Java, a developer needs to understand two things:

SREZ Page 2
Object Oriented Programming -I B.E. 4th

1. Java language and APIs : This is the front-end communication between the developer and
the Java platform.

2. Java Virtual Machine : This is the back-end communication between the Java platform and
the underlying hardware.

What is Java API?


 Java defines the syntax and semantics of the Java programming language. This includes
the basic vocabulary and rules used to write algorithms such as primitive data types,
if/else blocks, loops, etc.
 APIs are important software components bundled with the Java Platform. These are pre-
written Java programs that can plug and play existing functionality into your own code.
For example, you could use Java APIs to get the date and time, perform mathematical
operations, or manipulate text.
 Any Java application code written by a developer will typically combine new and pre-
existing code from Java APIs and Java libraries.

 JDK, JRE, JVM

JDK (Java Development Kit)

 Provides the environment to develop and execute(run) the Java program.


 JDK is a kit(or package) that includes two things :
1. Development Tools(to provide an environment to develop your java programs)
2. JRE (to execute your java program).

JRE (Java Runtime Environment)


 JRE (Java Runtime Environment) is an installation package that provides an environment
to only run(not develop) the java program(or application)onto your machine.
 JRE is a part of JDK, but can be downloaded separately.
 JRE is only used by those who only want to run Java programs that are end-users of your
system.

SREZ Page 3
Object Oriented Programming -I B.E. 4th

Byte code
 it is a intermediate representation of a java source code.
 it produce by java compiler by compiling java source code
 extension of java class file or byte id called .class
 it is a platform independent

JVM (Java Virtual Machine)

 The Java Virtual Machine (JVM) serves as a runtime environment for executing Java
bytecode, adhering to a standardized specification.
 As the name suggests, the JVM operates as a virtual processor, enabling platform-
independent execution of Java programs. T
 he cornerstone of Java's platform independence lies in its JVM, which facilitates seamless
operation .
 The JVM performs following operation:

 Loads code
 Verifies code
 Executes code

 Creating, Compiling And Executing A Simple Java Program

 Java Programming Structure :

public class Hello


{
public static void main(String args[] )
{
System.out.println("Hello Wold ! ");
}
}

SREZ Page 4
Object Oriented Programming -I B.E. 4th

class Hello
 it is a name of a class.

public static void main(String args[] )


1. Access Modifier: `public`
- The `public` keyword is an access modifier that indicates the visibility of the method.
In this case, `public` means that the `main` method can be accessed from outside the
class.

2. Static Modifier: `static`


- The `static` keyword indicates that the `main` method belongs to the class itself, rather
than to instances of the class. This means that you can invoke the `main` method without
creating an object of the class.

3. Return Type: `void`


- The `void` keyword indicates that the `main` method does not return any value. It
simply performs actions and does not produce a result.

4. Method Name: `main`


- The `main` method is the name of the entry point method in a Java program. This is
the standard name recognized by the JVM.

5. Parameters: `(String[] args)`


- The `main` method takes a single parameter, which is an array of strings (`String[]`).
This parameter, commonly named `args`, allows you to pass command-line arguments to
the Java program when it is executed.

6. String args[]:
- `String args[]` is the parameter declaration, where `String[]` specifies that `args` is an
array of strings. - The name `args` can be any valid Java identifier, but conventionally it
is named `args`, short for "arguments".

Putting it all together, `public static void main(String[] args)` declares a `main` method
that is:
- Accessible from outside the class (`public`).
- Belongs to the class itself, not to instances of the class (`static`).
- Does not return any value (`void`).
- Takes an array of strings as a parameter, which can be used to pass command-line
arguments to the program (`String[] args`).

System.out.println

SREZ Page 5
Object Oriented Programming -I B.E. 4th

System: System is a predefined class in the java.lang package. It provides access to


system-related properties and methods.

out: out is a public static field (instance) of the System class. It represents the standard
output stream, typically the console or command line.

println(): println() is a method of the PrintStream class, which is the type of the out field.
It is used to print a string to the standard output stream
followed by a newline character (\n). The println() method has several overloaded
versions to print different data types.

Execution of Java Program :

open Command prompt (cmd) and command :


To compile: javac Hello.java
This command will compile source file and if the compilation is successful, it will
generate a file named FirstJava.class containing bytecode.
Java compiler translate java program into bytecode form.
To Run : java Hello
the command called 'java' takes the bytecode and runs the bytecode on JVM.
Output:
Hello World !

 Type Casting in Java :


 type casting is a method or process that converts a data type into another
data type in both ways manually and automatically.
 The automatic conversion is done by the compiler and manual conversion
performed by the programmer. In this section, we will discuss type casting
and its types with proper example.

SREZ Page 6
Object Oriented Programming -I B.E. 4th

 There are two types of type casting


1. Widening Type Casting
 Converting a lower data type into a higher one is called widening type casting. It is
also known as implicit conversion or casting down.
 It is done automatically. It is safe because there is no chance to lose data. It takes
place when:
 Both data types must be compatible with each other.
 The target type must be larger than the source type.
byte -> short -> char -> int -> long -> float -> double

2. Narrowing Type Casting


 Converting a higher data type into a lower one is called narrowing type casting. It is
also known as explicit conversion or casting up.
 It is done manually by the programmer. If we do not perform casting then the
compiler reports a compile-time error.

double -> float -> long -> int -> char -> short -> byte

 Identifiers and Variables


In Java, identifiers and variables play a crucial role in programming as they are used to
represent various elements such as classes, methods, variables, and more. Let's discuss
identifiers and variables in Java:

1. Identifiers:
- An identifier in Java is a sequence of characters that consists of letters (uppercase or
lowercase), digits, underscores (_), and dollar signs ($).
- The first character of an identifier must be a letter, underscore (_), or dollar sign ($).
- Identifiers cannot contain spaces or special characters (except for underscores and
dollar signs after the first character).
- Java is case-sensitive, so uppercase and lowercase letters are considered different.

Example of valid identifiers: Example of invalid identifiers:

- `variableName` - `123variable` (starts with a digit)


- `_variable` - `my variable` (contains a space)
- `$variable` - `my-variable` (contains a hyphen)

SREZ Page 7
Object Oriented Programming -I B.E. 4th

- `myVariable123` - `my.variable` (contains a period)


- `MyClass`
- `MAX_VALUE`

2. Variables:
- In Java, a variable is a named storage location in memory that holds a value of a
particular data type.
- Variables must be declared before they can be used. The declaration specifies the
variable's name and its data type.
- Java supports different types of variables, including primitive types and reference
types.
Example of variable declaration and initialization:
int age = 30; // Declares and initializes the 'age' variable
double salary = 50000.50; // Declares and initializes the 'salary' variable
String name = "John"; // Declares and initializes the 'name' variable

 Data types in java

 Data types in Java specify how memory stores the values of the variable. Each variable
has a data type that decides the value the variable will hold.
 By assigning different data types to variable, you can store integers, decimal or characters
in these variable.

Data types in Java are divided into 2 categories:

1. Primitive Data Types


2. Non-Primitive Data Types / Object data types

Primitive Data Types


Primitive data types specify the size and type of variable values. They are the building blocks
of data manipulation and cannot be further divided into simpler data types.

There are 8 Primitive data types in Java – Boolean, char, byte, int, short, long, float, and
double.

byte:
Byte data type is a 8-bit signed two.s complement integer.
Minimum value is -128(-2^7)
Maximum value is 127 (inclusive)(2^7-1)
Default value is 0
Byte data type is used to save space in large arrays, mainly in place of integers since a byte is
four times smaller than an int
Example: byte a=100 byte b=-50

short:
Short data type is a 16-bit signed two's complement integer
Minimum value is -32,768 (-2^15)

SREZ Page 8
Object Oriented Programming -I B.E. 4th

Maximum value is 32,767 (inclusive) (2^15-1)


Short data type can also be used to save memory as byte data type.
A short is 2 times smaller than an int
Default value is 0.
Example: short s=1000 short r=-2000

int :
Int data type is a 32-bit signed two's complement integer.
Minimum value is 2,147,483,648.(-2^31)
Maximum value is 2,147,483,647 (inclusive). (2^31-1)
Int is generally used as the default data type for integral values unless there is. concern about
memory.
The default value is 0.
Example: int a=10000 int b=-200000

long:
Long data type is a 64-bit signed two's complement integer.
Minimum value is -9,223,372,036,854,775,808 (-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63-1)
This type is used when a wider range than int is needed.
Default value is 0L..
Example: int a = 100000L, int b = -200000L

float:
Float data type is a single-precision 32-bit IEEE 754 floating point.
Default value is 0.0f.
Float is mainly used to save memory in large arrays of floating point numbers
Float data type is never used for precise values such as currency. Example: float f1 = 234.5f

double:
double data type is a double-precision 64-bit IEEE 754 floating point.
This data type is generally used as the default data type for decimal values. generally the
default choice.

Double data type should never be used for precise values such as currency.
Default value is 0.0d.
Example: double d1 = 123.4

boolean:
boolean data type represents one bit of information.
There are only two possible values: true and false.
This data type is used for simple flags that track true/false conditions.
Default value is false.
Example: boolean one = true

char.:
char data type is a single 16-bit Unicode character.
Minimum value is '\u0000' (or 0).
Maximum value is '\uffff' (or 65,535 inclusive).

SREZ Page 9
Object Oriented Programming -I B.E. 4th

Char data type is used to store any character.


Example: char letterA ='A'

Non-Primitive Data Types


Non-primitive data types or reference data types refer to instances or objects. They cannot
store the value of a variable directly in memory. They store a memory address of the variable.
Unlike primitive data types we define by Java, non-primitive data types are user-defined.
Programmers create them and can be assigned with null. All non-primitive data types are of
equal size.

Array, Class, Interfaces, String, Enum.

 Java Basic Operators

Java provides a rich set of operators to manipulate variable. Java operators can be divide
into the following group:

Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators

 The Arithmetic Operators

Arithmetic operators are used in mathematical expressions in the same way that they are used
in algebra. The following table lists the arithmetic operators −

Assume integer variable A holds 10 and variable B holds 20, then

SREZ Page 10
Object Oriented Programming -I B.E. 4th

 The Relational Operators

There are following relational operators supported by Java language.

Assume variable A holds 10 and variable B holds 20, then −

SREZ Page 11
Object Oriented Programming -I B.E. 4th

 The Bitwise Operators

Java defines several bitwise operators, which can be applied to the integer types, long, int,
short, char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b =
13; now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators −
Assume integer variable A holds 60 and variable B holds 13 then

 The Logical Operators

The following table lists the logical operators −


Assume Boolean variables A holds true and variable B holds false, then −

SREZ Page 12
Object Oriented Programming -I B.E. 4th

 The Assignment Operators

Following are the assignment operators supported by Java language −

 Miscellaneous Operators

There are few other operators supported by Java Language.


 Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to decide,
which value should be assigned to the variable. The operator is written as −

- variable x = (expression) ? value if true : value if false

 instanceof Operator
This operator is used only for object reference variables. The operator checks whether the
object is of a particular type (class type or interface type). instanceof operator is written as −

( Object reference variable ) instanceof (class/interface type)

If the object referred by the variable on the left side of the operator passes the IS-A check for
the class/interface type on the right side, then the result will be true.

SREZ Page 13
Object Oriented Programming -I B.E. 4th

 Precedence of Java Operators

 Operator precedence determines the grouping of terms in an expression. This affects how
an expression is evaluated. Certain operators have higher precedence than others; for
example, the multiplication operator has higher precedence than the addition operator −
 For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3 * 2 and then adds into 7.
 Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.

SREZ Page 14
Object Oriented Programming -I B.E. 4th

Chapter 2 : Selections , Mathematical functions and loops

 Decision making statement

 Decision making structures have one or more conditions to be evaluated or tested by the
program, along with a statement or statements that are to be executed if the condition is
determined to be true, and optionally, other statements to be executed if the condition is
determined to be false.
 Following is the general form of a typical decision making structure found in most of the
programming languages −

Java programming language provides following types of decision making statements.

1. if statement : An if statement consist of boolean expression followed by one or more


statements.

2. if...else statement : An if statement can be followed by an optional else statement,


which execute when the boolean expression is false.

3. nested if statement

You can use one if or else if statement inside another if or else if statement(s).

4. switch statement

A switch statement allows a variable to be tested for equality against a list of values.

SREZ Page 15
Object Oriented Programming -I B.E. 4th

 if statement :

 Syntax of if Statement :

if(Boolean_expression)
{
// Statements will execute if the Boolean expression is true

Working of if Statement :

 If the Boolean expression evaluates to true then the block of code inside the if statement
will be executed. If not, the first set of code after the end of the if statement (after the
closing curly brace) will be executed.

 Example 1
 In this example, we're showing the use of a if statement to check if a value of variable, x
is less than 20. As x is less than 20, the statement within if block will be printed.

public class Test


{
public static void main(String args[])
{
int x = 10;
if( x < 20 )
{
System.out.print("This is if statement");
}
}
}
Output :
This is if statement

 if...else statement :

 In java, the if else statement is used to execute two code blocks based on the given
condition.
 A java if statement executes when the Boolean expression for the if statement is true. An
if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.
 Syntax of if-else Statement in Java :

if(Boolean_expression) {
// Executes when the Boolean expression is true
}else {
// Executes when the Boolean expression is false
}

SREZ Page 16
Object Oriented Programming -I B.E. 4th

If the boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.
Example:
In this example, we're showing the usage of if else statement. We've created a variable x and
initialized it to 30. Then in the if statement, we're checking x with 20. As if statement is false,
the statement within the else block is executed.

public class Test


{
public static void main(String args[])
{
int x = 30;
if( x < 20 )
{
System.out.print("This is if statement");
}else
{
System.out.print("This is else statement");
}
}
}
Output :
This is else statement

 if-else-if Statement :

 The if...else if...else statement is used for executing multiple code blocks based on the
given conditions (Boolean expressions).
 An if statement can be followed by an optional else if...else statement, which is very
useful to test various conditions using a single if...else if statement.
 Points to Remember
 An if can have zero or one else's and it must come after any else if's.
 An if can have zero to many else if's and they must come before the else.
 Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax of if-else-if statement :

if(Boolean_expression 1) {
// Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2) {
// Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3) {
// Executes when the Boolean expression 3 is true
}else {
// Executes when the none of the above condition is true.
}

SREZ Page 17
Object Oriented Programming -I B.E. 4th

Example

In this example, we're showing the usage of if...else if...else statement. We've created a
variable x and initialized it to 30. Then in the if statement, we're checking x with 10. As if
statement is false, control jumps to else if statement checking another value with x and so
on.

public class Test


{
public static void main(String args[])
{
int x = 30;
if( x == 10 )
{
System.out.print("Value of X is 10");
}else if( x == 20 )
{
System.out.print("Value of X is 20");
}else if( x == 30 )
{
System.out.print("Value of X is 30");
}else
{
System.out.print("This is else statement");
}
}
}

Output
Value of X is 30

 nested if else statement :

 The nested if else statement is used for better decision-making when other conditions are
to be checked when a given condition is true. In the nested if else statement, you can have
an if-else statement block the another if (or, else) block.
 Syntax of nested if-else statement :

if(condition1){
// code block
if(condition2){
//code block
}
}

Example

The following examples finds the largest number among three using nested if..else statement.

SREZ Page 18
Object Oriented Programming -I B.E. 4th

public class Test


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

int x = 10, y = 20, z = 30;

if(x >= y)
{
if(x >= z)
System.out.println(x + " is the largest.");
else
System.out.println(z + " is the largest.");
} else
{
if(y >= z)
System.out.println(y + " is the largest.");
else
System.out.println(z + " is the largest.");
}
}
}
Output :
30 is the largest.

 Java switch Statement

The Java switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each case.

The switch statement can be used when multiple if-else statement are required. It can have
multiple code blocks along with the case values and executes one of many code blocks based
on the matches case value.

Syntax :

switch(expression) {

case value :

// Statements

break; // optional

case value :

// Statements

SREZ Page 19
Object Oriented Programming -I B.E. 4th

break; // optional

// You can have any number of case statements.

default : // Optional

// Statements

Rules :

 The variable used in a switch statement can only be integers, convertable integers (byte,
short, char), strings and enums.
 You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.
 The value for a case must be the same data type as the variable in the switch and it must
be a constant or a literal.
 When the variable being switched on is equal to a case, the statements following that case
will execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control jumps
to the next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true.
No break is needed in the default case.
 Example:
In this example, we're showing use of switch statement where cases are based on a char.
We've created a variable grade. Based on value of grade, each case is checked. if a case is
satisfied and break statement is present then following cases are not checked
public class Test {

public static void main(String args[]) {


char grade = 'C';

switch(grade) {
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :

SREZ Page 20
Object Oriented Programming -I B.E. 4th

System.out.println("Better try again");


break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}

 Common Mathematical Functions

There are three types of mathematical functions that are commonly used
1.Trigonometric Function
2.Exponent Method
3.Service Method

Trigonometric function

SREZ Page 21
Object Oriented Programming -I B.E. 4th

Exponent method

Service method

 LOOPS

 While Loop
The Java while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop.
Syntax:
while(condition){
//code to be executed
}

SREZ Page 22
Object Oriented Programming -I B.E. 4th

 DO-WHILE LOOP
 The Java do-while loop is used to iterate a part of the program several times. If the
number of iteration is not fixed and you must have to execute the loop at least once, it is
recommended to use do-while loop.
 The Java do-while loop is executed at least once because condition is checked after loop
body.
Syntax:
do{
//code to be executed
}while(condition);

SREZ Page 23
Object Oriented Programming -I B.E. 4th

 FOR LOOP
A simple for loop is the same as C/C++. We can initialize the variable, check condition and
increment/decrement value. It
consists of four parts:
1. Initialization: It is the initial condition which is executed once when the loop starts. Here,
we can initialize the
variable, or we can use an already initialized variable. It is an optional condition.
2. Condition: It is the second condition which is executed each time to test the condition of
the loop. It continues
execution until the condition is false. It must return boolean value either true or false. It is an
optional condition.
3. Statement: The statement of the loop is executed each time until the second condition is
false.
4. Increment/Decrement: It increments or decrements the variable value. It is an optional
condition.

Syntax:
for(initialization;condition;incr/decr){
//statement or code to be executed
}

SREZ Page 24
Object Oriented Programming -I B.E. 4th

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

 The ? : Operator

SREZ Page 25
Object Oriented Programming -I B.E. 4th

 We have covered conditional operator ? : in the previous chapter which can be used to
replace if...else statements. It has the following general form −
o Exp1 ? Exp2 : Exp3;
 Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
 To determine the value of the whole expression, initially exp1 is evaluated.
 If the value of exp1 is true, then the value of Exp2 will be the value of the whole
expression.
 If the value of exp1 is false, then Exp3 is evaluated and its value becomes the value of the
entire expression.
o Example
 In this example, we're creating two variables a and b and using ternary operator we've
decided the values of b and printed it.

public class Test {


public static void main(String args[])
{
int a, b;
a = 10;
b = (a = = 1) ? 20: 30;
System.out.println( "Value of b is : " + b );

b = (a = = 10) ? 20: 30;


System.out.println( "Value of b is : " + b );
}
}
Output
value of b is : 30
value of b is : 20

 The Break And Continue

 Break statement
 The break statement in Java terminates the loop immediately, and the control of the
program moves to the next statement following the loop.
 It is almost always used with decision-making statements (Java if...else Statement).
 Here is the syntax of the break statement in Java:
break;

SREZ Page 26
Object Oriented Programming -I B.E. 4th

Nested Break

Labeled Break

SREZ Page 27
Object Oriented Programming -I B.E. 4th

 Continue Statement
 The continue statement in Java skips the current iteration of a loop (for, while,
do...while, etc) and the control of the program moves to the end of the loop. And, the
test expression of a loop is evaluated.
 In the case of for loop, the update statement is executed before the test expression.
 The continue statement is almost always used in decision-making statements (if...else
Statement).
 It's syntax is:
continue;

SREZ Page 28
Object Oriented Programming -I B.E. 4th

Nested Continue

Labeled Continue

SREZ Page 29

You might also like