0% found this document useful (0 votes)
14 views

Java-unit_1

jntua r23

Uploaded by

farhana.fayk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Java-unit_1

jntua r23

Uploaded by

farhana.fayk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

(23A05303T) OBJECT-ORIENTED PROGRAMMING THROUGH JAVA

Course Objectives: The learning objectives of this course are to:


❖ Identify Java language components and how they work together in applications
❖ Learn the fundamentals of object-oriented programming in Java, including defining classes, invoking
methods, using class libraries.
❖ Learn how to extend Java classes with inheritance and dynamic binding and how to use exception
handling in Java applications
❖ Understand how to design applications with threads in Java
❖ Understand how to use Java apis for program development
Course Outcomes: After completion of the course, students will be able to
❖ Analyze problems, design solutions using OOP principles, and implement them efficiently in Java. (L4)
❖ Design and implement classes to model real-world entities, with a focus on attributes, behaviors, and
relationships between objects (L4)
❖ Demonstrate an understanding of inheritance hierarchies and polymorphic behaviour, including
method overriding and dynamic method dispatch. (L3)
❖ Apply Competence in handling exceptions and errors to write robust and fault-tolerant code. (L3)
❖ Perform file input/output operations, including reading from and writing to files using Java I/O
classes, graphical user interface (GUI) programming using JavaFX. (L3)
❖ Choose appropriate data structure of Java to solve a problem (L6)
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.
UNIT II:
Classes and Objects: Introduction, Class Declaration and Modifiers, Class Members, Declaration of Class
Objects, Assigning One Object to Another, Access Control for Class Members, Accessing Private Members of
Class, Constructor Methods for Class, Overloaded Constructor Methods, Nested Classes, Final Class and
Methods, Passing Arguments by Value and by Reference, Keyword this.

Methods: Introduction, Defining Methods, Overloaded Methods, Overloaded Constructor Methods, Class
Objects as Parameters in Methods, Access Control, Recursive Methods, Nesting of Methods, Overriding
Methods, Attributes Final and Static.
UNIT III:
Arrays:Introduction, Declaration and Initialization of Arrays, Storage of Array in Computer Memory, Accessing
Elements of Arrays, Operations on Array Elements, Assigning Array to Another Array, Dynamic Change of
Array Size, Sorting of Arrays, Search for Values in Arrays, Class Arrays, Two-dimensional Arrays, Arrays of
Varying Lengths, Three-dimensional Arrays, Arrays as Vectors.

Inheritance :Introduction, Process of Inheritance, Types of Inheritances, Universal Super Class- Object Class,
Inhibiting Inheritance of Class Using Final, Access Control and Inheritance, Multilevel Inheritance, Application
of Keyword Super, Constructor Method and Inheritance, Method Overriding, Dynamic Method Dispatch,
Abstract Classes, Interfaces and Inheritance.

Interfaces :Introduction, Declaration of Interface, Implementation of Interface, Multiple Interfaces, Nested


Interfaces, Inheritance of Interfaces, Default Methods in Interfaces, Static Methods in Interface, Functional
Interfaces, Annotations.

1|Page
UNIT IV:
Packages and Java Library: Introduction, Defining Package, Importing Packages and Classes into Programs,
Path and Class Path, Access Control, Packages in Java SE, Java.lang Package and its Classes, Class Object,
Enumeration, class Math, Wrapper Classes, Auto-boxing and Auto- unboxing, Java util Classes and Interfaces,
Formatter Class, Random Class, Time Package, Class Instant (java.time.Instant), Formatting for Date/Time in
Java, Temporal Adjusters Class, Temporal Adjusters Class.

Exception Handling: Introduction, Hierarchy of Standard Exception Classes, Keywords throws and throw, try,
catch, and finally Blocks, Multiple Catch Clauses, Class Throwable, Unchecked Exceptions, Checked
Exceptions.

Java I/O and File: Java I/O API, standard I/O streams, types, Byte streams, Character streams, Scanner class,
Files in Java(Text Book 2)
UNIT V:
String Handling in Java:Introduction, Interface Char Sequence, Class String, Methods for Extracting
Characters from Strings,Comparison, Modifying, Searching; Class String Buffer.

Multithreaded Programming:Introduction, Need for Multiple Threads Multithreaded Programming for Multi-
core Processor, Thread Class, Main Thread-Creation of New Threads, Thread States, Thread Priority-
Synchronization, Deadlock and Race Situations, Inter-thread Communication - Suspending, Resuming, and
Stopping of Threads.

Java Database Connectivity: Introduction, JDBC Architecture, Installing MySQL and MySQL Connector/J,
JDBC Environment Setup, Establishing JDBC Database Connections, ResultSet Interface

Java FX GUI: Java FX Scene Builder, Java FX App Window Structure, displaying text and image, event
handling, laying out nodes in scene graph, mouse events (Text Book 3)

Text Books:
1. JAVA one step ahead, Anitha Seth, B.L.Juneja, Oxford.
2. Joy with JAVA, Fundamentals of Object Oriented Programming, DebasisSamanta, MonalisaSarma,
Cambridge, 2023.
3. JAVA 9 for Programmers, Paul Deitel, Harvey Deitel, 4th Edition, Pearson.

References Books:
1. The complete Reference Java, 11thedition, Herbert Schildt,TMH
2. Introduction to Java programming, 7th Edition, Y Daniel Liang, Pearson
Online Resources:
1. https://nptel.ac.in/courses/106/105/106105191/
2. https://infyspringboard.onwingspan.com/web/en/app/toc/lex_auth_012880464547618816347_shared/overview

2|Page
UNIT - I
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.
Introduction:
Procedure Oriented Programming (POP):
➢ The problem is viewed in a procedure oriented programming as a sequence of things
to be done such as reading, calculating and printing.
➢ A number of functions are used to perform these operations.
➢ POP divides the program into small parts called functions.
➢ In a procedure oriented programming the primary focus is on function since
everything is represented inside the function only.
Object Oriented Programming (OOP):
➢ Oops was invented to overcome the drawbacks of Pops.
➢ OOP treats data as a critical element in the program development and does not
moved freely around the system.
➢ Object oriented programming divides a problem into a number of entities called
objects.
➢ Everything is represented in the form of object in OOPs.
➢ Objects protects of its data and functions from outside objects.
➢ The data of an object can be accessed only by the functions associated with the
object
Introduction to Java
Java History:
➢ Java is a general purpose object oriented programming language developed by Sun
Microsystems of USA in 1991.
➢ Originally java was called “OAK” by James Gosling, one of the inventors of java
language.
➢ Java was developed for consumer electronic devices like TV’s, VCR’s and such other
electronic machines.
➢ The main goal of java team is developing of simple, portable and highly reliable
language.
➢ Patrick Naughton, one of the java developers team member discovered that the existing
languages(C or C++) had some limitations
➢ However they modeled their new language java by removing some of the features of C
and C++
Java used in:
✓ Desktop applications
✓ Mobile applications
✓ Enterprise applications
✓ Web applications
✓ Games and Robotics

3|Page
Features of Java (Or) Java Buzzwords
The following are most important features of Java.
1. Compiled and Interpreted. 8. High Performance.
2. Platform–Independent and Portable. 9. Dynamic and Extensible.
3. Object Oriented 10. Ease of Development
4. Robust and Secure. 11. Scalability and Performance
5. Distributed. 12. Monitoring and manageability
6. Simple Small and Familiar. 13. Desktop Client.
7. Multithreaded and Interactive.

1. Compiled and interpreted: Usually, a computer language is either complied or


interpreted. But Java is both compiled and interpreted language. The Java compiler
translates “source code” into “Byte code”, and the java interpreter translates “Byte
code” into “Machine code”.
2. Platform independent and portable: The most important feature of Java language is
“Portable”. i.e., Java programs can easily moved from one computer to another,
anywhere and anytime. Byte code instructions of java programs are executed in any
platform using JVM, hence java is platform independent.
3. Object oriented: Java is purely object oriented programming language. Because, all
the program code and data must resides with in the class.
4. Robust and Secure: Java is the Robust and Secure language. Because, It has strict
compile time and runtime checking for errors. Java also supports exception handling
to handle runtime errors.
5. Distributed: Java is designed as a distributed language to create network based
applications (Client/Server applications).
6. Familiar, Simple and Small: Java is simple and small language. Because, many
features of c & c++ are reduced in java. All over the world, many no.of persons are using
Java. So that, Java is a familiar language.
7. Multithreaded and interactive: Java supports multithreading concept. i.e., It executes
multiple threads (process) simultaneously.
8. High performance: Java is a high performance language, due to the use of “Byte code”.
By using “Byte code”, Java increases overall execution speed of program.
9. Dynamic and Extensible: Java is a dynamic language, because it is capable of dynamic
linking. Java supports native methods to extend the programs, developed in C and C++.

4|Page
Java Virtual Machine (JVM):
➢ All language compilers translate the “Source code” into “Machine code” for a specific
machine.
➢ But Java Compiler produces an intermediate code known as “Bye code” for a
specific machine called Java Virtual Machine (JVM).
➢ JVM is also called “Java interpreter”, and its functionality is converting “Byte code”
into “Machine code”.
➢ The Machine code is not machine independent. i.e., machine code is dependent.
➢ This Machine dependent code is generated by JVM.
➢ Java acts as an intermediate between “Byte code” and “Machine code”.

Java source code


Text editor Java compiler(JAVAC)

Machine code Java interpreter


Byte code (.class)
(java or JVM)

Functions of JVM:
➢ Collecting classes from API (Application Program Interface).
➢ Allocating memory to the objects.
➢ Calling methods.
➢ Calling I/O resources.
➢ Producing output.
➢ Submitting machine code to the processor.
➢ Removing memory allocated to the objects.
➢ Maintaining threads, executing constructors.
➢ Executing static methods.
Basic Concepts of OOP / Object Oriented Programming Principles
The following are the basic concepts of object oriented programming language.
1. Objects 2. Class 3. Data Abstraction 4. Encapsulation

5. Inheritance 6. Polymorphism 7. Dynamic binding 8. Message passing

1. Objects:
• Objects are the basic run time entities in an object oriented programming.
• Objects may represent a person, a place, a bank account or any item.
• Object takes memory space and has an address.
• Objects are the variables and classes are data types.
• Each object contains data and methods. By using methods, we can manipulate
data.
5|Page
Geethanjali Institute of Science and Technology: Nellore II B.Tech – CSE – I Sem

2. Classes:

• Classes are the basic building blocks of oops.


• A class is a kind of blueprint or template or internal structure of an object.
• The entire set of data and code of an object can be made with the help of a class.
• Once a class has been defined, we create number of objects belonging to that class.
• Class is a data type and object is a variable of that class.

Class Objects
Fruit Mango,banana,apple
Furniture Bench,chair,table
Bike Hero,Yamaha,Honda
vehicle Car,truck,bus

3. Data Abstraction:
• Removing of unnecessary information and representing necessary information is
called data abstraction. (or)
Hiding of unnecessary information and highlighting of necessary information is
called data abstraction.
• Classes use the concept of abstraction, and are defined with a list of data items
(variables) and methods (functions).
4. Encapsulation:
• Data encapsulation is most important feature of class.
• The process of combining data and methods (functions) in a single unit is known
as Encapsulation.
• The data of a class is accessed by only the methods of same class.
• By using encapsulation, we can accomplish data hiding.

Abstraction

6|Page
Geethanjali Institute of Science and Technology: Nellore II B.Tech – CSE – I Sem
5. Inheritance:

• The process of creating a new class from old class is called inheritance.
• Inheritance is very useful to add additional features to an existing class without
modifying it.
• The new class will have the combined features of new class and old class.
• New class is called derived class or sub class and old class is called super class
or base class.

6. Polymorphism:
• Polymorphism means the ability to take more than one form with a single name.
• “Polymorphism” comes from the ‘Greek’ word. “Poly” means “many” and
“morphism” means “forms”. i.e., many forms.
• It’s a quality that allows one name to be used in two more purposes.
• An action is depends on the type of the data.
• There are two types of polymorphisms.
1. Compile time polymorphism.
2. Run time polymorphism.

7. Dynamic binding:
• Dynamic binding means linking the code at the time of executing the program.
• It is associated with polymorphism and inheritance.
8. Message passing:
• A message for an object is nothing but request to execute a procedure.
• Message passing specifies name of the object, name of the method (message) and
the information to be sent.

7|Page
Every programming language follows certain program structure which is followed
by the programmer.

• Documentation Section: The documentation section contains set of comment lines.


Comment lines are non-executable statements they are ignored by the compiler. Java
supports 3 types of comment lines. They are
a) Single line comment--// comment line
b) Multiple line comment /* comment lines*/
c) Document comments--/** comment lines*/
• Package Statements: The first statement in a Java program is the package statement.
This statement declares the package, and informs the compiler that the classes defined
here belongs to this package.
• Import Statements: An import statement is similar to #include statement in C or C++
language. The import statement instructs the interpreter, to allocate memory for the
specified classes.
Ex: import java.lang.System;
Import java.util.*;
• Interface Statements: An interface is like a class, which includes a group of abstract
methods. This section is used to declare an interface.
• Class Definition: A Java program can contain multiple classes. In this section the
programmer may define one or more classes. The complexity of the program is depends
on the no. of classes used in the program..
• main() method Class: Every java stand-alone program requires a main() method. It is
starting point for execution. The main() method creates objects of various classes and
establishes communication between them

8|Page
Implementing of java program includes a series of steps. Thy are
1. Create a program
2. Compiling the program
3. Running the program
1. Create a program:
We can create a program using any text editor such as notepad, edit etc; assume
that we have entered the following program.
class Test
{
public static void main(String args[ ])
{
System.out.println(“Hello Java”);
}
}
The filename should be similar to the main method class name and extension is
.java. This file is called source file. So the file name is Test.java
2. Compiling the program:
Java compiler is used to compile the source of program. “javac” is the java compiler.
The following is used for compilation.
E:\> Javac Test.java
If everything is ok, the javac compiler creates a class file called “Test.class” containing
the byte codes. The compiler automatically names the bytecode as <classname>.class.
3. Running the program:
We need to use the java interpreter “java” to run a standalone program. At the
command prompt, type
E:\>java Test
Now the interpreter looks for the main( ) method in the program and begins execution
from there. It can be display the output as: Hello Java
Naming Conventions in Java
Naming conventions specify the rules to be followed in the java programmer while
writing the names of packages, classes, methods etc .
Packages can be named using the standard Java naming rules. Packages begin with
lowercase letters. This makes easy for users to
distinguish package names from class names. We
know that all class names begin with an uppercase
letter.
Example : This statement uses a fully qualified
class name Math to invoke the method sqrt( ). Note
that methods begin with lowercase letters. Every
package name must be unique. Duplicate names will
cause run-time errors.

9|Page
Naming Conventions of the Different Identifiers
The following table shows the popular conventions used for the different identifiers.
Identifiers Naming Rules Examples
Type
It should start with the uppercase letter. public class Employee
It should be a noun such as Color, Button, System, Thread, {
Class
etc. //code snippet
Use appropriate words, instead of acronyms. }

It should start with the uppercase letter. interface Printable


It should be an adjective such as Runnable, Remote, {
Interface
ActionListener. //code snippet
Use appropriate words, instead of acronyms. }

class Employee
{
It should start with lowercase letter.
// method
It should be a verb such as main(), print(), println().
void draw()
Method If the name contains multiple words, start it with a lowercase
{
letter followed by an uppercase letter such as
//code snippet
actionPerformed().
}
}

It should start with a lowercase letter such as id, name.It


class Employee
should not start with the special characters like &
{
(ampersand), $ (dollar), _ (underscore).
// variable
Variable If the name contains multiple words, start it with the
int id;
lowercase letter followed by an uppercase letter such as
//code snippet
firstName, lastName.
}
Avoid using one-character variables such as x, y, z.

//package
package com.javatpoint;
It should be a lowercase letter such as java, lang.
class Employee
Package If the name contains multiple words, it should be separated
{
by dots (.) such as java.util, java.lang.
//code snippet
}

class Employee
It should be in uppercase letters such as RED, YELLOW. {
If the name contains multiple words, it should be separated //constant
Constant
by an underscore(_) such as MAX_PRIORITY. static final int MIN_AGE
It may contain digits but not as the first letter. = 18; //code snippet
}

10 | P a g e
The smallest individual element in the program is called token. Java supports 5
types of tokens. They are
1. Keywords (Pre-Defined Words)
2. Identifiers (User-defined Words)
3. Literals (Constants)
4. Operators
5. Separators

1. Keywords:
➢ System or language defined words are called Keywords.
➢ Keywords are also called Pre-defined words or reserved words.
➢ There are 50 keywords used in Java language.
➢ Keywords h..ave a specific meaning and purpose, that purpose will not be changed
by the programmer.
➢ The following are the list of keywords in Java language:

abstract assert boolean break byte case


catch char class const continue default
Do double else enum extends final
finally float for goto if implements
import instanceof int interface long native
New package private public protected return
short static strictfp super switch synchronized
This throw throws transient try void
volatile while

2. Identifiers:
• Programmer or user defined words are known as Identifiers.
• An identifier is a name, given to a program element such as variables, constants,
function names, array names and so on.
Rules for an identifier:
1. An identifier must contain combination of alphabets, digits and underscore only.
2. The first letter must be an alphabet.
3. The length of an identifier can be upto 31 characters.
4. Commas are not allowed
5. Spaces are not allowed
6. Special symbols other than underscore are not allowed
7. Keywords must not be used as identifiers.
8. An identifier must not be repeated in a program.
Examples:
Valid Identifiers: a salary sum stud_num c123 etc.
Invalid Identifiers: a+b 2abc float etc.

11 | P a g e
3. Literals (Or) Constants:
Literals are constants. They cannot be change their values during the execution of the
program. The following are various types of Literals.

LITERALS

(a) Integer Literals:


• Any number without fractional part(decimal point) is called an Integer Literal.
• The integer numbers can contain digits (0…9) and sign (+ or -).
• An Integer Literal must not contain commas and spaces.
Ex: 3 -3 15 -15 2500 -9700 etc.
(b) Floating Point (Real) Literals:
• Any number with fractional part(decimal point) is called floating point Literal.
• A floating point number can contain digits (0…9), a decimal point and/or exponent.
The letter ‘E’ or ‘e’ represents the exponent.
Eg-1: 45.0 4520.2587 -6847.000 -74.56000 etc.
Eg-2: 6.5E5 or 6.5E+5 means 6.5x105
6.5E-5 means 6.5x10-5
(c) Single Character Literals:
• Any single character enclosed within single quotes is known as single character
Literal.
• It may contain any alphabet, digit or special symbol.
• It can be used in arithmetic operations using its ASCII (American Standard Code
for Information Interchange) value.
Ex: ‘A’ ‘h’ ‘4’ ‘+’ ‘&’ etc.
(d) String Literals:
• A sequence of one or more characters enclosed within double quotes is known as
string Literal.
• It can contain alphabets, digits or special symbols. It cannot be used in arithmetic
operations.
Ex: “A” “ABCDE” “Geethanjali” “Venu Kumar” etc..
4. Operators:
An operator is a symbol used to perform operations between the operands. It is used
to manipulate data stored in the variables.
Types of Operators:
1. Arithmetic operators 5. Increment and Decrement Operators
2. Relational operators 6. Conditional Operators
3. Logical operators 7. Bitwise Operators
4. Assignment operators 8. Special Operators

12 | P a g e
5. Separators:
Separators are the symbols used to indicate where groups of score are divided and
arrange.
1) Parenthesis →()
2) Braces →{}
3) Brackets →[]
4) Comma →,
5) Period →.
6) Semi colon →;

• A variable is a name given to a memory location, where the data is stored


temporarily.
• It is an identifier whose value is changed during the execution of a program.
• A variable can store only one value in its location.
• Variables are also called data names.
Rules for naming a variable:
1. A variable name must contain combination of alphabets, digits and underscore only.
2. The first letter must be an alphabet.
3. The length of a variable can be upto 31 characters.
4. Commas are not allowed
5. Spaces are not allowed
6. Special symbols other than underscore are not allowed
7. Keywords must not be used as variable names.
8. A variable name must not be repeated (declaration) in the declaration
Examples:
Valid Variables: a salary sum stud_num c123 etc.
Invalid Variables: a+b 2abc float etc.

Declaration of Variables:
A variable must be declared before it is used in the program. While declaration, the
compiler reserves memory space and creates an address (unsigned integer) to each
variable.
Syntax: datatype var1, var2, ;
Eg: int a, b, sum ;
float avg, f ;
char ch;
Initialisation of Variables: Assigning a value to a variable at the time of declaration is
called Initialisation. If the value is not assigned to a variable by default a garbage
(unknown) value is assigned.

Syntax: datatype var1=value, var2=value, ;


Here, the value must be a constant.
Eg: int a=20, b=100;
float c=12.35;
char ch=’A’;

13 | P a g e
• The area of the program where the variable is accessible and where the variable is
not accessible is called its scope
• Scope determines life time of the variable.
• Lifetime is nothing but when the variable is created and when the variable is
destroyed.
• A block defines the scope of a variable. A block is a piece of code placed between
opening closing curly braces { }.
• Java allows defining a variable inside the block. The variable inside the block is not
accessible in outside the block.
• Java variables are classified into three kinds.
1. Instance variables.
2. Class variables (static)
3. Local variables.
1. Instance variables :
• Instance variables are declared inside a class
• These are created when the objects are instantiated.
• These variables are access through object
2. Class Variables or Static Variables :
• These variables are declared inside the class but outside the methods and blocks
but by using ‘static’ keyword.
• Declare inside Class and outside Method.
• Class variables are global to all objects of a class.
• Allocates only one copy of memory and shared by all objects.
3. Local variables :
• Variables declared and used inside methods are called local variables.
• They are not available for use outside the method definition.
• Local variables can also be declared inside program blocks that are defined between
an opening brace { and a closing brace }.

Block 1

int m = 10;

}
In the above figure the variable x declared in block 1 and is available in all the three
blocks. The variable n declared in block 2 and is available only in block 2. Similarly m is
accessible in block3

14 | P a g e
/* Example program for scope of variables*/
class ScopeEx
{
public static void main(String args[])
{
int i=10; Output::
//block1 i=10
{ j=20
int j=20; i=10
System.out.println("i="+i); j=30
System.out.println("j="+j);
}
//block2
{
int k=30;
System.out.println("i="+i);
System.out.println("k="+j);
}
System.out.println("i="+i);
//System.out.println("j="+j); Error
//System.out.println("k="+k); Error
}
}
Ex.2:- /*Types of Varibles*/
import java.util.*;
import java.lang.*;
class
{
static int c=30; /*static variables*/
int a=10; /*Instance variables*/
public static void main(String args[]) /*Main Method*/
{
int b=20; /*local variables*/
System.out.println(c);
System.out.println(b);
Varible obj=new Varible(); /*Object Creation*/
System.out.println(obj.a);
}
}
Escape / Backslash Character constants :
Java supports some special backslash character constants that are used in output
methods.
Constant Meaning
‘\b’ Back Space
‘\f’ Form Feed
‘\n’ New Line
‘\r’ Carriage return
‘\t’ Horizontal tab
‘\’’ Single quotes
‘\”’ Double quotes
‘\\’ Back Slash
Ex:- public class Test
{
public static void main(String[] args)
{
System.out.println("Hello Dear" +"\n welcome to"+ "\t My World ");
}
}

15 | P a g e
DATA TYPES
Every variable in Java has a data type. The data type specifies the size and type of
data is stored and manipulated in the variable. The Java supports the following data types.

Integer:
Integer types can hold whole numbers such as 78,45 etc. The size of the value is
depends on the type of the integer data type. Java supports 4 types of integer data types.
They are

Size and Range of Integer types:


Type Size Minimum Value Maximum Value
byte 1 byte -128 127
short 2 bytes -32,768 32,767
int 4 bytes -2,147,483,648 2,147,483,647
long 8 bytes -9,223,372,036,855 9,223,372,036,854
Floating point:
Floating point types holds the number containing fractional parts such as 45.9, 9.8 etc.
Java supports 2 types of floating point data types. They

Size and Range of floating point types:


Type Size Minimum Value Maximum Value
float 4 byte 34e-038 34e+038
double 8 bytes 1.7e-308 1.7e+308
Character:
Java provides a character data type called “char”. The char type can hold one
character. It occupies 2 Bytes of memory.
Boolean:
Boolean data type is used, when we want to store the result of the condition. Boolean
data type is defined by using the keyword “Boolean” and uses 1 bit of memory. Here 1 bit is
nothing bur either 0(false) or 1 (true)
16 | P a g e
Converting values form one type to another type is called type conversion or type casting.
Type castings are two types they are
1. Implicit conversion
2. Explicit conversion
1. Implicit conversion: .
• While evaluating the expression java automatically converts the intermediate
values form one type to another type.
• This automatic conversion is known as Implicit Type conversion.
• In the implicit conversion the lower type is automatically converted to the higher
type. This is called widening.

Example:
class Test
{
public static void main(String[] args) Output:
{ Int value 100
int i = 100;
Long value 100
long l = i; //automatic type conversion
float f = l; //automatic type conversion Float value 100.0
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
2. Explicit conversion:
• The type conversion performed by the programmer by specifying data type in the
expression is called explicit conversion.
• In the explicit conversion converting higher type into lower type is called
Narrowing.
• Widening may causes loss of data.
Syntax: (type-name) expression

Example
class Test
{ Output:
public static void main(String[] args) Double value 100.04
{ Long value 100
double d = 100.04; Int value 100
long l = (long)d; //explicit type casting
int i = (int)l; //explicit type casting
System.out.println("Double value "+d);
System.out.println("Long value "+l); //fractional part lost
System.out.println("Int value "+i); //fractional part lost
}
}

17 | P a g e
OPERATORS
Operators: - An operator is a symbol that performs an operation. If an operator acts
on a single variable, then it is called ‘Unary Operator’. If an operator acts on two variables
then it is called ‘Binary Operator’. If an operator acts on three variables then it is called
‘Ternary Operator’. The following are the Operators available in Java.
1) Arithmetic Operators.
2) Relational Operators.
3) Logical Operators.
4) Assignment Operators.
5) Increment and decrement Operators.
6) Conditional Operators.
7) Bitwise Operators.
8) Special Operators.
1. Arithmetic operators:
The Arithmetic operators are used to perform arithmetic calculations such as
addition, subtraction etc. The following are the various arithmetic operators.
Operator Meaning Example Result
+ Addition 10+3 13
– Subtraction 10–3 7
* Multiplication 10*3 30
/ Division 10/3 3
10/3.0 3.3333
% Modulo division (Remainder) 10%3 1
2. Relational Operators:
• The relational operators are used to compare two values or variables.
• If a relational operator placed between two operands then it is called simple
condition.
• The result of simple condition is either true (1) or false (0)
• The following are the relational operators.
Operator Meaning Example Result
== Equal to 10 = = 15 0 (F)
!= Not equal to 10 != 15 1 (T)
> Greater than 10 > 15 0 (F)
< Less than 10 < 15 1 (T)
>= Greater than or equal to 10 >= 15 0 (F)
<= Less than or equal to 10 <= 15 1 (T)
3. Logical Operators:
• Logical operators are used to combine two or more simple conditions.
• If a logical operator is placed beftween two or more simple conditions then it is
called compound condition.
• The result of compound condition is also either true (1) or false (0).
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT

18 | P a g e
(a) Logical AND (&&) Operator:
• The && operator returns true if all the given conditions are true otherwise returns
false.
• The && operator returns false if any one of the given condition is false otherwise
returns true

Truth Table
Condition1 Condition2 Condition1 && Condition2
TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE
Examples:
10>14 && 15<30 && 67<89 → False
23!=34 && 15>10 && 45<78 → True
(b) Logical OR ( ¦¦ ) Operator:
• The ¦¦ operator returns true if any one of the given condition is true otherwise
returns false.

• The ¦¦ operator returns false if all the given conditions are false otherwise returns
true. Truth Table
Condition1 Condition2 Condition1¦¦ Condition2
TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE
Examples:
10>14 ¦¦ 45<30 ¦¦ 67!=67 → False
23!=34 ¦¦ 15>70 ¦¦ 85<78 → True
(c) Logical NOT (!) Operator:
• This operator negates the result of a condition.
• It means if the condition is true then it gives false. If the condition is false then it
returns true.
Truth Table
Condition ! (Condition)
TRUE FALSE
FALSE TRUE
Example:

!(70<50)→!(false)→true

19 | P a g e
4. Assignment Operators:
• The assignment operators are used to assign (store) a value to a variable.
• An assignment operator always consists of a variable on left hand side and a valid
expression/constant/variable on right hand side.
• There are two types of assignment operators. They are
i. Simple Assignment Operator
ii. Compound Assignment Operators
i. Simple Assignment Operator: The equal sign ‘=’ is used as simple assignment
operator. Syntax: Variable = Expression / Constant / Variable.;
Ex: a = 10; c=a+b; a = b; a = b = 50;
ii. Compound Assignment Operators: These are used to perform arithmetic operation
with the specified variable.

Compound
Syntax: Variable operator = Expression / Constant / Variable.;
Example: Let a=10, then
Operator Example Meaning Final Value of ‘a’
+= a += 5 a=a+5 15
–= a –= 5 a=a–5 5
*= a *= 5 a=a*5 50
/= a /= 5 a=a/5 2
%= a %= 5 a=a%5 0

5. Increment and Decrement Operators:


i. Increment Operator (++):
It is used to increase the value of a variable by 1. It is a unary operator. It is used
in two ways. They are pre-increment and post-increment.
Pre-increment: If the ‘++’ operator precedes the variable then it is called “Pre increment”. In
this method, the pre-increment operator increments the value of variable first and thenthe
new value is used in the expression.
For example: c = ++a; means a = a + 1; and then
c = a;
Post-increment: If the ‘++’ operator succeeds the variable then it is called “Post
increment”. In this method, the value of the variable is used in expression and then it is
incremented.
For example: c = a++; means c = a; and then
a = a + 1;
ii. Decrement Operator (– –):
It is used to decrease the value of a variable by 1. It is a unary operator. It
is used in two ways. They are pre-decrement and post-decrement.
Pre-decrement: If the ‘– –’ operator precedes the variable then it is called “Pre decrement”.
In this method, the pre-decrement operator decrements the value of variable first and then
the new value is used in the expression.
For example: c = – – a; means a = a – 1; and then
c = a;
20 | P a g e
Post-decrement: If the ‘– –’ operator succeeds the variable then it is called “Post
decrement”. In this method, the value of the variable is used in expression and then it is
decremented.
For example: c = a – –; means c = a; and then
a = a – 1;
Initial
Values Expression Final Values
a b a b
3 7 a = ++b 8 8
3 7 a = b++ 7 8
3 7 a = – –b 6 6
3 7 a=b–– 7 6
6. Conditional Operator:
This operator performs condition based execution. This operator operates on three
operands. Hence it is also known as Ternary Operator. This operator simplifies “if…else”
control statement. The general form of conditional operator is as follows:
Syntax: var = (condition) ? Statement1 : Statement2 ;
Example:-
import java.io.*;
class Max
{ public static void main(String args[]) throws IOException
{ int a,b,large;
DataInputStream d=new DataInputStream(System.in);
System.out.print(“Enter First Number”);
a=Integer.parseInt(d.readLine());
System.out.print(“Enter Second Number”);
b= Interer.parseInt(d.readLine());
large = (a>b) ? a : b;
System.out.println(“Large value is “ + large);
}
}
In the above example, if a>b then the value of variable ‘a’ is assigned otherwise the
value of ‘b’ is assigned to the variable ‘large’.

7. Bitwise Operators:
Java has the capability of manipulating the bits (0 or 1) directly stored in the
memory. These operators perform bitwise operations on a bit by bit level. However, they
must be used only with integer or character type of values. The operators are as follows
Operator Meaning
& Bitwise AND
¦ Bitwise OR
^ Bitwise XOR (Exclusive OR)
~ 1’s complement
<< Left shift
>> Right shift
>>> Right shift with Zero fill

21 | P a g e
Bitwise AND (&) operator: If all the bits are “1” then this operator returns “1” otherwise
it returns “0”.
Truth table:
& 1 0
1 1 0
0 0 0
Example: Let x = 15 and y = 19, then z = x & y is as follows
Value of x : 00001111
Value of y : 00010011
Value of z : 00000011
(x & y)

Bitwise OR ( ¦ ) operator: If any or all the bits are “1” then it returns “1” otherwise it
returns “0”.
Truth table:
¦ 1 0
1 1 1
0 1 0
Example: Let x = 15 and y = 19, then z = x ¦ y is as follows
Value of x : 00001111
Value of y : 00010011
Value of z : 00011111
(x ¦ y)
Bitwise XOR ( ^ ) operator: If one bit is “1” and other is “0” then it returns “1” otherwise
it gives “0”.
Truth table: ^ 1 0
1 0 1
Example: Let x = 15 and y = 19, then 0 1 0 z = x ^ y is as follows
Value of x : 00001111
Value of y : 00010011
Value of z : 00011100
(x ^ y)

1’s complement (~) operator: This operator is a unary operator that reverses the state of
each bit. That means it changes “0” as “1” and “1” as “0”. Example: Let x = 19, then z =
~x is as follows

Value of x : 00010011
Value of z : 11101100
( ~x )
Left Shift (<<) operator:
This operator is used to move bit patterns to the left. It is used in the following form op<<n
,Here, ‘op’ is an integer value and ‘n’ is number of bit positions. The left shift operator shifts
all the bits of operand ‘op’ to the left by ‘n’ positions. The left most ‘n’ bits in the original bit
pattern will be lost and right most ‘n’ bit positions are filled with zeros.
Example: Let us consider ‘a’ is an unsigned integer whose bit pattern is as follows:
a→ 1100110011001111
a<<3 → 0110011001111000
a<<5 → 1001100111100000

22 | P a g e
The left shift operator is used for multiplication purpose. It means, x<<n gives the
result as x*2n. Example : 5<<1 gives 10, 5<<2 gives 20, 5<<3 gives 40

Right Shift (>>) operator: This operator is used to move bit patterns to the right. It is used
in the following form op>>n

Here, ‘op’ is an integer value and ‘n’ is number of bit positions. This operator shifts all
the bits of operand ‘op’ to the right by ‘n’ positions. The right most ‘n’ bits in the original bit
pattern will be lost and left most ‘n’ bit positions are filled with zeros.

Example: Let us consider ‘a’ is an unsigned integer whose bit pattern is as follows:
a→ 1100110011001111
a>>3 → 0001100110011001
a>>5 → 0000011001100110
The right shift operators can also be used for division purpose. It means, x>>n gives the
result as xn
2
Example : 15>>1 gives 7, 15>>2 gives 3, 15>>3 gives 1
8. Special Operators: The following are the special operators used in Java.
1) Instanceof Operator
2) Dot Operator
3) Type Cast Operator
4) new Operator
Instanceof Operator: The instanceof is an object reference operator and return true if the
object on the left hand side is an instance of the class given on the right side. This operator
determines whether the object belongs to a particular class or not.

Ex: s1 instanceof student

It gives true if the object person belongs to the class student; otherwise it is false

Dot Operator : this operator is also called as member selection operator(.) . the Dot
Operator is used to access the instance variables, methods of class objects, classes, and
sub-packages from a package.
Ex: person.age;
person.salary( );

Type Cast Operator : Cast operator is used to convert one data type into another data
type. This operator can be used by writing datatype inside parenthesis.

Ex: double x = 10.54;


int y = (int) x; // stores 10 into y.

new Operator : new operator is used to create objects to classes. Objects are created on
heap memory by JVM, at runtime.
Syntax : classname obj = new classname( );

23 | P a g e
Priority of Operators:
When several operators are used in a statement, it is important to know which operator
will execute first and which will come next. To determine that, certain rules of operator
precedence are followed:
❖ First, the contents inside the braces: ( ) and [ ] will be executed
❖ Next, ++ and --
❖ Next, *, /, and % will execute
❖ + and - will come next
❖ Relational operators are execute next
❖ Boolean and bitwise operators
❖ Logical operators will come afterwords
❖ Then ternary operator
❖ Assignment operators are executed at the last

Operator Precedence in Java (Highest to Lowest)

Category Operators Associativity

Postfix ++ - - Left to right

Unary + - ! ~ ++ - - Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

24 | P a g e
Reading Input with Java.util.Scanner Class:
➢ The Scanner class is mainly used to get the user input, and it belongs to the java.util
package.
➢ In order to use the Scanner class, you can create an object of the class and use any
of the Scanner class methods.
➢ In the below example, we can use nextLine() method, which is used to read Strings.
importjava.util.Scanner;// import the Scanner class
public class Example
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);//Create a Scanner object
System.out.println(“Enter username”);
String name=s.nextLine();// Read user input
System.out.println(“name is :” +name);//Output user input
}
}
Output: After successful compilation of the above program the output will be:
Enter user name : Venukumar
Name is Venukumar
Scanner Class Methods:-
Method Description
nextBoolean() Reads a Boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user

BufferedReader class:-
Reads text from a character-input stream, buffering characters so as to
provide for the efficient reading of characters, arrays, and lines. The buffer size
may be specified, or the default size may be used. The default is large enough for
most purposes
BufferedReader is used to decrease the time for taking input. Generally, we
use the Scanner class.

25 | P a g e
Example:-
import java.io.*;
class Addition1
{
public static void main(String args[])
throws Exception
{
int a, b, c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter any two numbers to add:");
a = Integer.parseInt(br.readLine());
b = Integer.parseInt(br.readLine());
c = a + b;
System.out.println("\nSum of two numbers:" + c);
}
}
Output: Enter any two numbers to add:
30 20
Sum of two numbers: 50

Displaying Output with System.out.println():


• Java System.out.println () is used to print an argument that is passed to it.
• The statement can be broken into 3 parts which can be understood separately as :
1. System : It is a final class defined in the java.lang package.
2. Out : This is an instance of Print stream type, which is a public and static
member field of the System class.
3. Println(): As all instances of Printstream class have a public method
println(),hence we can invoke the same on out as well. This is an upgraded
version of print().
Syntax: System.out.println (parameter); (Or)
System.out.print(parameter); (Or) System.out.printf(parameter);
Example: import java.io.*;
class Sample
{
public static void main(String args[])
{
System.out.println(“Welcome”);
System.out.println(“To”);
System.out.println(“Java Programming”);
}
}
Output: After successful compilation of the above program the output will be:
Welcome
To
Java Prorgamming

26 | P a g e
Command Line Arguments:
➢ The java command-line argument is an argument i.e. passed at the time of running the
java program.
➢ The arguments passed from the console can be received in the java program and it can
be used as an input

➢ Any argument provided in the command line is stored in a String class array called
args[], which is the formal argument of main() function.
➢ The individual element of an array args[] is accessed by a number called “index”.
➢ The index of first argument is “0” and the index of last argument is “args.length-1”
➢ There is no restriction on the number of java command line arguments. We can specify
any number of arguments.
➢ All the supplied arguments are string class objects later they can be translated into
any other types using “Wrapper classes”.

Syntax:

Example1:
import java.lang.String;
import java.lang.System; Output:
class Cmd Pascal
{ C
public static void main(String[] args) C++
{ Java
for(int i=0;i< args.length;i++) Basic
{ Oracle
System.out.println(args[i]);
}
}
}
Compiling : javac Cmd.java
Running: java Cmd Pascal C C++ Java Basic Oracle
Ex 2:-
class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
Output:- compile by > javac CommandLineExample.java
run by > java CommandLineExample venukumar
Output: Your first argument is: venukumar

27 | P a g e
• Control structures (statements) used to specify the order in which an instruction is
executed in the program.
• Control structures are used to change the execution sequence.
• In Java, the control statements are classified into 3 types. They are as follows:

Control Statements

Conditional /Decision Repetitive or Iterative Unconditional or Jumping


Control Statements Control Statements Statements

If Statement while continue


if...else Statement do...while break
Switch Statement for return
Conditional Operator

These statements execute a group of statements depending on the given condition.


The following are conditional control statements.
1. if statement
2. if-else statement
3. if-else-if statement
4. else-if ladder
5. switch statement

1. ‘if’ statement:-
It is a conditional branching statement that executes the specified set of
instructions based on the condition.

Condition
T
Syntax: if (condition)
StatementBlock; Statement Block
F

• In the above syntax, if the condition is true then the statements in the statement-
block are executed, otherwise they are not executed.
• When there are multiple statements then they must be enclosed within curly braces
‘{ }’.
Examples:
1. if (avg >= 75)
System.out.println(“grade is distinction”);
2. if (a < 0)
a++;

28 | P a g e
2. ‘if-else’ statement:
It is conditional branching statement that executes the statements based on the
condition. If the condition is true then it executes one group of statements (true part)
otherwise it executes another group of statements (false part).

Flowchart:

Syntax: if (condition)
StatementBlock1;

else Condition

StatementBlock2;
Statement Block-2 Statement Block-1

3. ‘if-else-if’ or nested ‘if’ Statement:


When the ‘if’ statement is used within another ‘if’ statement then it is called ‘if-else-
if’ or nested ‘if’ statement.
Syntax:

if (condition1) Flowchar
{
if (condition2)
statement-block1 ; Cond-1
else
statement-block2 ;
} Cond-2 Cond-3
else
{
Statementblock1 Statementblock3
if (condition3) Statementblock2 Statementblock4

statement-block3 ;
else
statement-block4 ;
}
In the above syntax,
i. If ‘condition1’ and ‘condition2’ are true then stament-block1 is executed
ii. If ‘condition1’ is true and ‘condition2’ is false then stament-block2 is executed
iii. If ‘condition1’ is false and ‘condition3’ is true then stament-block3 is executed
iv. If ‘condition1’ and ‘condition3’ are false then stament-block4 is executed
Ex:- class Nesting
{
public static void main(String args[])
{
int a=3,b=7,c=4;
Sytem.out.print(“Larget value is : “);
if( a>b)
{
if(a>c)
System.out.println(a);
else
System.out.println(b);
}
else
{
if (b>c)
System.out.println(b);
else
System.out.println(c);
} } }
29 | P a g e
4. else-If ladder: An if statement followed by at least one else if statement then it is
called else-if ladder. Once an else if succeeds, none of the remaining else if's or else's will
be tested. None of the else-if statements are succeeded the final else statement is
executed.
Syntax:

if(cindition1)
Statement1;
else if(cindition2)
Statement2;
else if(cindition3)
Statement3;
else if(condition n)
Statement n;
else
Default statements;

Example:
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");

5. Switch Statement: The ‘switch’ statement is a multiple condition statement. It can be


used to make a decision from the number of choices. It is an extension of ‘if…else’
statement.
Syntax:
switch(operand) Flowchart:
{
case v1 :
statement-block1;
break; Switch (operand)
case v2 :
statement-block2;
break; T
Case Statement-
: :
: : F
case vn :
T
statement-block-n; Case Statement-
break;
default : F
statement-block-d; T
Case Statement-
}
F

Here, ‘operand’ can be a constant, variable default


T
Statement-
(or) expression. v1, v2, …, vn are unique
values of integer or character type.

30 | P a g e
Working:
• If a case value matches to the ‘operand’, the switch statement executes all the
statements in that block.
• If there is ‘break’ statement in that block then it stops execution of switch
statement. If ‘break’ is not present then all the remaining blocks are also executed.
• If any value doesn’t match the operand then the default block is executed, if it is
specified in the switch statement.
Example 1:
int a=4;
switch (a)
{
case 1: System.out.println(“Sunday”);
break;
case 2: System.out.println(“Monday”);
break;
case 3: System.out.println(“Tuesday”);
break;
case 4: System.out.println(“Wednesday”);
break;
case 5: System.out.println(“Thursday”);
break;
case 6: System.out.println(“Friday”);
break;
case 7: System.out.println(“Saturday”);
break;
default: System.out.println(“Wrong Value”);
}

Example 2:-
//To perform all arithmetic operators using switch
import java.util.Scanner;
public class Switchex
{
public static void main(String[] args)
{
int a, b, op;
Scanner sc = new Scanner(System.in); //object of the Scanner class
System.out.println("Enter the first number:");
a = sc.nextInt(); //reading input from the user
System.out.println("Enter the second number:");
b = sc.nextInt();
System.out.println("Enter 1.Addition\n 2.Subtraction \n 3.Multiplication \n 4.division:");
op = sc.nextInt();
switch(op)
{
case 1: System.out.println(+(a+b));
break;
case 2: System.out.println(+(a-b));
break;
case 3: System.out.println(+(a*b));
break;
case 4: System.out.println(+(float)a/b);
break;
default: System.out.println("Wrong Value");
}
}
}

31 | P a g e
The repetitive control statements are used to execute a group of statements
repeatedly as long as the given condition is satisfied. The repetitive control statements are
also called Iterative (or) Looping control statements.
In 'C' language, there are 3 types of repetitive control structures. They are
1. While structure
2. Do…while structure
3. For structure
1. While Structure (while loop):
• This statement executes one or more statements repeatedly as long as the
condition is satisfied.
• It is an entry control loop structure. Because first it evaluates the condition
after that it executes statement part.
• Looping process is continued in while loop as long as the condition is true; when
the condition becomes false the loop will be terminated.

Flow diagram:-
Syntax: while (condition)
{
T
Statementblock; Condition Statement-block
}
F
Here,
− The condition must be enclosed within parenthesis.
The statement-block specifies one or more statements. When there is more than one
statement, they must be enclosed in flower braces ‘{ }’
Ex : class ExWhile
{
public static void main(String args[ ])
{
int i=1;
while(i<=100)
{
System.out.print(i);
++i;
}
}
}
o/p: 1 2 3 4 …….100

2. do…while Structure (do..while loop):


• This statement executes one or more statements repeatedly as long as the condition is
satisfied.
• It is an exit control loop structure. Because first it executes statement part after that it
evaluates the condition.
• Looping process is continued in do-while loop as long as the condition is true; when the
condition becomes false the loop will be terminated.
• Do-while executes the statement part at least once whether the condition is true or
false.
32 | P a g e
Syntax:
do
{
Statement block;
} while (condition);
Here,
− The condition must be enclosed within parenthesis.
− The statement-block specifies one or more statements. When there is more than
one statement, they must be enclosed in flower braces ‘{ }’.
Ex:-

Example :
class ExDoWhile
{
public static void main(String args[ ])
{
int i=1;
do
{
System.out.print(i);
++i;
} while(i<=100);
}
} Output:- : 1 2 3 4 …….100

3. ‘for’ structure (for loop):


This statement executes one or more statements repeatedly as long as the condition is
true.
Syntax: for(initialisation ; condition ; increment/decrement)

{
statement-block;
}
• It executes the statements in initialization part and then it checks the condition.
• If the condition is true then it executes all the statements in the statement-block.
• After executing all the statements, increment/decrement part is executed then
again checks the condition.
This looping process is continued as long as condition is true. When the condition is false,
the loop is terminated
Flow diagram:-

Ex:- Initialization
class ExFor
{
public static void main(String args[ ]) T
{ Condition
int i;
Statement-block
for(i=1 ; i<=100 ; i++) F
System.out.print(i);
}
} Increment /decrement

33 | P a g e
The unconditional branching statements are used to transfer the control from one
place to another place within a program without using any condition.
The following are the unconditional control structures used in 'JAVA' language.
1. Break 2. Continue 3. Return
1. Jumping out of a Loop (or) Break Statement:
Normally the break statement is used in switch statement. But it is also used to
terminate the execution of a loop unconditionally.
Syntax:
break ;
Example:
int i=1;
for(i=1;i<=100;i++)
{
System.out.println(i);
if(i==50)
Output: 1 2 3 4 …….50
break;

2. Skipping a part of a loop (or) Continue Statement:


The continue statement must be used in loops only. When the continue statement
is reached within a loop, it continues the execution from the first statement of the loop.
Syntax:
Continue ;
Example:
int i=1;
for(i=1;i<=10;i++)
{
if(i==4 || i==7)
continue;
System.out.println(i); Output: 1 2 3 5 6 8 9 10
}

3. Return Statement :
return statement is used in a method to come out of it to the calling method. return
statement is often used in the methods.
Examples : return (x+y); //calculates x+y and return that value
return -5; // return -5 to the calling method.
Ex:- class Demo
{
public static void main( String args [ ] )
{
int res=Demo.square(10);
System.out.println(“Result = “ + res);
}
static int square(int num)
{
return num * num;
}
} Output : Result = 100

34 | P a g e

You might also like