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

JavaUNIT-1 Notes (1)

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

UNIT-1

Need for Object Oriented Programming:


Object-oriented programming offers several advantages and some of these are highlighted as follows:
Reusability In OOP programs, functions and modules can be reused by other users without any modification. It enables
programmers to build the programs from previously tested standard working modules that communicate with one another.
Thus, it saves development time and leads to high productivity as we do not need to write the code from scratch.

Modular structure OOP provides a clear and modular structure for program development. This enables us to define abstract
data types where implementation details can be kept hidden.

Easy to maintain and upgrade Object-oriented systems can be easily upgraded. It is easy to maintain and modify the
existing code. Because of the modularity, it is easier to locate and correct the problem rather than search for the problem in
the entire program.

Inheritance This allows us to eliminate redundant code and use existing classes.

Data hiding The programmer can hide the data and functions in a class from other classes. It helps in the building of secure
programs.
History of java:
Java was developed by James Gosling in 1995, he is known as the father of java. Java team members are known as Green
Team, they initiated a revolutionary task to develop a language for digital devices such as set-top boxes, televisions etc.
Currently, Java is used in internet programming, mobile devices, games, e-business applications etc. Firstly it was called
"Greentalk" by James Gosling. Later, it is changed to “Oak”.
Why Oak name for Java language?  Oak is a symbol of strength and choosen as a national tree of many countries like
U.S.A., France, Germany, Romania etc. In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
INTRODUCTION TO JAVA:
It is a simple programming language. Java makes writing, compiling, and debugging programming easy. It helps to create
reusable code and modular programs. Java is a class- based, object-oriented programming language and is designed to have
as few implementation dependencies as possible. A general-purpose programming language made for developers to write
once run anywhere that is compiled Java code can run on all platforms that support Java. Java applications are compiled to
byte code that can run on any Java Virtual Machine. The syntax of Java is similar to c/c++. Now more than 3 billion devices
run java.
Features of Java (buzz words)
There is given many features of java. They are also known as java buzzwords.
1. Simple
2. Object-Oriented
3. Portable and Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Multithreaded
8. Distributed applications
9. Compiler/Interpreter
Simple:
Java is simple language. It does not use pointer, goto statements, etc. It eliminates operator overloading and
multiple inheritance.
Object-Oriented:
Everything in java is an object. Object oriented means we organise our software as a combination of different
types of objects that incorporates both data and behaviour.
Portable and Platform independent:
Write once and run anywhere. Java programs are portable because of its ability to run the program on any
platform and no dependency on the underlying hardware/operating system.
Secured:
Security is an important feature of Java and this is the strong reason that programmer use this language for
programming on Internet. The absence of pointers in Java ensures that programs cannot get right of entry to
memory location without proper approval.
Robust:
Java is a most strong language which provides many securities to make certain reliable code. It is design as
garbage –collected language, which helps the programmers virtually from all memory management problems.
Java also includes the concept of exception handling, which detain serious errors and reduces all kind of threat
of crashing the system.
Architecture neutral:
Irrespective of architecture the memory allocated to the variables will not vary. Whatever the architecture we
are using that memory allocated for the variables is same.
Eg: In C language the size of the datatype is depends on the architecture of the compiler, So if we take integer
variable in 16bit compiler it occupies 2bytes of memory, and if it is 32bit compiler it is 4bytes of memory.
Here, the memory allocation depends on the architecture.
Multithreaded:
Concurrent execution of several parts of same program at same time. So this will improve CPU utilization.
Distributed applications:
It is software that runs on multiple computers connected to a network at the same time. [A java program is able
to create this Distributed applications].
Compiler/Interpreter: Usually a computer language is either compiled or interpreted. Java combines both these
approaches thus making java a two-stage system. First, java compiler translates source code into bytecode.
Bytecodes are not machine instructions and therefore, in the second stage, java interpreter generates machine
code that can be directly executed by the machine that is running the java program so we can say that java is
both compiled and interpreted language.

Difference between C and JAVA


C JAVA

1 It is procedure oriented language. 1 It is object oriented language.

2 C is divided into small parts called 2 Java is divided into some parts called class and
functions. objects.

3 C is middle level language. 3 Java is high level language.

4 C is platform dependent. 4 Java is platform independent.

5 C doesn’t support Multithreading. 5 Java supports Multi-threading.

6 C supports pointers. 6 Java does not supports pointers.

7 In C garbage collection needs to 7 In java it is automatically managed by a Garbage


managed manually. collector.

8 In C declaration variables are declared at 8 In Java variables are declared any where.
the beginning.

9 free() is a function to release the memory 9 A compiler will free up the memory by calling the
in C. Garbage collector.

10 C does not have a feature of overloading 10 Java supports method overloading.


functionality.

11 Function oriented program follows top to 11 Object oriented programming follows bottom up
down approach. approach.

12 C does not have access 12 It has 3-access specifiers public, private, protected
specifiers/modifiers. and default.

13 Data can move freely from function to 13 Objects can move and can communicate with each
function in the system. other.

14 No data hiding is possible hence, security 14 In Java provides data hiding hence, security is
is not possible. possible.

Where Java is used?


There are many devices where Java is currently used.
 Desktop applications such as Acrobat Reader, Media Player, Anti-Virus etc.
 Web applications such as irctc.co.in.
 Enterprise applications such as banking applications.
 Mobile applications.
 Embedded system.
 Smart card.
 Robotics.
 Games etc.
Structure of java program:
 Documentation Section
 Package Statement
 Import Statements
 Interface Statements
 Class Definitions
 Main method definition

Documentation Section:
It is an important section but optional for a java program. It includes basic information about a java program. The
information includes the description of the program. Whatever we write in the documentation section, the java compiler
ignores the statements during execution of the program. To write the statements in the documentation section, we use
comments. The comments may be single-line, multi-line and documentation comments.
Single-line comment: //Example for Single line comment
Multi-line comment: /*it is an example of multiline comment*/
Documentation comment: /**it is an example of documentation comment*/ (This comment style is new in java. The main
purpose of this type of comment is to automatically generate program documentation. The java doc tool reads these
comments and uses them to prepare your program’s documentation in HTML format.)

Package Declaration:
It is an optional declaration. Package name can be defined by programmer with any name. Package contains a group
of classes. By default compiler consider as these classes, which are defined under it belongs to this package.
Package packagename;

Import statements:
It contains many predefined classes and interfaces. If we want to use any class of a
particular package, we need to import that class. We use the import keyword to import the class.
import java.util.Scanner; //it imports the scanner class
import java.util.*; //it imports all the class of the java.

Interface Section:
An interface is similar to classes, which consist of group of method declaration. It is an optional section and can be
used when programmers want to implement multiple inheritance.

Interface car
{
Void start();
Void stop();
}

Class Definition:
In this section, we define the class. Without the class, we cannot create any java program. We use the class keyword
to define the class.
class Example //class definition
{
}

Main method:
In this section, we define the main() method. It is essential for all java programs. Because the execution of all java
programs starts from the main() method. In other words, it is an entry point of the class. It must be inside the class.
public static void main(String args[])
{
}
WRITING SIMPLE JAVA PROGRAMS:

Java is purely an object-oriented language and the classes are the means to achieve the same. Therefore, after the import
statement, as discussed, every program starts with the declaration of a 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.
In Program 2.1, the class name is Start. The body of the class, which may consist of several statements or calls to other
methods, is enclosed between the braces {}. A sample of class declaration is illustrated in Fig. 2.1.
Java’s main() method is the starting point from where the JVM starts the execution of a Java
program. JVM will not execute the code, if the program is missing the main method. Hence, it is one of the most important
methods of Java, and having a proper understanding of it is very important.
The Java compiler or JVM looks for the main method when it starts executing a Java program. The signature of the main
method needs to be in a specific way for the JVM to recognize that method as its entry point. If we change the signature of
the method, the program compiles but does not execute.
Java Example
Let's have a quick look at java programming example
1. class Simple {
2. public static void main(String args[]) {
3. System.out.println("Hello Java");
4. }
5. }

Understanding public static void main(String args[]) in java:


The point from where the program starts its execution or simply the entry point of java programs is the main() method.

Public:
It is an access modifier, which specifies from where the main() method public makes it globally available. It is made public,
so that JVM (java virtual machine) can invoke it from outside the class as it is not present in the current class.
class Example
{
private static void main(String[] args)
{
System.out.print(“a”);
}
Output:
Error: method not found in class, please define the main method as:
public static void main(String[] args)
Static (Direct access without object):
It is a keyword when it is associated with a method, makes it a class related method. The main() method is static so that JVM
can invoke it without instantiating the class(Without creating an object for a class).
class Ex
{
public void main(String[] args)
{
System.out.print(“a”);
}
Output: Error: method not found in class Ex, please define the main method as:
public static void main(String[] args).
Void:
It is a keyword and is used to specify that a method doesn’t return anything. As the main() method doesn’t return
anything, its return type is void. As soon as the main() method terminates, the Java program terminates too. In Java, every
method has the return type. Void keyword acknowledges the compiler that main() method does not return any value. Hence,
it doesn’t make any sense to return from the main() method as JVM can’t do anything with its return value of it.
If main method is not void, we will get an error.
Main:
It is the name of java main method & it is the identifier that the JVM looks for as the starting point of the java program.
Note: main is not a keyword.

String[] args:
It stores java command line arguments and is an array of type. (When you run a java program with command prompt or want
to give command line arguments, then “String[] args” is used) Here, the name of the string array is args but it is not fixed and
user can use any name.
The main() method also accepts some data from the user. It accepts a group of strings, which is called a string array. It is used
to hold the command line arguments in the form of string values.
main(String args[])

Here, agrs[] is the array name, and it is of String type. It means that it can store a group of string. Remember, this array can
also store a group of numbers but in the form of string only. Values passed to the main() method is called arguments. These
arguments are stored into args[] array, so the name args[] is generally used for it.

The class body starts with the left brace ({) and ends with the right closing brace (}). A class body may comprise statements
for declaration of variables, constants, expressions, and methods.
In the aforementioned case, we have written “class body” after// because it is a comment. Anything written after double slash
(//) up to the end of a line becomes a comment. Comments are neglected by the compiler. They are not part of a program.

ELEMENTS OR TOKENS IN JAVA PROGRAM:

 Tokens are the smallest elements of a program that is meaningful to the compiler. They are also known as the
fundamental building blocks of the program.
 Java compiler breaks the line of code into text (words) is called Java tokens.
Tokens can be classified as follows:
1. Keywords
2. Identifiers
3. Constants/literals
4. Separators
5. Operators
6. Comments
Keyword: Keywords are pre-defined or reserved words in a programming language. Each keyword is
meant to perform a specific function in a program. Since keywords are referred names for a compiler,
they can’t be used as variable names because by doing so, we are trying to assign a new meaning to
the keyword which is not allowed. Java language supports following keywords:
Identifiers:
Identifiers are used to name a variable, constant, function, class, and array. Remember that the identifier name must be
different from the reserved keywords.

There are some rules to declare identifiers are:


1. An Identifier name must start with a letter, a currency character ($), or a connecting character
such as underscore (_).
2. Identifier should not start with a number (digit).
3. Identifier may be a single word or combination of words with no spaces in between the words.
4. Identifier should be a keyword of java.
5. Identifier should not be a Boolean literal i.e true or false.
6. Identifier should not be a null literal.
7. It should not start with a digit but it can start with an underscore (which is not encouraged).
8. It can comprise one or more unicode characters which are characters as well as digits. Therefore,
a programmer may write names in the native language if it is part of the unicode character set
and are recognized by the user’s computer.
9. Uppercase and lowercase letters are distinct. Example : Total, TOTAL and total are different.
10. They can be of any length, but the number of characters of an identifier should be between 4 to
15 characters.
11. Spaces and any special symbols are not allowed except underscore (_) and Dollar $.
Conventions for identifier names:
1. Names of all methods should start with a lower-case character. If the name contains two or more
words, the subsequent words start with a capital letter. A pair of parentheses at the end indicates that
it is a method. The words are generally verbs;
Ex:- total, display(), totalMarks, netSalary, getData(), compute(), display(), run(), etc.

2.All names of classes and interfaces should start with a capital letter, if the name contains more than
one word then the second word’s first character should be capital letter. Ensure that there should not
be any spaces between the words.
Ex:- Student, HelloJava

3.All the Names of variables should start with a lower-case character. If more than one word is present,
the other words should start with upper case character. The names are generally nouns.
Some examples are s, x, y, ch, price, age, etc.
4. Names of Constant variables should be written in capital letters and if there are more than one word
an underscore is used between words.
Ex:- MAX, TOTAL_VALUE

5. Names of packages should be written in name should be in written in lowercase only.Ex:- mypack,
mypackage, java.lang etc
Constants/Literals:
Constants are also like normal variables. But the only difference is, their values cannot be modified by the
program once they are defined. Constants refer to fixed values. They are also called as literals. Constants may
belong to any of the data type.
In java, a literal may be one of the following

1. Integer literals
2. Floating point literals
3. Boolean literals
4. Character literals
5. String literals
6. Null Literals

Integer Literals: Interger literals are sequence 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. The digital literals may be of the following types.
Decimal Integer Literals : These are sequences of decimal digits which are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. The
decimal numbers are the numbers used in everyday computation. 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 for distinction. Examples are 0x56ab or 0X6AF2, etc.
Octal Integer Literals: These are sequences of octal digits which are 0, 1, 2, 3, 4, 5, 6, and 7. For distinction,
these numbers are preceded by 0. Examples of literals are 07122, 04, 043526, etc.
Binary Literal: These are sequences of binary digits. Binary numbers have only two digits—0 and 1 and a base 2.
These numbers are preceded by 0b for identification by the computer. 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 of such numbers are 3.14159, 567.78, etc.
Boolean Literal: These are Boolean values. There are only two values—true or false.
Character Literal: These are the values in characters. Characters are represented in single quotes such as ‘A’,
‘H’, ‘k’, and so on. The character may as well be represented in hexadecimal or octal numbers. More examples are
‘b’, ‘z’, ‘\uFFFF’, ‘\178’, etc.
String Literals: These are strings of characters in double quotes. Examples are “Delhi”, “John”, “AA”, etc.
Null Literal: There is only one value of Null Literal, that is, null.
Seperators:- In java, the different separators are represented by parentheses ‘()’, braces ‘{}’, square brackets ‘[]’,
commas ‘,’, semicolon ‘;’, and period ‘.’. Each of these is used for different applications as listed in Table 2.3.
Operators:- There are 37 operators in Java. Java provides many types of operators which can be used according
to the need. They are classified based on the functionality they provide. Some of the types are-
 Arithmetic Operators
 Unary Operators
 Assignment Operator
 Relational Operators
 Logical Operators
 Ternary Operator(conditional operator)
 Bitwise Operators and bit-shift operators
 instance of operator
Comments:
In Java, Comments are the part of the program which are ignored by the compiler while compiling the Program.
They are useful as they can be used to describe the operation or methods in the program. The Comments are
classified as follows:
• Single Line Comments
• Multiline Comments

STRUCTURE OF JAVA PROGRAM:


Documentation section:

The documentation section is optional and contains the comments in the java program code. The comments are
part of java program that are ignored and not compiled by the compiler.

The main purpose of the comments in the documentation section is to improve the readability and
maintainability of the java programming code. The comments are added to the program code especially in the
large and complex project where number of programmers are writing the programming code. The comments
inserted in the program code makes it easier to understand the programming code.
The documentation section is an important section but optional for a Java program. It includes basic information
about a Java program. The information includes the author's name, date of creation, version, program name,
company name, and description of the program. It improves the readability of the program. Whatever we write in
the documentation section, the Java compiler ignores the statements during the execution of the program. To write
the statements in the documentation section, we use comments. The comments may be single-line, multi-line,
and documentation comments.
Package statement:
The package statement in java program is optional and identifies the package that a java program is a part of the
package. The package declaration is optional. It is placed just after the documentation section. In this section, we
declare the package name in which the class is placed. Note that there can be only one package statement in a

Java program. It must be defined before any class and interface declaration. It is necessary because a Java class
can be placed in different packages and directories based on the module they are used. For all these classes
package belongs to a single parent directory. We use the keyword package to declare the package name. For
example:

Ex: - package student

Import statements:
This is the statement after the package statement. It is similar to # include in c/c++. The package contains the
many predefined classes and interfaces. If we want to use any class of a particular package, we need to import that
class. The import statement represents the class stored in the other package. We use the import keyword to import
the class. It is written before the class declaration and after the package statement. We use the import statement in
two ways, either import a specific class or import all classes of a particular package. In a Java program, we can use
multiple import statements.
For example:

import java.util.Scanner; //it imports the Scanner class only

The above statement instructs the interpreter to load the Scanner class from the java.util package.
Note:
 Import statement should be before the class definitions.
 A java file can contain N number of import statements.

Interface statements:

An interface is like a class but includes a group of method declarations. It is an optional section. We can create an
interface in this section if required. We use the interface keyword to create an interface. An interface is a slightly
different from the class. It contains only constants and method declarations. Another difference is that it cannot
be instantiated. We can use interface in classes by using the implements keyword. An interface can also be
used with other interfaces by using the extends keyword. For example:

interface car
{
void start();
void stop();
}
Note: Methods in interfaces are not defined just declared.
Class definitions:

Java is a true oop, so classes are primary and essential elements of java program. A programcan have multiple
class definitions. In this section, we define the class. It is vital part of a Java program. Without the class, we cannot
create any Java program. A Java program may conation more than one class definition. We use the class keyword
to define the class. The class is a blueprint of a Java program. It contains information about user-defined methods,
variables, and constants. Every Java program has at least one class that contains the main() method.

For example

class Student
{
//class definition
}
Main method class:

Every stand-alone program required a main method as its starting point. As it is true oop the main method is kept
in a class definition. Every stand-alone small java program should contain at least one class with main method
definition. In this section, we define the main() method. It is essential for all Java programs. Because the
execution of all Java programs starts from the main() method. In other words, it is an entry point of the class. It
must be inside the class. Inside the main method, we create objects and call the methods. We use the following
statement to define the main() method:

public static void main(String args[])


{
}
Rules for writing JAVA programs:
1. Every statement ends with a semicolon
2. Source file name and class name must be the same.
3. It is a case-sensitive language.
4. Every thing must be placed inside a class, this feature makes JAVA a true object oriented
programming language.

Rules for file names:


 A source code file can have only one public class, and the file name must match the public class
name.
 A file can have more than one non-public class.
 Files with no public classes have no naming restrictions.

The following picture shows the execution of a java program/applet.

JAVA STATEMENTS:
 The java program consists of set of instructions, where every instructions are called statements
in java.
 A statement specifies an action in a Java program.
 Java statements can be broadly classified into the following categories:
 Empty Statement
 Variable Declaration statement
 Labelled Statement
 Expression statement
 Control statement
 Selection statement
 Iteration statement
 Jump statement
 Synchronization statement
 Guarding statement
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 behaviour 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 that we
can pass through a command line can be obtained through the number of elements in an array. To ensure this, we
can make use of the length property of the array. Command line arguments are parameters that are passed to the
application program atthe time of execution. The parameters are received by args array of string type.
The first argument is stored at args[0]
The second argument is stored at args[1] and so on…..
Example 1:

class Xyz
{
public static void main(String args[])
{
System.out.println(“Enter any number:” +args[0]);
}
}
OUTPUT:
Compile: javac Xyz.java
run: java Xyz 23

EXAMPLE-2
class Sum
{
public static void main(String ar[])
{
int x,y,s;
x=Integer.parseInt(ar[0]);
y=Integer.parseInt(ar[1]);
s=x+y;
System.out.println("sum of " + x + " and " + y +" is " +s);
}
}

OUTPUT:

Compile: javac Sum.java


run: java Sum 23 6

USER INPUT TO THE PROGRAM:


In this section, we make use of the class Scanner of package java.util to carry out input to the program. Basically,
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. The object of the class Scanner is declared. Here, in Program 2.6
scaninput is the name of the object. The object invokes the public methods of class. Here, 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 illustrates a
user’s input from the keyboard.
 The Scanner class is used to get user input, and it is found in the java.util package.
 To use the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class.
 For Example, we will use the nextLine() method to read String.

Input Types and their respective 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

import java.util.*;
class UserInputDemo
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter first number- ");
int a= sc.nextInt();
System.out.print("Enter second number- ");
int b= sc.nextInt();
System.out.print("Enter third number- ");
int c= sc.nextInt();
int d=a+b+c;
System.out.println("Total= " +d);
}
}
ESCAPE SEQUENCE CHARACTERS:
 If a character is preceded by a backslash (\) is known as Java escape sequence or escape characters.
It may include letters, numerals, punctuations, etc.
 Escape characters must be enclosed in quotation marks (""). These are the valid character literals.
The Java compiler interprets these characters as a single character that adds a specific meaning to the
compiler.
Escape Characters Description

\t It is used to insert a tab in the text at this point.

\' It is used to insert a single quote character in the


text at this point.

\" It is used to insert a double quote character in the


text at this point.

\\ It is used to insert a backslash character in the


text at this point.

\n It is used to insert a new line in the text at this


point.

\b It is used to insert a backspace in the text at this


point.

//Using Escape Characters in Java Program


public class EscapeCharaterExample
{
public static void main(String args[])
{
String str = “Java\tProgramming"; //it inserts a Tab Space
System.out.println(str);
String str1 = "the best way\nto communicate \nan idea \nis to act it out"; //it inserts a New Line
System.out.println(str1);
String str2 = "And\\Or"; //it insert a backslash
System.out.println(str2);
String str3 = “Javac\bProgramming”);
System.out.println(str3);
String str4 = ”\’EscapeCharacters\’"; //it prints a single quote
System.out.println(str4);
String str5 = ”\”EscapeCharacters\”"; //it prints a double quote
System.out.println(str5);
}
}

programming style refers to the conventions and guidelines followed to write clean, readable, and
maintainable code. While there are various style guides (like Google's, Oracle's, and others), the core
principles remain consistent.
Key Elements of Java Programming Style
Naming Conventions
 Class names: Start with a capital letter, use nouns or noun phrases (e.g., Customer, OrderProcessor).
 Method names: Start with a lowercase letter, use verbs or verb phrases (e.g., calculateTotal,
displayMessage).
 Variable names: Start with a lowercase letter, use descriptive names (e.g., customerName,
orderQuantity).
 Constants: Use all uppercase letters with underscores (e.g., MAX_VALUE, PI).
Indentation and Formatting
 Use consistent indentation (usually 4 spaces).
 Place opening curly braces on the same line as the control structure (e.g., if, for, while).
 Use braces for all control structures, even for single-line statements.
 Limit line length to improve readability.
Comments
 Use clear and concise comments to explain the code's purpose.
 Add comments to clarify complex logic or non-obvious code sections.
 Avoid excessive commenting; well-named variables and methods often reduce the need for comments.
Code Organization
 Break down code into logical methods and classes.
 Use meaningful and descriptive method and class names.
 Follow a consistent structure within classes (e.g., fields, constructors, methods).
 Use appropriate access modifiers (public, private, protected).
Code Readability
 Use meaningful variable and method names.
 Avoid magic numbers; use constants instead.
 Write clean and concise code.
 Consider using white space effectively to improve readability.
VARIABLES:
A variable in Java is essentially a named container that holds data values during program execution. It's like a
box with a label (the variable name) where you can store different items (data).
Key Characteristics:
 Data Type: Defines the type of data a variable can hold (e.g., numbers, characters, text).
 Name: A unique identifier for the variable.
 Value: The data stored in the variable, which can change during program execution.
Declaring a Variable
To use a variable, you must first declare it, specifying its data type and name:
Java
data_type variable_name;
Example:
Java
int age;
String name;
double salary;
Assigning a Value
Once declared, you can assign a value to a variable using the assignment operator (=):
Java
age = 30;
name = "Alice";
salary = 50000.50;
There are three types of variables:
1. Local variable
2. Instance variable
3. Static/class variable.
Local variable:
A variable that is declared and used inside the body of methods, constructor or blocks is called
local variable, it cannot be defined with "static" keyword.

Local variable must be assigned a value at the time of declaration.


No access modifiers can be used with local variables.
A local variable cannot be static.
Syntax:
class class_name
{
return_type method_name()

{
data_type variable=value;
}
}

//Example-1 for local variable


class Localvar
{

void m(int x,int y)

{
int z=x+y;
System.out.println(z);
}
public static void main(String[] args)

{
Localvar v= new Localvar();
v.m(10,20);
}

OUTPUT:
30
Instance variable:
A variable that is declared inside the class but outside the body of a method, constructor or any block
are called instance variable.

The instance variable is initialized at the time of the class loading or when an object of the class is
created.

An instance variable can be declared using different access modifiers available in Java like default,
private, public, and protected.

Syntax:
class class_name
{

data_type variable; return_type method_name()


{

}
}

//Example program for instance variable


class Instancevar
{

int a=10;
public static void main(String[] args)
{

Instancevar var=new Instancevar();


System.out.println(var.a);
}
}

OUTPUT:
10

Static variable:
A variable which is declared with a static keyword is called a static variable. It is also called as a class
variable, because it is associated with a class.
Static variables are always declared inside the class but outside of any methods, constructors or any blocks.
Static variable will get the memory only once. If we changes the value of static variable, it will replace the
previous value and display the changed value, this is because it is constant for every object created.
Syntax:
class class_name
{

static data_type variable;


return_type method_name()
{

…………
………….
}
}

//Example program for static variable


class Staticvar
{

static int a=20;


public static void main(String[] args)
{

Staticvar obj=new Staticvar();


System.out.println(obj.a);
System.out.println(Staticvar.a);
}
}

OUTPUT:
10
10
//EXAMPLE 2
class StaticDemo
{
Static int count=0;
public void increment()
{
count++;
}
public static void main(String args[])
{
StaticDemo obj1=new StaticDemo ();
StaticDemo obj2=new StaticDemo ();
StaticDemo obj3=new StaticDemo ();
obj1.increment();
obj2.increment();
obj3.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
System.out.println("Obj3: count is="+obj3.count);
}
}
//program to demonstrate local, instance, and static variables
class Example
{

int a=10;
static int b=20;
void m()
{
int c=30;
int d=a+b+c;

System.out.println(d);
}

public static void main(String[] args)


{

Example e=new Example();


System.out.println(Example.b);
System.out.println(e.b);
e.m();
System.out.println(e.a);
}
}

OUTPUT:
20
20
60
10
Scope and life time of variable:
Scope Lifetime of variable

Local variable: Scope of local variable is within Execution time of block or


the block in which it is declared. Until the control leaves the
block in which it is declared.

Instance variable: Throughout the class except in Until the object stays in
Static methods. memory.

Static variable: Throughout the class Until the end of the program.

Data Types:
Data types specify the different sizes and values that can be stored in the variable. There are two types of data
types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double.
2. Non-primitive data types: The non-primitive data types include Classes, Interface, Strings and
Arrays.
● Why Java is strongly typed language?
Java is a strongly typed programming language because every variable must be declared with a data type.
Data Type Default Value Default size Range

byte 0 1 byte or 8 bits -128 to 127

short 0 2 bytes or 16 bits -32,768 to 32,767

2,147,483,648 to
int 0 4 bytes or 32 bits
2,147,483,647
9,223,372,036,854,775,808
long 0 8 bytes or 64 bits to
9,223,372,036,854,775,807

float 0.0f 4 bytes or 32 bits 1.4e-045 to 3.4e+038

double 0.0d 8 bytes or 64 bits 4.9e-324 to 1.8e+308

char ‘\u0000’ 2 bytes or 16 bits 0 to 65536

boolean FALSE 1 byte or 2 bytes 0 or 1

public class ExampleDataTypes


{
public static void main(String[] args) {
int myNum = 5; // integer (whole number)
float myFloatNum = 5.99f; // floating point number
char myLetter = 'D'; // character
boolean myBool = true; // boolean
String myText = "Hello"; // String
System.out.println(myNum);
System.out.println(myFloatNum);
System.out.println(myLetter);
System.out.println(myBool);
System.out.println(myText);
}
}
Note 1: Note that you should end the value with an "f" for float variables
Note 2: Note that you should end the value with a "d" for double variables
Example:
int num = 5;
float num1 = 5.99f;
double num3=5.7896d;
char ch = 'D';
boolean status = true;
String name = "java";
Non-Primitive Data Types
Non-primitive data types or reference data types refer to instances or objects.
They cannot store the value of a variable directly in memory.
They store a memory address of the variable.
Unlike primitive data types we define by Java, non-primitive data types are user-defined.
Programmers create them and can be assigned with null. All non-primitive data types are of equal size.

Key Characteristics:
 User-defined: Created by programmers to represent specific data structures.
 Reference variables: Instead of holding direct values, they hold references to memory locations
where the actual data is stored.
 Memory allocation: Typically allocated on the heap.
 Size: Not fixed, can vary depending on the data stored.
 Rich set of methods: Offer a wide range of operations through built-in methods.
Understanding with Examples:
// String (non-primitive)
String name = "Alice"; // Holds a reference to a String object

// Array (non-primitive)
int[] numbers = {1, 2, 3, 4, 5}; // Holds a reference to an integer array

// Class (non-primitive)
class Person
{
String name;
int age;
}
Person person1 = new Person(); // Creates a Person object
person1.name = "java";
person1.age = 10;

Formatted Output with printf()


 It is a method used to format output in Java.
 The printf method that has been adapted by Java from programming language C and modified and
upgraded. This method is easy and simple to use, and hence, it is more popular than other
methods.
Syntax
System.out.printf(format_string, argument_list);

The syntax of the method printf () method is as follows.

• format_string: A string containing plain text and format specifiers.


• argument_list: A list of arguments to be formatted and inserted into the format string.
Format Specifiers
Format specifiers begin with a percent sign (%) and are followed by a conversion character.
Conversion Character Description
d Integer
f Floating-point number
s String
c Character
b Boolean
n Platform-specific line separator
t date/time values.

//Example program to demonstrate formatted output


public class PrintfExample
{
public static void main(String[] args)
{
String name = "Alice";
int age = 30;
double salary = 50000.50;
System.out.printf("Name: %s, Age: %d, Salary: %.2f\n", name, age, salary);
}
}
Output:
Name: Alice, Age: 30, Salary: 50000.50

 %s: Format specifier for strings


 %d: Format specifier for integers
 %.2f: Format specifier for floating-point numbers with two decimal places

// Java Program to demonstrate use of


// printf() for formatting Date-time
import java.io.*;
import java.util.*;

// Driver Class
class Date_Time
{
// main function
public static void main(String[] args)
{
Date time = new Date();

System.out.printf("Current Time: %tT\n", time);

// Another Method with all of them Hour


// minutes and seconds seperated
System.out.printf("Hours: %tH Minutes: %tM Seconds: %tS\n", time, time, time);
}
}
Output
Current Time: 11:32:36
Hours: 11 Minutes: 32 Seconds: 36
Type conversion:
It is a process of converting a value from one data type to another data type. If the data types are compatible
then java can perform the conversion automatically or implicitly, If not they need to be casting explicitly.
Types of conversion:
1. Widening/implicit type conversion.
2. Narrowing/explicit type conversion.
Widening:
Converting a lower data type to a higher data type is known as widening. In this case the conversion is done
automatically also called as implicit type casting.
byte → short → int → long → float → double
//Program to demonstrate implicit type conversion
class TypeConversion
{
public static void main(String[] args)
{
int a=10;
long b=a;
float c=a;
System.out.println(“Integer value:” +a);
System.out.println(“long value:” +b);
System.out.println(“Float value:” +c);
}
}
Output:
Integer value: 10
long value:10
Float value:10.00
Narrowing:
Converting a higher data type to the lower data type is narrowing. In this case the casting or conversion is not
done automatically, user need to convert explicitly using the cast operator “( )”.
Therefore it is known explicit type casting.
double ← long ← float ← int ← short ← byte.
Syntax:
target datatype Variable_name(Type_name)variable;
//Program to demonstrate explicit type conversion
class TypeConversion
{
public static void main(String[] args)
{
double d=100.04;
long l=(long)d;
int i=(int)l;
System.out.println(“Double value:” +d);
System.out.println(“long value:” +l);
System.out.println(“Int value:” +i);
}
Output:
Double value: 100.04
long value: 100
Int value: 100
Static fields and methods:
Static is a keyword, it is used with class, variables, methods and block. It is mainly used for memory
management.
Static keyword belongs to the class instead of a specific instance of the class. Static can be accessed without
creating object.
The static can be:
• Variable
• Method
• Block
Static variable:
The static variable can be used to refer to the common property of all objects (which is not unique for each
object).
Advantages:
• It makes your program memory efficient (i.e., it saves memory).
//Java Program to demonstrate the use of static variable
class Student
{
//instance variable
int rollno;
String name;
//static variable
static String college ="RGM";
Student(int r, String n)
{
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[])
{
Student s1 = new Student(111,"abc");
Student s2 = new Student(222,"xyz");
s1.display();
s2.display();
}
}
Output:
111 abc RGM
222 xyz RGM
static method:
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than the object of a class. A static method can be invoked without
creating an instance(object) of a class.
A static method can access static data member and can change the value of it.
//Java Program to demonstrate the use of a static method
class Student
{
int rollno;
String name;
static String college = “RGM";
static void change()
{
college = "SREC";
}
Student(int r, String n)
{
rollno = r;
name = n;
}
void display()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[])
{
Student.change();
Student s1 = new Student(1,"abc"); Student s2 = new Student(2,"xyz"); Student s3 = new Student(3,"def");
s1.display();
s2.display();
s3.display();
}
}
Static Block:
It is used to initialize the static member.
It is executed before the main method at the time of classloading.
// example program for static block
class A
{
static
{
System.out.println(”static block is invoked”);
}
public static void main(String args[])
{
System.out.println(”main method”);
}
}
OUTPUT:
static block is invoked
main method

Formatted Output with printf()


It is a method used to format output in Java.
The printf method that has been adapted by Java from programming language C and modified and upgraded.
This method is easy and simple to use, and hence, it is more popular than other methods.
Syntax
System.out.printf(format_string, argument_list);
The syntax of the method printf () method is as follows.

 format_string: A string containing plain text and format specifiers.


 argument_list: A list of arguments to be formatted and inserted into the format string.
Format Specifiers
Format specifiers begin with a percent sign (%) and are followed by a conversion character.
Conversion Character Description
d Integer
f Floating-point number
s String
c Character
b Boolean
n Platform-specific line separator
t date/time values.
//Example program to demonstrate formatted output
public class PrintfExample
{
public static void main(String[] args)
{
String name = "Alice";
int age = 30;
double salary = 50000.50;
System.out.printf("Name: %s, Age: %d, Salary: %.2f\n", name, age, salary);
}
}
Output:
Name: Alice, Age: 30, Salary: 50000.50

 %s: Format specifier for strings


 %d: Format specifier for integers
 %.2f: Format specifier for floating-point numbers with two decimal places

// Java Program to demonstrate use of


// printf() for formatting Date-time
import java.io.*;
import java.util.*;

// Driver Class
class Date_Time {
// main function
public static void main(String[] args)
{
Date time = new Date();

System.out.printf("Current Time: %tT\n", time);


// Another Method with all of them Hour
// minutes and seconds seperated
System.out.printf("Hours: %tH Minutes: %tM Seconds: %tS\n", time, time, time);
}
}

Output
Current Time: 11:32:36
Hours: 11 Minutes: 32 Seconds: 36

Attribute Final:
Operators
An operator is a special symbol performing specific operations on operands. The operators are classified and listed
according to their precedence order. Java operators are generally used to manipulate primitive data types.
1. Arithmetic operator
2. Unary operator
3. Ternary operator
4. Assignment operator
5. Relational operator
6. Bitwise operator
7. Logical operator

Arithmetic operator:
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as basic
mathematical operations.
// Arithmetic Operator Example
class Arithmetic
{
public static void main(String[] args)
{
int a=1+1;
int b=a*3;
int c=b/4;
int d=c-a;
int e=42%10;
System.out.println(“a=”+a);
System.out.println(“b=”+b);
System.out.println(“c=”+c);
System.out.println(“d=”+d);
System.out.println(“e=”+e);
}
}
OUTPUT:
a=2
b=6
c=1
d=-1
e=2

Unary operator:
The ++ and – increment and decrement operators. The increment operator increases the operand value by 1 and the
decrement operator decreases the operand value by 1, these operators are unique in that they can appear both in
postfix and prefix forms. In the prefix form the operand is incremented or decremented before the value is
obtained. In the postfix form the previous value is obtained for the use in the expression and then the opearand is
modified.
Ex:
x=42 x=42
y=++x; y=x++;
O/P: y=43 O/P: y=42
//java program using unary operator
public class unaryop
{
public static void main(String[] args)
{
int r = 6;
System.out.println("r=: " + r++);
System.out.println("r=: " + r);
int x = 6;
System.out.println("x=: " + x--);
System.out.println("x=: " + x);
int y = 6;
System.out.println("y=: " + ++y);
int p = 6;
System.out.println("p=: " + --p);
}
}

Ternary Operator
The ternary operator is a conditional operator that decreases the length of code while performing
comparisons and conditionals. This method is an alternative for using if-else and nested if-else statements.
The order of execution for this operator is from left to right.

Syntax: Variable=condition? Statement 1: Statement 2

Condition: It is the expression to be evaluated which returns a boolean value. Statement 1: It is the
statement to be executed if the condition results in a true state.

Statement 2: It is the statement to be executed if the condition results in a false state.

//Example program
class Test

{
public static void main(String[] args)

int febdays=29;

String result;

result=(febdays==28) ? ”Not a leap year” : “leap year”;


System.out.println(“result”);

}
}

Output: Not a leap year


Assignment Operator: Assignment operator is used to combine an arithmetic operation using assignment.

public class Test

public static void main(String args[])

{
int a = 10;

int b = 20;

int c = 0;

c = a + b;

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

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

c -= a ;

System.out.println("c -= a = " + c );
c *= a ;

System.out.println("c *= a = " + c );
}

}
Relational Operator: These are used to compare two operands/ variables for equality, non equality, greater
than, less than, it always returns a Boolean value true or false.

//Example program for relational operator


class relational
{

public static void main(String[] args)

int a=10;
int b=20;

System.out.println(“a==b:” + a==b);

System.out.println(“a!=b:” + a!=b);

System.out.println(“a>b:” + a>b);

System.out.println(“a=b:” + a>=b);
System.out.println(“a<=b:” + a<=b);

Bitwise Operator: These are used to perform manipulation of individual bits of their operands. They can be
applied to the integer types long, int, short and byte.
Types of Bitwise Operator
Bitwise AND &
Bitwise exclusive OR ^
Bitwise inclusive OR |
Bitwise Compliment ~
Bitwise left shift <<
Bitwise right shift >>
Unsigned Right Shift Operator >>>

//BITWISE AND OPERATOR


public class BitwiseAndExample

{
public static void main(String[] args)

{
int x = 9, y = 8; // bitwise and
System.out.println("x & y = " + (x & y)); // 1001 & 1000 = 1000 = 8
}

OUTPUT:

x&y =8

//BitwiseXorExample
public class BitwiseXorExample

public static void main(String[] args)


{

int x = 9, y = 8; // bitwise XOR // 1001 ^ 1000 = 0001 = 1 System.out.println("x ^ y = " + (x ^ y));

OUTPUT:
x^y=1

//BitwiseInclusiveOrExample
public class BitwiseInclusiveOrExample
{

public static void main(String[] args)


{

int x = 9, y = 8; // bitwise inclusive OR

System.out.println("x | y = " + (x | y)); // 1001 | 1000 = 1001 = 9


}

OUTPUT:
x|y=9
//Write a program for Bitwise Operators.

class BitwiseOp

public static void main(String[] args)

{
int a=60;

int b=13;

int c;

System.out.println(“a&b:” +c);

System.out.println(“a|b:” +c);
System.out.println(“a^b:” +c);

c=~a;

System.out.println(“~a:” +c);

c=a>>2;
System.out.println(“a>>2:” +c);

c=a<<>>2;

System.out.println(“a>>>2:” +c);

Unsigned right operator:


Shifting the bits of a number towards right, a specified ‘n’ no. of positions.
Example:

If a=11110000 and b=2, find a>>>b?

a >>> b = 11110000 >>> 2 = 00111100


The left operand value is moved right by the number of bits specified by the right operand and the shifted
bits are filled up with zeros. Excess bits shifted off to the right are discarded. Therefore, before shifting the
bits the decimal value of a is 240, and after shifting the bits the decimal value of a is 60
//RightShiftOperatorExample
public class SignedRightShiftOperatorExample

public static void main(String args[])

int x = 50;
System.out.println("x>>2 = " + (x >>2));

OUTPUT:
x>>2=12

//Write a program to demonstrate bitwise shifting operators.


class OperatorShifting

{
public static void main(String[] args)

byte x,y;

x=10;

y=-10;
System.out.println(“Bitwise leftshift: x<<>2 =”+(x>>2));

System.out.println(“Bitwise unsigned rightshift: x>>>2 =”+(x>>>2));


System.out.println(“Bitwise unsigned rightshift: y>>>2 =”+(y>>>2));

Logical Operators
Logical operators are used to check whether an expression is true or false. They are used in decision making.

Operators
&& (Logical AND)
|| (Logical OR)

! (Logical NOT)
//Write a program for logical operators AND, OR, NOT
class Main

public static void main(String[] args)


{ // && operator

System.out.println((5 > 3) && (8 > 5)); // true

System.out.println((5 > 3) && (8 < 5)); // false

// || operator

System.out.println((5 < 3) || (8 > 5)); // true


System.out.println((5 > 3) || (8 < 5)); // true

System.out.println((5 < 3) || (8 < 5)); // false

// ! operator

System.out.println(!(5 == 3)); // true


System.out.println(!(5 > 3)); // false

Precedence and Associativity of Operators


• Precedence: This determines the order in which operators are evaluated in an expression.
Operators with higher precedence are evaluated before those with lower precedence.

• Associativity: This defines the order in which operators of the same precedence are evaluated.
It can be left-to-right or right-to-left.

Operator Associativity

++, -- (pre-increment, pre-decrement) Right-to-left

++, -- (post-increment, post-decrement) Left-to-right

!, ~ (logical NOT, bitwise complement) Right-to-left

*, /, % (multiplication, division, modulus) Left-to-right

+, - (addition, subtraction) Left-to-right


<<, >>, >>> (shift operators) Left-to-right

<, <=, >, >= (comparison operators) Left-to-right

==, != (equality operators) Left-to-right

& (bitwise AND) Left-to-right

^ (bitwise XOR) Left-to-right

` ` (bitwise OR)

&& (logical AND) Left-to-right

` ` (logical OR)

?: (ternary operator) Right-to-left

= (assignment operator) Right-to-left

Example
Consider the expression: int result = 5 + 3 * 2;

According to the precedence table:

1. Multiplication (*) has higher precedence than addition (+).

2. So, 3 * 2 is evaluated first, resulting in 6.


3. Then, 5 is added to 6, giving 11.
4. Finally, 11 is assigned to the result variable.

//EXAMPLE
public class OperatorPrecedenceExample

{
public static void main(String[] args) { int a = 5, b = 3, c = 2;

// Example 1: Precedence

int result1 = a + b * c; // Output: 11 System.out.println("Result 1: " + result1);

// Example 2: Associativity
int result2 = a = b = c; // Output: 2
System.out.println("Result 2: " + result2);

// Example 3: Parentheses to override precedence

int result3 = (a + b) * c; // Output: 16 System.out.println("Result 3: " + result3);


}
}

Note:

• Precedence determines the order in which operators are evaluated.

• Associativity determines the order of evaluation when operators have the same precedence.

• Parentheses can be used to explicitly control the order of evaluation.

Control statements
Control statements is one of the fundamentals required for programming. It determines which statement to
execute, and it controls the flow of execution of the program. Statements can be executed multiple times or
only under a specific condition.

(or)
The default execution flow of a program is a sequential order. But the sequential
order of execution flow may not be suitable for all situations. Sometimes, we may
want to jump from line to another line, we may want to skip a part of the program,
or sometimes we may want to execute a part of the program again and again. To

solve this problem, java provides control statements.

The ”selection” statements are used for testing conditions, the “ iteration” statements are used to create
cycles, and the jump statements is used to alter a loop.

Control statements can be divided into the following categories:


1. Selection statements(Decision making statements)
2. Iteration statements(Loop statements)

3. Jump statements(Branching statements)


Simple if statement: It instructs the program to execute only certain part of the code if the condition is true.
The Boolean value is true then statement will be executed.

Syntax:
if(condition)

{
statement; //executes when condition is true

// example program for Simple if condition statement


public class Student
{

public static void main(String[] args)

int x = 10;

int y = 12;
if(x+y > 20)

System.out.println("x + y is greater than 20");

}
}

if-else statement:
The if-else statement is an extension to the if statement, which uses another block of code, i.e., else block.
The else block is executed if the condition of the if block is evaluated as false.

Syntax:
if(condition)

statement 1; //executes when condition is true


}

else
{

statement 2; //executes when condition is false


}
//Write a java program for if-else condition statement
class ifelse

public static void main(String args[])

{
int a=15;

if(a>20)

System.out.println(“a is greater than 10”);

}
else

System.out.println(“a is less than 10”);

}
}

if-else-if ladder statement:


The if-else-if statement contains the if statement followed by multiple else-if statements. It is used to decide
among multiple options.

Syntax:
if(condition 1)
{

statement 1; //executes when condition 1 is true

else if(condition 2)

{
statement 2; //executes when condition 2 is true
}

else
{
statement 2; //executes when all the conditions are false

//program for if-else-if ;adder condition statement

public class Student

public static void main(String[] args)

String city = "Delhi";


if(city == "Meerut")

System.out.println("city is meerut");

}
else if (city == "Noida")

System.out.println("city is noida");

else if(city == "Agra")

{
System.out.println("city is agra");

else
{

System.out.println(city);

}
}
}
Iteration Statements
• An iteration statement, or loop, repeatedly executes a statement, known as the loop body, until the
controlling expression is false (0).

The while statement evaluates the control expression before executing the loop body.

The do statement evaluates the control expression after executing the loop body; at least one execution of
the loop body is guaranteed.

The for statement executes the loop body based on the evaluation of the second of three expressions

Syntax :
while (boolean condition)

loop statements...

//Example
import java.io.*;

class WhileExample
{

public static void main (String[] args) {

int i=0;

while (i<=10)

{
System.out.println(i);

i++;

}
for loop:
Syntax:
for (initialization condition; testing condition;increment/decrement)

statement(s)

//Example
import java.io.*;

class ForExample
{

public static void main (String[] args)

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


{

System.out.println(i);

do while:

Syntax:
do
{

statements..

}
while (condition);
//Example
import java.io.*;

class DoWhileEx

public static void main (String[] args)

{
int i=0;

do

System.out.println(i);

i++;
}

while(i<=10);

• Nested Loop:
• Nested loop means a loop statement inside another loop statement.

• There are different combinations of loop using for loop, while loop, do-while loop.

//Nested for loop

import java.io.*;

class NestedFor

{
public static void main (String[] args)
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 2; j++)
{
System.out.println(i);
}
System.out.println();
}
}
}
For-each loop
• A for-each loop is a simplified way to iterate through elements in an array.

Syntax:
for (data_type variable : array)

// code to be executed for each element


}

Example:

public class ForEachLoopExample


{

public static void main(String[] args)

// Array of numbers
int[] numbers = {1, 2, 3, 4, 5};

// Iterate through the array using for-each loop

for (int number : numbers)

System.out.println(number);
}
}

Simple program with for each loop:


import java.io.*;
class Easy

{
public static void main(String[] args)

{
// array declaration
int ar[] = { 10, 50, 60, 80, 90 };
for (int element : ar)

System.out.print(element + " ");

Continue Statement
• Statement is often used inside in programming languages inside loops control structures. Inside the
loop, when a continue statement is encountered the control directly jumps to the beginning of the
loop for the next iteration instead of executing the statements of the current iteration.

Syntax:
continue;

// Java Program to illustrate the use of continue statement


import java.util.*;

public class ContinueEx {

// Main driver method

public static void main(String args[])

{
// For loop for iteration

for (int i = 0; i <= 15; i++) {

// Check condition for continue

if (i == 10 || i == 12) {

// Using continue statement to skip the


// execution of loop when i==10 or i==12
continue;

// Printing elements to show continue statement


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

Break statement
• Break Statement is a loop control statement that is used to terminate the loop. As soon as the break
statement is encountered from within a loop, the loop iterations stop there, and control returns from the
loop immediately to the first statement after the loop.

Syntax:
break;

//Example
public class BreakExample

public static void main(String[] args)

{
for (int i = 1; i <= 10; i++)

System.out.println(i);

if (i == 5)

{
break; // Terminates the loop when i becomes 5

System.out.println("Loop is terminated.");

}
}

You might also like