[Go to site: main page, start]

0% found this document useful (0 votes)
42 views54 pages

Object Oriented Programming in Java

The document outlines the course material for Object Oriented Programming through Java for B.Tech students in Information Technology. It includes course objectives, prerequisites, a detailed syllabus, course outcomes, and a lesson plan covering various Java programming concepts. Additionally, it provides resources for practice quizzes, assignments, and supportive online certification courses.

Uploaded by

trywin01378
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views54 pages

Object Oriented Programming in Java

The document outlines the course material for Object Oriented Programming through Java for B.Tech students in Information Technology. It includes course objectives, prerequisites, a detailed syllabus, course outcomes, and a lesson plan covering various Java programming concepts. Additionally, it provides resources for practice quizzes, assignments, and supportive online certification courses.

Uploaded by

trywin01378
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

COURSE MATERIAL

OBJECT ORIENTED PROGRAMMING


SUBJECT THROUGH JAVA(CS23APC302)

UNIT 1

COURSE [Link]

DEPARTMENT Information Technology

SEMESTER 21

PREPARED BY
(Faculty Name/s) [Link], Assistant professor

Version V-1

PREPARED / REVISED DATE 21-07-2025


SVEC TIRUPATI
TABLE OF CONTENTS – UNIT 1
S. NO CONTENTS
1 COURSE OBJECTIVES
2 PREREQUISITES
3 SYLLABUS
4 COURSE OUTCOMES
5 CO - PO/PSO MAPPING
6 LESSON PLAN
7 ACTIVITY BASED LEARNING
8 LECTURE NOTES
1.1 INTRODUCTION TO OBJECT ORIENTED PROGRAMMING
1.2 Basic concepts, Principles
1.3 Program Structure in Java:
1.4 Writing Simple Java Programs
1.5 Elements or Tokens in Java Programs
1.6 Java Statements
1.7 Command Line Arguments
1.8 User Input to Programs
1.9 Escape Sequences Comments, Programming Style
1.10 Type Casting, Scope of Variable Identifier
1.11 Literal Constants, Symbolic Constants
1.12 Formatted Output with printf() Method, Static Variables
and Methods
1.13 Attribute Final,
Introduction to Operators
1.14 Precedence and Associativity of Operators, Assignment
Operator ( = )
1.15 Basic Arithmetic Operators, Increment (++) and
Decrement (- -)Operators, Ternary Operator,
1.16 Relational Operators, Boolean Logical Operators, Bitwise
Logical Operators.
1.17 Control Statements: Introduction, if Expression, Nested if
Expressions, if–else Expressions, Ternary Operator?:,
Switch Statement, Iteration Statements
1.18 while Expression, do–while Loop, for Loop, Nested for
Loop, For–Each for Loop, Break Statement, Continue
Statement.
9 PRACTICE QUIZ
10 ASSIGNMENTS
11 PART A QUESTIONS & ANSWERS (2 MARKS QUESTIONS)
12 PART B QUESTIONS
13 SUPPORTIVE ONLINE CERTIFICATION COURSES
14 REAL TIME APPLICATIONS

BTECH_IT-SEM 21
SVEC TIRUPATI
15 CONTENTS BEYOND THE SYLLABUS
16 PRESCRIBED TEXT BOOKS & REFERENCE BOOKS
17 MINI PROJECT SUGGESTION

BTECH_IT-SEM 21
1. Course Objectives
The objectives of this course are to
1. To understand object oriented concepts and problem solving techniques
2. To obtain knowledge about the principles of inheritance and polymorphism
3. To implement the concept of packages, interfaces, exception handling and
concurrency mechanism.
4. To design the GUIs using applets and swing controls.
5. To understand the Java Database Connectivity Architecture

2. Prerequisites
Students should have knowledge on
1. C Programming Syntax and Semantics
2. Object Oriented Programming Concepts

3. Syllabus
UNIT I
Object Oriented Programming: Basic concepts, Principles, Program Structure in Java: Introduction,
Writing Simple Java Programs, Elements or Tokens in Java Programs, Java Statements, Command Line
Arguments, User Input to Programs, Escape Sequences Comments, Programming Style.
Data Types, Variables, and Operators :Introduction, Data Types in Java, Declaration of Variables, Data
Types, Type Casting, Scope of Variable Identifier, Literal Constants, Symbolic Constants, Formatted
Output with printf() Method, Static Variables and Methods, Attribute Final,
Introduction to Operators, Precedence and Associativity of Operators, Assignment Operator ( = ),
Basic Arithmetic Operators, Increment (++) and Decrement (- -)Operators, Ternary Operator,
Relational Operators, Boolean Logical Operators, Bitwise Logical Operators.
Control Statements: Introduction, if Expression, Nested if Expressions, if–else Expressions, Ternary
Operator?:, Switch Statement, Iteration Statements, while Expression, do–while Loop, for Loop,
Nested for Loop, For–Each for Loop, Break Statement, Continue Statement.

4. Course outcomes
Student should be able to
Understand the syntax, semantics and features of Java Programming
Language.
Learn object oriented features and understanding type conversion and
casting.
Understand different types of string handling functions and its usage.

5. Co-PO / PSO Mapping


Machine
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 P10 PO11 PO12 PSO1 PSO2
Tools

CO1 2 2 2 1 3 1 1 3 1 3 2 3 3

CO2 1 2 3 3 1 2 3 1 1 3 3

CO3
2 2 2 3 3 1 1 3 3
6. Lesson Plan
LECTURE WEEK TOPICS TO BE COVERED REFERENCES

1 INTRODUCTION TO OBJECT ORIENTED PROGRAMMING T1,R!

Basic concepts, Principles T1, R1


2
1
Program Structure in Java: T1, R1
3
Writing Simple Java Programs T1, R1
4
Elements or Tokens in Java Programs T1, R2
5
Java Statements T1, R1
6
2
Command Line Arguments T1, R1
7

8 User Input to Programs T1, R1

Escape Sequences Comments, Programming Style T1, R1


9
Type Casting, Scope of Variable Identifier T1, R1
10
3
Literal Constants, Symbolic Constants T1, R1
11
Formatted Output with printf() Method, Static T1, R1
12
Variables and Methods
Attribute Final, T1, R1
13
Introduction to Operators
Precedence and Associativity of Operators, T1, R1
14
4 Assignment Operator ( = )
Basic Arithmetic Operators, Increment (++) and T1, R1
15
Decrement (- -)Operators, Ternary Operator,
Relational Operators, Boolean Logical Operators, T1, R1
16
Bitwise Logical Operators.

7. Activity Based Learning

1. Develop programs by applying Object oriented concepts.


2. Implementation of String handling functions.

8. Lecture Notes

1.1 INTRODUCTION
1. Java Is A “Programming Language”.
2. A Programming Language Is Set Of Instructions , Used To Establish
Communication Between Human And A System
3. Java technology is both a programming language and a platform.
4. Java is a high level, robust, secured and object-oriented programming
language.

[Link] IT 21
SVEC TIRUPATI

 Program Structure in Java:


 Introduction
 Writing Simple Java Programs
 Elements or Tokens in Java Programs
 Java Statements
 Command Line Arguments
 User Input to Programs
 Escape Sequences
 Comments
 Programming Style.
 Data Types Variables and Operators :
 Introduction Data Types in Java
 Declaration of Variables Data Types
 Type Casting
 Scope of Variable Identifier
 Literal Constants, Symbolic Constants
 Formatted Output with printf() Method
 Static Variables and Methods
 Attribute Final
 Introduction to Operators
 Precedence and Associativity of Operators
 Assignment Operator ( = )
 Basic Arithmetic Operators
 Increment (++) and Decrement (- -) Operators
 Ternary Operator Relational Operators
 Boolean Logical Operators
 Bitwise Logical Operators.
 Control Statements:
 Introduction
 if Expression
 Nested if Expressions
 if–else Expressions
 Ternary Operator?:
 Switch Statement
 Iteration Statements
 while Expression
 do–while Loop
[Link]
1) Nested for Loop
2) For–Each for Loop
3) Break Statement
3|O O P S - U N I T - I

[Link] IT SEM21
SVEC TIRUPATI
4) Continue Statement.
5) Program Structure in Java:

 Introduction

Java is an Object Orient and high-level programming language, originally


developed by Sun Microsystems and released in 1995. Java runs on a variety of
platforms, such as Windows, Mac OS, Linux etc.

In Java, there are three types of programs as follows:


Stand- aline application programs : These programs are made and run on
users computers
Applet programs : These programs are meant to run in a web page on the
Internet. Java Servlets : These programs run in computers that provide web
services. They are also oftern called server isde programs or servlets.

 Writing Simple Java Programs


Java is an Object oriented language. Every java program imports packages
which are provides necessary classes and interfaces.
For example:
import [Link].*; import
[Link].*;

After import statement, every java program starts with the declaration of the
class. A program may have one or more classes.

A class declaration starts with the keyword class, followed by the identifier or name
of the class. Giving the name of a package at the top is optional.

Class declarion contains name of the class and body of the class. The body of
the class may consist of several statements and is enclsed between the
braces {}.

A sample of class declarions is as follows.

Here:
public is access specifier. This class is accessible to any ouside code. Otherwise
the class is accessibe to only same package classes.
4|O O P S - U N I T - I

[Link] IT SEM21
SVEC TIRUPATI
class is a keyword of java language which is used to declare the class.
The class body starts with the left brace { and ends with the right colsing brace }.
// are comments which are neglected by the compiler.A class body may comprise
statements for declaration of variables. constants, expressions, and methods.

Simple program in Java. Save this code in Text Document as “[Link]”

public class Start()


{
public static void main()
{
[Link](“Hello World”);
}
}

Here:
class is a keyword
Start is a name the class. Here class is declared as public, so it is
available to all the classes.
main() is the method which initiate and terminate the program ( in java
functions are called as Methods)
println() is method of object “out”. “out” is the object of class
“System”. println() prints the string “Hello World” on the
screen/monitor.

Compiling and Running Java program

Java compiler first converts the source code into an intermediate code,
known as bytecode or virtual machine code. To run the bytecode, we need
the Java Virtual Machie (JVM). JVM exists only inside the computer memory
and runs on top of the Operating System. The bytecode is not machine
specific. The Java interpreter converts the bytecode into Machine code. The
following diagram illustrates the process of compiling and running Java
programs.

For compiling the program, the Java compiler javac is run, specifying the
name of the source file on the command line as depicted here:

javac [Link]

The Java compiler creates a file called [Link] containing the bytecode
version of the program. The java interpreter in JVM executes the instructions
contained in

5|O O P S - U N I T - I

[Link] IT SEM21
this intermediate Java bytecode version of the program. The
Java interpreter is called with “java” at the command prompt.

C:\> java Start

Output:

Hello World

Here java command calls the Java interpreter which executes the
[Link] (bytecode of [Link]).

 Elements or Tokens in Java Programs

Java program contains different types of elements like white


spaces, comments and tokens. A token is the smallest program
element which is recognized by the compiler and which treats
them as defined for the compiler. A program is a set of tokens
which comprise the following elements:

Identifiers or names: Identifier is the name of variables, methods,


classes etc.

Rules for framing Names or Identifiers.

• It should be a single word which contains alphabets a to z or A


to Z, digits 0 to 9, underscore (_).
• It should not contain white spaces and special symbols.
• It should not be a keyword of Java.
• It should not be Boolean literal, that is, true or false.
• It should not be null literal.
• It should not start with a digit but it can start with an underscore.
• It can comprise one or more unicode characters which are characters as
well as digits.

Conventions for Writing Names


• Names of packages are completely in lower-case letters
such as mypackage, [Link].
• Names of classes and interfaces start with an upper-case letter.
• Names of methods start with a lower-case character.
• Names of variables should start with a lower-case character.

Keywords: These are special words defined in Java and


represent a set of instructions.
• The keywords represent groups of instructions for the compiler.
• These are special tokens that have a predefined meaning
and their use is restricted.
• keywords cannot be used as names of variables, methods, classes, or
packages.
• These are written in the lower case.
• Keywords of Java Language are as follows:

Literals: These are values represented by a set of character, digits, etc.


• A literal represents a value which may be of primitive type,
String type, or null type.
• The value may be a number (either whole or decimal
point number) or a sequence of characters which is
called String literal, Boolean type, etc.
• A literal is a constant value.
Types of Literals:
1. Integer literals
• Sequences of digits.
• The whole numbers are described by different number systems
such as decimal numbers, hexadecimal numbers, octal
numbers, and binary numbers.
• Each number has a different set of digits.
Decimal Integer Literals
• These are sequences of decimal digits which are 0, 1, 2, 3, 4, 5, 6,
7, 8, and 9.
• Examples of such literals are 6, 453, 34789, etc.
Hex Integral Literals
• These are sequences of hexadecimal digits which are 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F.
• The values 10 to 15 are represented by A, B, C, D, E, and F or
a, b, c, d, e, and f.
• The numbers are preceded by 0x or 0X. Examples are 0x56ab
o0X6AF2, etc.
Octal Integer Literals
• These are sequences of octal digits which are 0, 1, 2, 3, 4, 5, 6, and
7.
• These numbers are preceded by 0. Examples of literals are 07122,
04, 043526.
Binary Literal
• These are sequences of binary digits.
• Binary numbers have only two digits—0 and 1 and a base 2.
• Examples of such literals are 0b0111001, 0b101, 0b1000, etc.

• Floating point literal


• These are floating decimal point numbers or fractional
decimal numbers with base 10. Examples are 3.14159,
567.78, etc.

2. Boolean literal
• These are Boolean values. There are only two values—true or false.
3. Character literal
• These are the values in characters.
• Characters are represented in single quotes such as ‘A’, ‘H’, ‘k’, and so
on.

4. String literal
• These are strings of characters in double quotes.
Examples are “Delhi”, “John”, “AA”, etc.

5. Null literal
• There is only one value of Null Literal, that is, null.

Separators: These include comma, semicolon, period(.),


Parenthesis (), Square brackets [], etc
Operators: Operators are mostly represented by symbols such as +, -, *,
etc

Types of Operators:

Arithmetic Operators:
Operator Description
+ Addition or Unary plus
- Subtraction or Unary minus
* Multiplication
/ Division
% Modulus

Relational Operators:
Operator Description
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to

Logical Operators:
Operator Description
&& Greater than
|| Greater than or equal to
! Less than

Assignment Operators:
Operator Description
+= Add and assign to
-= Subtract and assign to
*= Multiply and assign to
/= Divide and assign to
%= Modulus and assign to

Increment / Decrement Operators:


Operator Description
++ Increment by one
-- Decrement by one
Bitwise Operators:
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise compliment
>> Shift Right
<< Shift Left
>>> Shift right with Zero fill

Conditional Operators:
Operator Description
?: Used to construct Conditional expression

 Java Statements
A Statement is a instruction to the computer. A program is a set
of statements or instructions. The statements specify the
sequence of actions to be performed when some method or
constructor is invoked. The statements are executed in the
sequence in the specified order. The important Java statements
are as follows.

Statement Description
Empty statement These are used during program development.
Variable It defines a variable that can be used to store the
declaration values.
statement
Labeled statement A block of statements is given a label. The
labels should not be keywords, previously used
labels, or already declared
local variables.
Expression Most of the statements come under this
statement category. There are seven types of expression
statements that include
assignment, method call and allocation, pre-
increment, post increment, pre-decrement, and
post decrement statements.
Control statement This comprises selection, iteration, and jump
statements.
Selection In these statements, one of the various control
statement flows is selected when a certain condition
expression is true. There are three types of
selection statements including if, if-else,
and switch.
Iteration statement These involve the use of loops until some
condition for the
termination of loop is satisfied. There are three
types of iteration statements that make use of
while, do, and for
Jump statement In these statements, the control is transferred
to the beginning or end of the current block or
to a labeled statement. There are four types of
Jump statements including
break, continue, return, and throw.
Synchronization These are used with multi-threading
statement
Guarding These are used to carry out the code safely that
statement may cause exceptions (such as division by zero,
and so on). These
statements make use of try and catch block, and
finally
 Command Line Arguments
• A Java application can accept any number of arguments from the command
line.
• These arguments can be passed at the time of running the
program. This enables a programmer to check the behavior of a
program for different values of inputs.
• When a Java application is invoked, the runtime system passes
the command line arguments to the application's main method
through an array of strings.
• It must be noted that the number of arguments
• ​
• in an array. To ensure this, we can make use of the length property
of the array. This is illustrated in

Program 2.2: Example showing command line argument

class vehicle
public static void main(String args[])
{
int x = [Link];
for(int i=0; i<x; i++)
{
[Link](args[i]);
}
}
Output

(After compiling, type the following lines on the command prompt. It produces
the output as)

C:\> Java vehicle “Car Cycle Motorbike"


Car
Cycle
Motorbike
Program 2.3: Illustration of command line

class Sum
{
public static void main{String args)

int s=1;

for(int i e; icargs length; 1++){

s=s+[Link](args(1]);

[Link](" The addition of passed arguments 15" );

Output

After compiling, the following lines are typed on the command


prompt: It produces the output as

C:\> Java Sun 20 15 17

Declaration of Variables

• A program may involve variables: variables are objects whose values


may change in the program.
• A variable is declared by first writing its type, followed by its
name or identifier as illustrated here.

• However, a variable should also be initialized, that is, a value


should be assigned to it before it is used in an expression. The line
ends with a semicolon (:) as shown in the above figure.

Examples:

double price = 28.5;


char ch = "C":
String name - "John";
Program 2.4 illustrates the declaration and output of some data types

class PrintOut
{
public static void main (String args[])
{
String name = "Sunita"; //"name" is variable, value is "Sunita"
String str = "Hello"; //String set has value- "Hello!"

int length = 50; // Variable name "length", value 50


int width = 8; // Variable name "width" value 8

[Link]("Name= " + name);


[Link]("Str = "+ str); //print statement

System. [Link]();

[Link]("Length "+ length);


System. [Link]("Width " + width);

[Link](str + name); // println statement


}
}

c:\>javac [Link]

c:\>java PrintOut
Name= SunitaStr = Hello
Length 50
Width 8
HelloSunita

 User Input to Programs

• The class Scanner of package [Link] to carry out input to the program.
• Java Scanner class is a text scanner that breaks the input into
tokens using a delimiter. The delimiter is whitespace by default.
• Importing the class is the first step.
import [Link];
• The object of the class Scanner is declared as follows.
Scanner scaninput = new Scanner (System. in);
• The object “scaninput” invokes the method nextInt() which reads
the value typed by the user. This value is assigned to n. The value of
m is similarly obtained.
• The other useful methods of Scanner class are nextDouble() and nextLine().
Program 2.6: Illustration of a user's input from keyboard into
program

import [Link];
public class Arithmetic
{
public static void main(String[] args)
{
Scanner scaninput = new Scanner (System. in);
int n;
int m;
[Link]. print( "Enter the value of n : ");
n=[Link]();
[Link]. print( "Enter the value of m : ");
m=[Link]();

[Link]("Sum of two numbers is ="+(n+m));

[Link]("Product of two numbers is ="+ n*m);

[Link]("Modulus of (n % m) is =" + n%m);

[Link]("Division of two numbers is =" + n /m );


}
}

Output
C:\>javac [Link]

C:\>java Arithmetic
Enter the value of n : 10
Enter the value of m : 3
Sum of two numbers is =13
Product of two numbers is =30
Modulus of (n % m) is =1
Division of two numbers is =3

C:\>
 Escape Sequences
Escape Sequences character is preceded by a backslash (\)has a
special meaning to the compiler. Escape sequences are as follows.

Program 2.9: Program on Escape Sequences

class Escape
{
public static void main(String[] args)
{
int n=256, a=0, b=70;
[Link]("Value of a =" + a + "\n b= "+b +"\n");
[Link]("\u0041 \t" + " \u0042 \t"+"\132");
[Link]("\"Value of b\" = "+b);
[Link]("\'Value of n\' = " +n);
}
}

Output:

C:\>javac [Link]

C:\>java Escape
Value of a =0
b= 70
A B Z
"Value of b" = 70
'Value of n' = 256
 Comments
• Comments are Line of Text which is not a part of the compiled
program.
• Comments are used for documentation to explain source code.
• They are added to the source code of the program.
• Java supports three types of comments as:
1. Single-line comment: These comments are started with
two front slash characters (//)
Example:
// This is Single line comment

2. Multi-line comment : These comments are enclosed


with /* and */ Example:
/* It is Multi
line
Comments
*/

3. Documentation comment: These comments are enclosed


with /** and */. It is different from multi line comments in
that it can extracted by javadoc utility to generate an HTML
document for the program.
Example:
/** It is
documentation
Comments */

 Programming Style.

• An analysis of the programming exercises will throw some light on the


look and feel of a program. The team members should easily
understand each other's code.
• For a beginner, it is better to develop a habit of writing a program in a
proper style so that there is no conflict between the current habits and
the company's imposition of style rule at a later stage.
• There are no set patterns of good style and bad style: however, if the
programmer takes care of a few requirements on the programs as
discussed, the resulting style will be better

1. The program should present a clean and orderly look. In order to


develop a clean program, the programmer can adapt the following
measures:
 The white spaces are neglected by the compiler.

 Indenting is another method often used to improve the looks and readability

 Use of Lambda expression and method reference of Java 8 enhances the look

 Include a space before and after operators

 The program should be easy to understand. The programmer should take care
of the following aspects:

 If it is team work, certain conventions about naming should be


preset so that a team member can easily identify an item.

 The makers of Java have a set of rules which are followed in the Java
library. The same rules or an even better convention may be set.

 Judicial use of comments can increase understandability. Use of too


many comments makes confusion in the program.

 It is better to use already defined and tested library methods


rather than user-defined methods

 Expressions like z = x++ + - - c*++k; should be avoided.

2. Debugging should be easy. The programmer may adopt the following


measures to ensure easy debugging.

 The vertical alignment of a similar item enhances the ability to find errors.

 The code line should not be too long.

 The variables should be declared close to the places of their use

 If it is a big program, it should be divided into small segments. In Java, it


is easy because the program may comprise separate classes.

 The methods should not be too big.

 Each source code file should have one class.


 The braces should be vertically aligned, if possible.

4. The program should be easy to use. The following points

• The input into program should be easy,

• The output should be self-explanatory should be taken care of

• The names used should imply the output type such as price, weight, length,
and so on.

• Confusing and long names must be avoided.


5. The program should be easy to maintain

• The program should be easily modifiable to ensure simplicity in fixing errors.

• The comments can help in modification of the program, fixing errors.

6. The program should be fail-safe. The failure of a program should not


be catastrophic.
7. Data Types Variables and Operators :

i. Introduction Data Types in Java

The Java language programs deal with the following entities:

I. Primitive data

1. Classes and objects

2. Interfaces and their references

3. Arrays

4. Methods

The primitive data and their types are defined independent of the classes
and interfaces, and the arrays and methods derive their types from the
first three entities.

An array is n collection of items that may be of primitive type, class


objects, or references. The type of an array can be determined from the
type of elements present in it.

Data Types in Java

• Data Type is the type of the data which computer accepts. Every
variable and expression has a data type that is known at the compile
time.
• The declaration of data type with a variable or expression limits the
types of values that a variable can have or the expression it can
evaluate.
• Java is an object-oriented programming language based on classes and
interfaces.
• Java defines some primitive (basic) data types that are not reference
types of any class or interface. Eight primitive (basic) types of data are
defined in Java. The type names are also the keywords shown here in
bold letters
• Integral types—byte, short, int, long
• Floating point types - float, double
• Character type -char
• Boolean type – Boolean values – True, False

There is a non-data type called void and no data can be of type void.
This type is used for methods that do not return any value.

Java is a case-sensitive language. This means that it takes Area, area, and
AREA are three different objects.

Declaration of Variables - Data Types


A variable is declared by first declaring its type followed by its identifier or
name, which is given as follows:

type Identifier;

Here type is the primitive data type and Identifier is the name of the

variable. Declaration and Initialization of the variable is as follows.

type identifier = value;

Ex:

byte n; // declares a variable of type byte.

short m = 67; // declares and initiates a

short number int length; //declares

length-a variable of type int length - 50; //

value is re-assigned after declaration char

ch = ‘A’; // declares a character variable

ch.

Non-primitive Types

These are the class and interface types. The name of a class or interface
is the name of type. A class object is declared as

Class_identifier object_identifier;

Similarly, an interface reference is declared as

Interface_identifier reference_identifier;
Example:

String str "Delhi":

Data Types

 Integers

Integers are whole numbers, that is, they represent numbers that do not
have a fractional part. The integers can be declared in four types
according to the size of memory allocated for them

Program 3.1 illustrates the integer data types.

class DataType
{
public static void main (String args[])
{
byte a= 4, b=8 ;// variables of type byte
short c = 67, d = 98; // variables of type short
int e = 7000, f = 20000; // variables of type int
long secondsInYear = 365 * 24 * 60 * 60; // long type
//e=d+f;
[Link]("(b + a) = " + (b+a));
[Link]("b + a = " + b + a);
[Link]("c = "+ c + " \td = " + d);
[Link]("e = " + e + "\t f= " + f);
[Link]("Seconds in a year = "+ secondsInYear);
}
}
Output:

C:\ >javac [Link]


C:\ >java DataType
(b + a) = 12
b + a = 84
c = 67 d = 98
e = 7000 f= 20000
Seconds in a year = 31536000

 Characters
• A variable may have value in terms of a character in which the type of
variable is char.
• These characters represent integer values.
• Java supports Unicode for the representation of characters.
• Unicode supports all the character sets of all the major languages of the
world.
• The initial version of Unicode allocated 2 bytes for storing characters.
• The range of values for characters in the initial version of Unicode
comprised from ‘\u0000’ to ‘\uffff ’ that is from 0 to 65535 both
end values inclusive.
• Program 3 2 illustrates anthmetic operations on character
constants and variables

class Datachar {
public static void main (String args[])
{
char ch1='E', ch2, ch3 ;

[Link]("ch1 =" +ch1); // printing ch1

ch2=ch1++;
[Link]("ch2 =" + ch2); // printing ch2

ch3=++ch1;
[Link]("ch3 =" + ch3); // printing ch3
}
}
Output:
C:\ >javac [Link]
C:\ >java Datachar
ch1 =E
ch2 =E
ch3 =G
 Floating Point Numbers

• The numbers that are not whole numbers, or those that have
fractional part, Examples are 3.141, 476.6, and so on.
• Java supports two types of such numbers.
Float: This type is used for single-precision decimal floating point
numbers, that is, 7 digits after the decimal point. These numbers are
stored on 4 bytes.

Program 3.4: Illustration for working with float and double data
class FloatType
{
public static void main (String args[])
{
float width =20.0f, length = 40.5f;
float rectArea = length * width;

[Link]("Width = "+ width);


[Link]("Length = "+ length);
[Link]("Rectangle Area = "+ rectArea);

double dia=10.0, pi=3.14159;


double areaCircle = pi* dia * dia / 4;

[Link]("Diameter " + dia);


[Link]("Area of Circle = " + areaCircle);
}
}
Output

C:\>javac [Link]
C:\>java FloatType
Width = 20.0
Length = 40.5
Rectangle Area = 810.0
Diameter 10.0
Area of Circle = 78.53975

 Boolean Type - Data

• For dealing with logical statements, variable of type boolean is supported.


• The value of boolean type variable is either true or false.
• The boolean type variables are unsigned as similar to char type variables.
• The variable may be declared as follows :
boolean
a; a = x
> y;

If the aforementioned logical statement is correct, The value of a is true,


otherwise the value of a is false. In Java true and false are not
converted into numerical values, which is the case in other Languages. A
boolean type variable is allocated to one byte, that is, 8 bits for storing its
values Program

3.5 illustrates the application of boolean type variables,

class Boolean
{
public static void main (String args[])
{
double x= 5.5, y=10.5, p=4.0;
int n=40, m=50;
boolean a,b,c,d;

a= x>y;
b= y>p;
c= y==x;
d= x<=y;

[Link]("a = " + a +" and b =" +b);


[Link]("Now c= "+c+ " and d = "+d);
}
}

C:\>javac [Link]

C:\>java Boolean
a = false and b =true
Now c= false and d = true
o Type Casting
Converting one data type to another data type is called as Type Casting.
There are two types of type casting. They are,

o.a Implicit Type casting


o.b Explicit Type casting
1. Implicit Type casting
Implicit type casting is done automatically by a compiler when we assign
a value to the variable.
Example:
int
a=10;
double
b;
b=a;
Here a is integer and d is double variables. Integer value is
automatically converted into double by the compiler.

2. Explicit Type casting


The explicit type casting is carried out by the
following code: type variable = (new_type)
variable;

• It is illustrated by the following

code lines: double D = 6.865;

int A = (int) D;

• In such a conversion, there is loss of data

Program 3.7: Illustration of type casting.


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

int a=4, b = 8, c = 9, d,e;


double x= 3.0, y=6.5, z,k;

d=c/a;
k=a+y;
e = a + (int)y;
z=(double)c/a;

[Link]("k = " + k +" and e =" +e);


[Link]("d= "+ d + " and z = "+ z);
}
}
Output

C:\ >javac [Link]

C:\ >java TypeCast


k = 10.5 and e =10
d= 2 and z = 2.25

p Scope of Variable Identifier


The scope and lifetime of a variable is the part of the program in which it
is visible and holds the last entered value In Java, there are distinctly two
types of scopes.
1) class scope and
2) method scope
 A variable declared in a class has class scope and scope of a
variable declared in a method has method scope.
 The variables declared in a block have block scope.
 Thus, the variables defined in main() at the beginning have scope in
entire main() method, however, those defined in a block have block
scope.
 A block starts with the left brace ( { ) and ends with the right brace ( } ).
In the case of nested blocks of statements, the scope of variables is
governed by the following rules.

1. The scope starts from the point the variable is defined in the block
(declared and value assigned to it).

2. Although the variable may be defined anywhere in a block, it can be


used only in the statements appear ing after its definition Therefore,
there is no use in defining a variable at the end of block.

If there are nested blocks, a variable defined in the outer block is visible in
the inner blocks also and it cannot be redefined with the same name in
the inner blocks

Program 3.10: Illustration of block scope

public class ScopeA


{
static int x = 5; // Variable scope within the Class
public static void main (String args[])
{
[Link]("Class Scope variable - outside main() x = " + x);
int y = 10;
[Link]("Variable y Scope within main() y = " + y);
{ // Anonymous Block
int z = 20;
[Link]("Variable z Scope within Anonymous Block z = " + z);
}
}
}
:\>javac [Link]

E:\>java ScopeA
Class Scope variable - outside main() x = 5
Variable y Scope within main() y = 10
Variable z Scope within Anonymous Block z = 20

E:\>java ScopeA

q Literal Constants, Symbolic Constants

q.a Literal Constants

Literal Constants are as follows.


1. Each character is a constant value.
2. An array of characters or a string also represents a constant value.
3. The digits in decimal system, octal system, or hexadecimal system
represent constant values.
4. The char literals are enclosed in single quotes (‘ ’). The examples ‘A’
and ‘B’. These may also be written as \u0041 and \u0042.
5. The string literals are enclosed in
double quotes. Examples : "Delhi”, "I
am going out."
6. The decimal integral literals examples are 5417, 684
7. The octal number literals are prefixed with 0 (Zero). Example. 072 , 042
8. The floating point literal examples are 684.62f, 5.245E+ 2f
9. The literal of Boolean data type are true and false. In Java, neither
true is converted to 1 nor

q.b Symbolic Constants

A Symbolic constant is a variable whose value does not change


throughout the program. Some of the examples include PL NORTH,
EAST etc.

It is usually preferred to declare the symbolic constants using all the


capital letters in a program as follows:

public static final int c =299792458;


public static final double PI = 3.21415;
Program 3.13 illustrates the use of symbolic constant

public class SymbolicConst


{
public static final double PI = 3.1415926535;
public static void main (String args[])
{
double r = 25.0, perimeter;
perimeter = 2*PI*r;
[Link]("radius=" + r);
[Link]("Perimeter of circle = " + perimeter);
}
}

C:\>javac [Link]

C:\>java SymbolicConst
radius=25.0
Perimeter of circle = 157.079632675

1. Formatted Output with printf() Method

In Java, the formatting of output may be carried out in two ways:

(a) By using class Formatter 2. By method printf()

• The Formatter class is used to format the output.


• The printf() method is easy and simple to use, and hence, it is mote
popular than other methods.
• The following formatting objectives may be realized by using print method
• Right and left justification
• Precision of floating point numbers by regulating the number
of digits after the decimal point
• Aligning a number of numbers in a column
• Controlling the placement of characters and strings at desired locations
• Representing integers in octal and hexadecimal systems
• Representing floating point numbers in exponential form or regular form
• Representing the time and date in

different formats. The syntax of the method

printf () method is as follows

[Link]("Formatting string" variables separated by comma);

• The formatting string specifics the output format for each


variable that consists of percent (%) sign followed by a
conversion letter.
• Thus, the format string for output of an integer and
character is "X" and or respectively.
• The order of variables in variable list should match with the
list of formats in formatting string.
• The following Table lists the conversion letters for different types of
variables.

Program 3.14: illustration of formatting strings for output of different types of


variables

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

int n = 713;
float x = 45.86f;
double d= 56.754;

String str = "Delhi";


char ch = 'A';
[Link]( "%d %f %f %c \t %s \n", n, x, d,ch,
str);

//for conversion into hexadecimal number


[Link]("Hexadecimal value of 163 = %X \n", 163);

//for conversion into octal


[Link]("Octal value of 163 = %o\n", 163);
}
}
Output

C:\>javac [Link]

C:\>java FormatPrintf
713 45.860001 56.754000 A Delhi
Hexadecimal value of 163 = A3
Octal value of 163 = 243

2. Static Variables and Methods

Static Variables:
a) The static variables are class variables. Only one copy of such
variables is kept in the memory and all the objects share that
copy.
b) The static variables are accessed through class reference,
whereas the instance variables are accessed through class
object reference
c) The variables in a class may be modified by modifier static.
d) The non-static variables declared in a class are instance variables Each
object of the class keeps a copy of the values of these variables.
Static Methods:
e) The static methods are similar to class methods and can be invoked
without any reference of object of class, however, class reference
(name of class) is needed, as in the following example The method
like sart() is declared as static method in Math class and is called

[Link](5); // Finds square root of 5

The static method is called using the method name that is preceded by
the class name; in this case. Math and period ().

Program 3.18: illustration of using static methods of class Math

public class StaticMethods


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

[Link]("The Square root root of 16 = "+ [Link](16));


[Link]("The cubroot root of 27 = "+ [Link](27));
//printing five random variables
for(int i =1; i<=5;i++)
[Link]("Random Number " + i + " = " +
(int)(100 *[Link]()));
}
}
E:\>javac [Link]

E:\>java StaticMethods
The Square root root of 16 = 4.0
The cubroot root of 27 = 3.0
Random Number 1 = 77
Random Number 2 = 69
Random Number 3 = 83
Random Number 4 = 2
Random Number 5 = 66

E:\>java StaticMethods
The Square root root of 16 = 4.0
The cubroot root of 27 = 3.0
Random Number 1 = 67
Random Number 2 = 31
Random Number 3 = 10
Random Number 4 = 13
Random Number 5 = 40

3. Attribute Final

Final Variable:
The value of a variable declared final cannot be changed in the
program. It makes the variable a constant. A few examples of
declarations are as follows:

final double PI = 3.14159; // The value of PI cannot be changed in its scope

final int M = 900; // The value of M cannot be changed in its scope

final double X = 7.5643; // The value of x cannot be changed in its scope.

a) As mentioned in the comments, the values of PI, M, and x cannot


be changed in their respective scopes.

Final Method:

b) The attribute final may be used for methods as well as for classes.
These are basically connected with inheritance of classes.
c) When final keyword is used with Java method, it becomes the final method.
d) A final method cannot be overridden in a sub-class.

Final Class:

e) A Java class with final modifier is called final class A final class cannot
be sub-classed or inherited. Several classes in Java are final including
String, Integer, and other wrapper classes.
f) There are certain important points to be noted when using final keyword in
Java
• New value cannot be reassigned to a variable defined as final in Java.
• Final keyword can be applied to a member variable, local variable,
method, or class.
• Final member variable must be initialized at the time of declaration.
• Final method cannot be overridden in Java
• Final class cannot be inheritable in Java
• Final is different from finally keyword, which is used on Exception handling
in Java

Example- 1:
public class Final
{
public static void main (String args[])
{

int n =10; // Normal variable


final int f = 20; // final variable

[Link]("n = "+ n);


[Link]("f = "+ f);

n = 50; // Now the value 50 is assigned to variable n


f = 60; // Error : f is final variable can not be changed
}
}

Output:
C:\>javac [Link]
[Link]: error: cannot assign a value to final variable f
f = 60; // Error : f is final variable can not be changed
^
1 error
C:\>

Example-2:

public class Final


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

int n =10; // Normal variable


final int f = 20; // final variable

[Link]("n = "+ n);


[Link]("f = "+ f);

n = 50; // Now the value 50 is assigned to variable n


[Link]("n = "+ n);
}
}
C:\>javac [Link]

C:\>java Final
n = 10
f = 20
n = 50
4. Introduction to Operators
An operator is a symbol that tells the computer to perform certain
mathematical and logical calculations.
-The different types of Java operators are,
(a) Arithmetic operators
(b) Relational operators
(c) Logical operators
(d) Increment or decrement operators
(e) Assignment operators
(f) Conditional operators
(g) Bitwise operators
(h) Special operators

5. Precedence and Associativity of Operators


If the expression contains several operators with the same precedence
level, the expression is evaluated according to its associativity.
For example, in
Z = 6*4%5;
Both the operators * and % have same precedence level.
6. Assignment Operator ( = )
Assignment operators:
-Assignment operators are used to assign the result of an expression to a
variable.
Operator Meaning
= Assignmen
t
-In addition, java has a set of short-hand assignment operators of the form
V OP=EXP;
- It is equivalent to
V=V OP EXP;
-The short-hand assignment operators are
+= , -= , *= , /= , %=
Example:
a+=b ---------- a=a+b
a-=b a=a-b
a*= b --------- a=a*b
a/=b----------- a=a/b
a%=b --------- a=a%b

7. Basic Arithmetic Operators


Operator Meaning
+ Addition or Unary plus
- Subtraction or Unary
minus
* Multiplication
/ Division
% Modulo division
-Integer division truncates any fractional part.
-The modulo division produces the remainder of an integer
division. Examples: a+b, a-b, a*b, a/b, a%b

Arithmetic Expression Types:


Integer arithmetic expression:
-An arithmetic operation involving only integer operands is called
integer arithmetic. int + int = int
int - int =
int int * int
= int
int / int = int (truncates
decimal part) int % int = int
(results remainder) Real
arithmetic expression:
- An arithmetic operation involving only real operands is called
real arithmetic. real + real = real
real - real =
real real *
real = real
real / real =
real
real % real = not allowed

Mixed-mode arithmetic expression:


-An arithmetic operation involving one operand is real and the other
operand is integer, then it is called mixed-mode arithmetic.
real+int=r
eal real-
int=real
real*int=r
eal
real/int=r
eal
real%int=
not
allowed

8. Increment (++) and Decrement (- -) Operators


-The increment operator is ++ which means +1
-The decrement operator is - - which means -1
-The operand must be either incremented or
decremented by 1. Example:
m=5;y=++m; results m=6 and y=6.
m=5;y=m++; results m=6 and y=5.
m=5;y= --m; results m=4 and y=4.
m=5;y=m--; results m=4 and y=5.

9. Ternary Operator or Conditional operators:


-It is also known as Ternary operator.
-The symbols used to construct a conditional expression are ? and :
-A conditional expression is of the form,
exp1?exp2:exp3;
Example:
(a>b)?[Link](“a is greater”): [Link] (“b is greater”);
- It is equivalent to if-else statement in java

Example:
if(a>b)
[Link](“a is
greater”); else
[Link] (“b is greater”);

10. Relational Operators


-The comparison between two operands or expressions is done with the
help of relational operators.
Operator Meaning
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equality
!= Inequality
Example:
a>b
a>=b
a<b
a<=b
a==b
a!=b
11. Boolean Logical Operators
-The java language has three logical operators.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
-The logical operators &&, || are used when we we want to test more
than one condition. && - used when all the conditions must be true.
|| - used when any of the conditions must be true.

-A logical expression yield a value 0 or 1, according to the truth table.


Operand Operand Operand1&&operan Operand1||opera
1 2 d2 nd2
Non- Non-zero 1 1
zero
Non- 0 0 1
zero
0 Non-zero 0 1
0 0 0 0
Example:
(a>b)&&(a>c)
(a>b)||(a>c)
-The logical not is used as a negation or complement of the
expression. Example:
!(y<10) means (y>=10)

12. Bitwise Logical Operators.


Bitwise operators:
-‘C’ provides bitwise operators that operate on data at the bit-level.
-Bitwise operators interpret operands as string of bits.
-These bit strings are then interpreted according to data type.

-Bitwise operators are of 2 types.


(a) Logical bitwise operators.
(b) Shift bitwise operators.
(a) Bitwise Logical operators

Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
Bitwise AND operator:
-The Bitwise AND (&) is a binary operator that requires two integral
operands(character or integer).
-It does a bit-by-bit comparison between two operands.
-The result of the comparison is 1 only when both bits are 1, otherwise it is
0.
First operand Second operand Result(&)
bit bit
0 0 0
0 1 0
1 0 0
1 1 1
Bitwise OR operator:
-The Bitwise inclusive OR (|) is a binary operator that requires
two integral operands(character or integer).
-It does a bit-by-bit comparison between two operands.
-The result of the comparison is 0 only when both bits are 0, otherwise it is
1.

First operand Second operand Result( |


bit bit )
0 0 0
0 1 1
1 0 1
1 1 1

Bitwise exclusive OR:


-The Bitwise exclusive OR (^)is a binary operator that requires
two integral operands(character or integer).
-It does a bit-by-bit comparison between two operands.
-The result of the comparison is 1 only if one of the operands is 1, otherwise
it is 0.
First operand Second operand Result(^)
bit bit
0 0 0
0 1 1
1 0 1
1 1 0
One’s complement:
-The one’s complement (~) is a unary operator applied to an integral value.
-The result is 1 when the original bit is 0 and it is 0 when the original bit is 1.
Original bit Result( ~ )
0 1
1 0

(b) ​Shift Bitwise operators:


-The shift Bitwise operators move bits to the right or left.
Operator Meaning
>> Bitwise shift right
<< Bitwise shift left
>>> Shift right with zero fill
Bitwise shift-right operator:
-It moves some number of bits from right to left.
-It requires two integral
operands. Syntax:
Operand1 >> Operand2;
-Here, Operand1 is value to be shifted.
Operand2 is number of bits to be shifted.
Bitwise shift-left operator:
-It moves some number of bits from left to right.
-It requires two integral
operands. Syntax:
Operand1 << Operand2;
-Here, Operand1 is value to be shifted.
Operand2 is number of bits to be shifted.

Special Operators.
(a) Java supports some special operators such as,
• instanceof operator
• member selection operator
(a) ​instanceof operator:
(b) The instanceof is an object reference operator and returns true if the
object on the left-hand side is an instance of the class given on the right
hand side.
(c) This operator allows us to determine whether the object belongs to a
particular class or not. Example:
person instanceof student
(d) It is true if the object person belongs to the class student, otherwise it is
false.

(b) ​member selection operator:


(e) The dot (.) operator is used to access the instance variables and
methods of class objects. Example:
[Link] // Reference to the variable
age [Link]( ) // Reference to the
method salary( )
(f) It is also used to access classes and sub packages from a package.
1. Control Statements:

• Introduction
CONTROL STATEMENTS: (FLOW OF CONTROL)
- A Control statement is a statement used to control the flow of execution in a
Java Program.

SELECTION STATEMENTS:
-Also called as conditional or decision-making control statements.
-There are two types in Selection control statements.
[Link]-way selection control statements
2. Multi-way selection control statements
• ​Two-way selection control statements:
-The different two-way selection statements are,
• if-else statement
• null else statement
• Nested-if statement

• if Expression - also called as “ null else statement ”

Syntax:
if(condition)
{
statements;
}
next statement;

Example:
if(a==2)
{
p++;
}
[Link](“program over”);
• Nested if Expressions
-if within if is called as
Nested-if. Syntax:
if(condition-1)
{
if(condition-2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
if(condition-3)
{
Statement-3;
}
else
{
Statement-4;
}
}
next statement;

Example:

if(a>b)
{
if(a>c)
{
[Link](“a is greater”);
}
else
{
[Link] (“c is greater”);
}
}
else
{
if(b>c)
{
}
}
else
{

}
[Link]
.println(“ [Link](“c is greater”);
b is
greater”); if–else Expressions Syntax: if(condition)
{

true-block statements;
}
else
{
false-block statements;
}
next statement;

Example: [Link](“a is greater”);


if(a>b)
{

} [Link](“b is greater”);
else
{

b else-if ladder statement:


Syntax:
if(condition-1)
{
Statement-1;
}
else if(condition-2)
{
Statement-2;
}
…………………
……………..…..
else if(condition n-1)
{
Statement-(n-1);
}
else
{
Statement-n;
}
next statement;
Example:
if(a>b&&a>c&&a>d)
{
[Link](“a is greater”);
}
else if(b>a&&b>c&&b>d)
{
[Link](“b is greater”);
}
else if(c>a&&c>b&&c>d)
{
[Link](“c is greater”);
}
else
{
[Link](“d is greater”);
}

• Ternary Operator?:
In Java, the ternary operator is a type of Java conditional
operator. The meaning of ternary is composed of three parts.
The ternary operator (? :) consists of three operands. It is used to
evaluate Boolean expressions. The operator decides which value will be
assigned to the variable. It is the only conditional operator that accepts
three operands.
It can be used instead of the if-else statement. It makes the code much
more easy, readable, and shorter.

Syntax:
Expression1 ? Expression2 : Expression3

1. The first expression is the test condition.


2. If it evaluates true, the Expression2 is executed; otherwise
Expession3 is executed.

Example-1:

public class Ternary


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

int a=10;
int b = (a<20)? 100 :200; // a < 20 if statement
[Link]("b= "+b);
}
}
Output:
C:\>javac [Link]

C:\>java Ternary
b= 100
Example-2:

public class Ternary


{
public static void main (String args[])
{
int a=10;
int b = (a>20)? 100 :200; // a>20 – else statement
[Link]("b= "+b);
}
}

Output:
C:\>javac [Link]

C:\>java Ternary
b= 200

• Switch Statement
Syntax:
switch(expression)
{
case value-1:statement-1;break; case
value-2:statement-2;break;
………………………….
………………………….
case value-n:statement-n;break;
default: default statement;
}
next statement;

Example:
switch(digit)
{
case 0: [Link](“ZERO”);break;
case 1: [Link](“ONE”);break;
case 2: [Link](“TWO”);break;
case 3: [Link](“THREE”);break;
case 4: [Link](“FOUR”);break;
case 5: [Link](“FIVE”);break;
case 6: [Link](“SIX”);break;
case 7: [Link](“SEVEN”);break;
case 8: [Link](“EIGHT”);break;
case 9: [Link](“NINE”);break;
default: [Link](“Enter between 0-9”);
}
• Iteration Statements
LOOP STATEMENTS:
-The iteration control statements are also called as Repetition or Iteration
control statements.
-A looping process includes the following four
steps.
-Setting and initialization of a counter.
-Execution of the statements in the loop body.
-Test for a specified condition (loop control expression) for execution of a
loop
-Incrementing or Decrementing counter.
• ​Pretest and Posttest loops:
-In a Pretest loop, the condition is checked before we execute a loop body.
-It is also called as entry-controlled loop.
-In the Posttest loop, we always execute the loop body atleast once.
-It is also called as exit-controlled loop.

• while Expression

a) while statement:
Syntax:
while(condition)
{
loop body;
}
next statement;

Example:
n=10,i=1,sum
=0;
while(i<=n)
{
sum=sum+i
; i++;
}
[Link](“sum=”+sum);
• do–while Loop - forLoop
Syntax:
do
{
loop body;
}while(condition);
next statement;

Example:
n=10,i=1,sum=0;
do
{
sum=sum+i;
i++;
} while(i<=n);
[Link](“sum=”+sum);

• forLoop
for statement:
Syntax:
for(initialization;condition;inc or dec)
{
loop body;
}
next statement;

Example:
n=10,i,sum=0;
for(i=1;i<=n;i+
+)
{
sum=sum+i;
}
[Link](“sum=”+sum);
• Nested for Loop
Syntax:

for(initialization;condition;inc or dec)
{

for(initialization;condition;inc or dec)
{
Inner loop body;
}

Outer loop body;


}
next statement;

Example:
n=10,i, j, sum=0;
for(i=1;i<=n;i++)
{

sum=sum+i;
}
[Link](“sum=”+sum);
• For–Each for Loop

The Java for-each loop or enhanced for loop. It provides an alternative


approach to traverse the array or collection in Java. It is mainly used to
traverse the array or collection elements. The advantage of the for-each loop is
that it eliminates the possibility of bugs and makes the code more readable. It
is known as the for-each loop because it traverses each element one by one.
Advantages:
1. Less clutter in code, especially when iterators are used.
2. Less chances of errors.
3. Improves overall readability of program.
Limitations:
1. It is designed to iterate in forward direction only.
2. In iteration, it takes a single step at a time.
3. It cannot simultaneously traverse multiple arrays or
collections. Syntax:

for (Object obj : Collection_name)


{
Body of loop
}

Example:

public class ForEach


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

int myArray[] = {10,20,30,40,50};

for (int x:myArray)


{
[Link](" "+x);
}
}
}

Output:

C:\>javac [Link]

C:\>java ForEach
10
20
30
4050
• Break Statement
Unconditional control statements:
-The unconditional control statements are,
a) break statement
b)continue statement

break statement:
-The break statement skips from the loop or block in which it is defined.
-The control then automatically goes to the first statement after the loop or
block.
-The general format is
break;
Example:

public class Break


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

//printing the values from 1 to 10


for(int i =0; i<10;i++)
{
if (i==5)
break; //Break Statement
[Link]( i );
}
}
}

Output:
C:\>javac [Link]

C:\>java Break
0
1
2
3
4

Here loop is stopped due to break statement.


• Continue Statement.
-The continue statement is used for continuing next iteration of loop statements.
-When it occurs in the loop, it does not terminate but it skips the statements
after it.
-It is useful when we want to continue the program without executing any part
of the program.
-The general format is
continue;

Example:

public class Continue


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

//printing the values from 1 to 10


for(int i =0; i<10;i++)
{
if (i==5)
continue; // Continue statement
[Link]( i );
}
}
}
Output:

C:\>javac [Link]

C:\>java Continue
0
1
2
3
4
6
7
8
9

Here 5 is not printed because of continue statement. The Iteration at the


condition i = =5 is skipped or jumped to next statement.

51

You might also like