0% found this document useful (0 votes)
7 views40 pages

Unit-I Notes - Java

Uploaded by

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

Unit-I Notes - Java

Uploaded by

kamesh-bsccs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

SRM Institute of Science and Technology

College of Science and Humanities

Java Programming
(A study material for M.C.A First Year)

Compiled by
Dr. M.Sivasakthi Ph.D., NET
USA20301J - PROGRAMMING IN JAVA
Unit-I Notes

The Genesis of Java

When the chronicle of computer languages is written, the following will be said: B led to
C, C evolved into C++, and C++ set the stage for Java.

Java is related to C++, which is a direct descendent of C. Much of the character of Java
is inherited from these two languages. From C, Java derives its syntax. Many of Java's
Object-oriented features were influenced by C++.

Birth of C programming

The need for C++

The creation of Java: Java was conceived by James Gosling, Patrick Naughton, Chris Warth,
Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop
the first working version. This language was initially called "Oak" but was renamed "Java" in
1995. Between the initial implementation of Oak in the fall of 1992 and the public announcement
of Java in the spring of 1995.

The trouble with C and C++ (and most other languages) is that they are designed to be compiled
for a specific target. Although it is possible to compile a C++ program for just about any type of
CPU, to do so requires a full C++ compiler targeted for that CPU. The problem is that compilers
are expensive and time-consuming to create. An easier—and more cost-efficient—solution was
needed. In an attempt to find such a solution, Gosling and others began work on a portable,

2|Page
platform-independent language that could be used to produce code that would run on a variety of
CPUs under differing environments. This effort ultimately led to the creation of Java.

How Java changed the Internet

Java has had a profound effect on the Internet. The reason for this is quite simple: Java expands
the universe of objects that can move about freely in cyberspace. In a network, two very broad
categories of objects are transmitted between the server and your personal computer:

i) Passive information
ii) Dynamic, active programs.

For example, when you read your e-mail, you are viewing passive data. Even when you
download a program, the program's code is still only passive data until you execute it. However,
a second type of object can be transmitted to your computer: a dynamic, self-executing program.
Such a program is an active agent on the client computer, yet is initiated by the server. For
example, a program might be provided by the server to display properly the data that the server is
sending.

As desirable as dynamic, networked programs are, they also present serious problems in the
areas of security and portability. Prior to Java, cyberspace was effectively closed to half the
entities that now live there. As you will see, Java addresses those concerns and, by doing so, has
opened the door to an exciting new form of program: the applet.

Java can be used to create two types of programs: applications and applets. An application is a
program that runs on your computer, under the operating system of that computer. An applet is
an application designed to be transmitted over the Internet and executed by a Java-compatible
Web browser

3|Page
Java's Magic: The Bytecode

output of a Java compiler is not executable code. Rather, it is bytecode. Bytecode is a highly
optimized set of instructions designed to be executed by the Java run-time system, which is
called the Java Virtual Machine (JVM).

Translating a Java program into bytecode helps makes it much easier to run a program in
a wide variety of environments.

The fact that a Java program is interpreted also helps to make it secure. Because the execution of
every Java program is under the control of the JVM.

Understanding Java Buzzwords

• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed

4|Page
• Dynamic

Simple - similarities with C/C++, Java is easy to learn

Secure - Java programs run inside a virtual machine,


Java does not support explicit pointer,
It provides java.security package implements explicit security

Portable- Java code can execute on all major platforms

Object-oriented- everything in java is an object oriented paradigm

Robust - consider two of the main reasons for program failure:


i) memory management mistakes(Java provides garbage collection for memory
deallocation)
ii) mishandled exceptional conditions (Java provides object-oriented exception
handling).
Multithreaded - Java supports multithreaded programming, which allows you to write programs
that do many things simultaneously.

Architecture-neutral- no guarantee exists that if you write a program today, it will run
tomorrow—even on the same machine. Operating system upgrades, processor upgrades, and
changes in core system resources can all combine to make a program malfunction. The Java
designers made several hard decisions in the Java language and the Java Virtual Machine in an
attempt to alter this situation. Their goal was "write once; run anywhere, any time, forever."

Interpreted- Java bytecode can be interpreted on any system that provides a Java Virtual
Machine.

High performance- Java bytecode was carefully designed so that it would be easy to translate
directly into native machine code for very high performance by using a just-in-time compiler.

5|Page
Distributed - Java is designed for the distributed environment of the Internet, because it handles
TCP/IP protocols. Java has revived a package called Remote Method Invocation (RMI).

Dynamic - Java programs carry with them substantial amounts of run-time type information that
is used to verify and resolve accesses to objects at run time.

Evolution of Java

History of Java.

1) James Gosling, Mike Sheridan, and Patrick


Naughton initiated the Java language project in June 1991. The
small team of sun engineers called Green Team.

2) Initially it was designed for small, embedded systems in


electronic appliances like set-top boxes.

3) Firstly, it was called "Greentalk" by James Gosling, and the file


extension was .gt.

4) After that, it was called Oak and was developed as a part of the Green project.
Why Java was named as "Oak"?

5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like
the U.S.A., France, Germany, Romania, etc.

6|Page
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.

Why Java Programming named "Java"?

Why had they chose the name Java for Java language? The team gathered to choose a new name.
The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They wanted
something that reflected the essence of the technology: revolutionary, dynamic, lively, cool,
unique, and easy to spell, and fun to say.

According to James Gosling, "Java was one of the top choices along with Silk". Since Java was
so unique, most of the team members preferred Java than other names.

Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a
kind of espresso bean. Java name was chosen by James Gosling while having a cup of coffee
nearby his office.

Notice that Java is just a name, not an acronym.

Java Version History

1. JDK Alpha and Beta (1995)


2. JDK 1.0 (23rd Jan 1996)
3. JDK 1.1 (19th Feb 1997)
4. J2SE 1.2 (8th Dec 1998)
5. J2SE 1.3 (8th May 2000)
6. J2SE 1.4 (6th Feb 2002)
7. J2SE 5.0 (30th Sep 2004)
8. Java SE 6 (11th Dec 2006)
9. Java SE 7 (28th July 2011)
10. Java SE 8 (18th Mar 2014)
11. Java SE 9 (21st Sep 2017)

7|Page
12. Java SE 10 (20th Mar 2018)
13. Java SE 11 (September 2018)
14. Java SE 12 (March 2019)
15. Java SE 13 (September 2019)
16. Java SE 14 (Mar 2020)
17. Java SE 15 (September 2020)
18. Java SE 16 (Mar 2021)
19. Java SE 17 (September 2021)
20. Java SE 18 (to be released by March 2022)

Introduction to Object Oriented Concepts of Java

Object-Oriented Programming is a paradigm that provides many concepts, such as encapsulation,


inheritance, polymorphism, etc.
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It
simplifies software development and maintenance by providing some concepts:
o Object
o Class
o Abstraction
o Encapsulation
o Polymorphism
o Inheritance

Understanding the Encapsulation, Polymorphism, Inheritance


Encapsulation
As Shown in the figure, Encapsulation is defined
as the wrapping up of data and function under a
single unit. It is the mechanism that binds
together function and the data it manipulates.
Another way to think about encapsulation is, that
it is a protective shield that prevents the data from

8|Page
being accessed by the code outside this shield.

Encapsulation can be achieved by declaring all the variables in the class as private and writing
public methods in the class to set and get the values of variables.

Example:

Example:

// fields to calculate area


class Area {

int length;
int breadth;

// constructor to initialize values


Area(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}

// method to calculate area

9|Page
public void getArea() {
int area = length * breadth;
System.out.println("Area: " + area);
}}
class Main {
public static void main(String[] args) {

Area rectangle = new Area(2, 16);


rectangle.getArea();
}}
Advantages of Encapsulation
 Data Hiding
 Increased Flexibility
 Reusability
 Testing code is easy

Polymorphism

The word “poly” means many and “morphs” means forms, So it means many forms. we can define
polymorphism as the ability to take more than one form. For Example a person at the same time can
have different characteristics. Like a man at the same time is a father, a husband, an employee. So the
same person possesses different behavior in different situations. This is called polymorphism.

Example

10 | P a g e
Example:

Types of polymorphism

 Compile-time Polymorphism (It is also known as static polymorphism. This type of


polymorphism is achieved by method overloading )

Example

// Java Program for Method overloading


// By using Different Types of Arguments

// Class 1
// Helper class
class Helper {

// Method with 2 integer parameters


static int Multiply(int a, int b)
{

// Returns product of integer numbers


return a * b;
}

11 | P a g e
// Method 2
// With same name but with 2 double parameters
static double Multiply(double a, double b)
{

// Returns product of double numbers


return a * b;
}
}

// Class 2
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Calling method by passing


// input as in arguments
System.out.println(Helper.Multiply(2, 4));
System.out.println(Helper.Multiply(5.5, 6.3));
}
}

Output:
8
42

 Runtime Polymorphism

12 | P a g e
It is also known as Dynamic Method Dispatch. It is a process in which a function call to the
overridden method is resolved at Runtime. This type of polymorphism is achieved by Method
Overriding. Method overriding, on the other hand, occurs when a derived class has a definition for
one of the member functions of the base class. That base function is said to be overridden.

Example:

// Java Program for Method Overriding

// Class 1
// Helper class
class Parent {

// Method of parent class


void Print()
{
// Print statement
System.out.println("parent class");
}
}
// Class 2
// Helper class
class subclass1 extends Parent {
// Method
void Print() { System.out.println("subclass1"); }
}
// Class 3
// Helper class
class subclass2 extends Parent {
// Method
void Print()
{

13 | P a g e
// Print statement
System.out.println("subclass2");
}
}
// Class 4
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating object of class 1
Parent a;
// Now we will be calling print methods
// inside main() method

a = new subclass1();
a.Print();

a = new subclass2();
a.Print();
}
}
Output:
subclass1
subclass2

Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of
a parent object.
Example:

14 | P a g e
The reason for using inheritance in java
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.
Terminologies
 Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
 Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.

The syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}

Java Inheritance Example

15 | P a g e
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

16 | P a g e
Types of inheritance in java

Lexical Issues

Lexical meaning: relating to the words or vocabulary of a language.

Java programs are a collection of whitespace, identifiers, comments, literals, operators,


separators, and keywords.

17 | P a g e
Whitespace

program could have been written all on one line or in any other strange way you felt like typing it, as long as there
was at least one whitespace character between each token that was not already delineated by an operator or
separator. In Java, whitespace is a space, tab, or newline.

Identifiers

Identifiers are used for class names, method names, and variable names. An identifier may be any descriptive
sequence of uppercase and lowercase letters, numbers, or the underscore and dollar-sign characters. They must not
begin with a number, lest they be confused with a numeric literal. Again, Java is case-sensitive, so VALUE is a
different identifier than Value.

Some examples of valid identifiers are:


AvgTemp
count
a4
$test
this_is_ok

Invalid variable names include:

2count
high temp
Not/ok

Literals
A constant value in Java is created by using a literal representation of it. For example,
here are some literals: 100 98.6 'X' "This is a test"

Comments

18 | P a g e
there are three types of comments defined by Java. You have already seen two: single-line and multiline. The third
type is called a documentation comment. This type of comment is used to produce an HTML file that documents
your program. The documentation comment begins with a /** and ends with a */.

Separators
In Java, there are a few characters that are used as separators. The most commonly

used separator in Java is the semicolon, The other separators are () {} [ ] , .

Keywords

Keywords are the reserved word These keywords cannot be used as names for a variable,
class, or method.

DATA TYPES

Java defines eight simple (or elemental) types of data: byte, short, int, long, char, float,double, and
boolean. These can be put in four groups:

19 | P a g e
Integers This group includes byte, short, int, and long, which are for whole valued signed numbers.

Floating-point numbers This group includes float and double, which represent numbers with fractional precision.

Characters This group includes char, which represents symbols in a character set, like letters and numbers.

Boolean This group includes boolean, which is a special type for representing true/false values.

Integers
Java defines four integer types: byte, short, int, and long. All of these are signed, positive and
negative values. Java does not support unsigned, positive-only integers. Many other Computer
languages, including C/C++, support both signed and unsigned integers.

Name Width Range


long 64 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int 32 –2,147,483,648 to 2,147,483,647
short 16 –32,768 to 32,767
byte 8 –128 to 127

byte
The smallest integer type is byte. This is a signed 8-bit type that has a range from –128to
127. Variables of type byte are especially useful when you’re a network or file. They are also
usefulnotbe when directly compatible-intypeswith. Java’s other built
Syntax: byte b, c;

short
short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the least-used Java
type, since it is defined as having its high byte first (called big-endian format). This type is mostly
applicable to 16-bit computers, which are becoming increasingly scarce.
Here are some examples of short variable declarations: short s;
short t;

20 | P a g e
int

The most commonly used integer type is int. It is a signed 32-bit type that has a range from –
2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int are commonly
employed to control loops and to index arrays. Any time you have an integer expression involving
bytes, shorts, ints, and literal numbers, the entire expression Is promoted to int before the
calculation is done.

long

long is a signed 64-bit type and is useful for those occasions where an int type is notlarge enough to
hold the desired value. The range of a long is quite large. This makesit useful when big, whole
numbers are needed. For example, here is a program thatcomputes the number of miles that light will
travel in a specified number of days.

Floating-Point Types

Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional
precision. For example, calculations such as square root, or transcendentals such as sine and cosine, result in a value
whose precision requires a floating-point type.

Name Width in Bits Range


double 64 1.7e–308 to 1.7e+308
float 32 3.4e–038 to 3.4e+038

float
The type float specifies a single-precision value that uses 32 bits of storage. Single precision is faster on some
processors and takes half as much space as double precision, but will become imprecise when the values are either
very large or very small.

float hightemp, lowtemp;

21 | P a g e
double
Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually
faster than single precision on some modern processors that have been optimized for high-speed mathematical
calculations.

Characters
In Java, the data type used to store characters is char. However, C/C++ programmers beware: char in Java is not the
same as char in C or C++. In C/C++, char is an integer type that is 8 bits wide. This is not the case in Java. Instead,
Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all of
the characters found in all human languages.

in Java char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars. The standard set of
characters known as ASCII still ranges from 0 to 127 as always,

Booleans
Java has a simple type, called boolean, for logical values. It can have only one of two possible values, true or false.
This is the type returned by all relational operators, such as a < b. boolean is also the type required by the
conditional expressions that govern the control statements such as if and for.

boolean b;

Variables

Variable is nothing but name of the memory location

Declaring a Variable

In Java, all variables must be declared before they can be used. The basic form of a
variable declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;

int a, b, c; // declares three ints, a, b, and c.


int d = 3, e, f = 5; // declares three more ints, initializing
// d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.

22 | P a g e
char x = 'x'; // the variable x has the value 'x'.

Dynamic Initialization

Java allows variables to be initialized dynamically, using any expression valid at the time the variable
is declared.

For example, here is a short program that computes the length of the hypotenuse of a
right triangle given the lengths of its two opposing sides:

// Demonstrate dynamic initialization.


class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
Here, three local variables—a, b,and c—are declared. The first two, a and b, are
initialized by constants. However, c is initialized dynamically to the length of the
hypotenuse (using the Pythagorean theorem).

The Scope and Lifetime of Variables

Scope of a variable determines the area or a region of code where a variable is available to use.
Lifetime of a variable is defined by the time for which a variable occupies some valid space in the
system's memory. Scope determines the life of a variable. Life of a variable depends on the scope.

The scope defined by a method begins with its opening curly brace. However, if that method has parameters, they
too are included within the method's scope.

As a general rule, variables declared inside a scope are not visible (that is, accessible) to code that is defined outside
that scope. Thus, when you declare a variable within a scope, you are localizing that variable and protecting it from
unauthorized access and/or modification. Indeed, the scope rules provide the foundation for encapsulation.

23 | P a g e
Scopes can be nested. Example for block scope

class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}

Here is another important point to remember: variables are created when their scope is entered, and destroyed when
their scope is left. This means that a variable will not hold its value once it has gone out of scope. Therefore,
variables declared within a method will not hold their values between calls to that method. Also, a variable declared
within a block will lose its value when the block is left. Thus, the lifetime of a variable is confined to its scope.

// Demonstrate lifetime of a variable.


class LifeTime {
public static void main(String args[]) {
int x;
for(x = 0; x < 3; x++) {
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}
The output generated by this program is shown here:
y is: -1
y is now: 100

24 | P a g e
y is: -1
y is now: 100
y is: -1
y is now: 100

Operators in Java

Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Conditional Operators

Arithmetic Operators

Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

++ Increment Increases the value of a variable by 1 ++x

25 | P a g e
-- Decrement Decreases the value of a variable by 1 --x

Relational Operators

Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Logical Operators

Operator Name Description Example

&& Logical and Returns true if both statements are true x < 5 && x < 10

|| Logical or Returns true if one of the statements is true x < 5 || x < 4

! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)

Bitwise Operators

Operator Description Example

& (bitwise Binary AND Operator copies a bit to the result (A & B) will give 12 which is

26 | P a g e
and) if it exists in both operands. 0000 1100

Binary OR Operator copies a bit if it exists in (A | B) will give 61 which is


| (bitwise or)
either operand. 0011 1101

^ (bitwise Binary XOR Operator copies the bit if it is set (A ^ B) will give 49 which is
XOR) in one operand but not both. 0011 0001

(~A ) will give -61 which is


~ (bitwise Binary Ones Complement Operator is unary 1100 0011 in 2's complement
compliment) and has the effect of 'flipping' bits. form due to a signed binary
number.

Binary Left Shift Operator. The left operands


A << 2 will give 240 which is
<< (left shift) value is moved left by the number of bits
1111 0000
specified by the right operand.

Binary Right Shift Operator. The left operands


A >> 2 will give 15 which is
>> (right shift) value is moved right by the number of bits
1111
specified by the right operand.

Shift right zero fill operator. The left operands


>>> (zero fill value is moved right by the number of bits A >>>2 will give 15 which is
right shift) specified by the right operand and shifted 0000 1111
values are filled up with zeros.

Assignment Operators

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

27 | P a g e
-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Conditional Operators

Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to decide,
which value should be assigned to the variable.

The operator is written as

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

Array

An array is a group of like-typed variables that are referred to by a common name. Arrays
of any type can be created and may have one or more dimensions. A specific element in
an array is accessed by its index.
One-Dimensional Arrays

28 | P a g e
The general form of a one dimensional array declaration is

type var-name[ ];

Example:

int month_days[];

The general form of new as it applies to one-dimensional arrays appears as follows:

array-var = new type[size];

Example:
month_days = new int[12];

Example Program

class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}

29 | P a g e
}

Multidimensional Arrays

int twoD[][] = new int[4][5];

Example Program

class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}

This program generates the following output:

01234

30 | P a g e
56789
10 11 12 13 14
15 16 17 18 19

Control Statements

if Statement

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

Example
public class Test {

public static void main(String args[]) {


int x = 10;

if( x < 20 ) {
System.out.print("This is if statement");
}
}
}

if-else statement

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

Example

31 | P a g e
public class Test {

public static void main(String args[]) {


int x = 30;

if( x < 20 ) {
System.out.print("This is if statement");
}else {
System.out.print("This is else statement");
}
}
}

Nested if

if(Boolean_expression 1) {
// Executes when the Boolean expression 1 is true
if(Boolean_expression 2) {
// Executes when the Boolean expression 2 is true
}
}

Example

public class Test {

public static void main(String args[]) {


int x = 30;
int y = 10;

if( x == 30 ) {
if( y == 10 ) {
System.out.print("X = 30 and Y = 10");
}
}

32 | P a g e
}
}

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

Syntax

switch(expression) {
case value :
// Statements
break; // optional

case value :
// Statements
break; // optional

// You can have any number of case statements.


default : // Optional
// Statements
}

Example

public class Test {

public static void main(String args[]) {


// char grade = args[0].charAt(0);
char grade = 'C';

switch(grade) {

33 | P a g e
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}

Looping Statements
while loop
A while loop statement in Java programming language repeatedly executes a target statement as long
as a given condition is true.
while(Boolean_expression) {
// Statements
}

Example
public class Test {

public static void main(String args[]) {


int x = 10;

while( x < 20 ) {
System.out.print("value of x : " + x );

34 | P a g e
x++;
System.out.print("\n");
}
}
}

Output:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

for loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to be
executed a specific number of times.
for(initialization; Boolean_expression; update) {
// Statements
}

Example
public class Test {

public static void main(String args[]) {

for(int x = 10; x < 20; x = x + 1) {


System.out.print("value of x : " + x );
System.out.print("\n");
}
}

35 | P a g e
}

Output
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

do...while loop
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.
Syntax
do {
// Statements
}while(Boolean_expression);

Example
public class Test {

public static void main(String args[]) {


int x = 10;

do {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}

36 | P a g e
Output
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

Jumping Statements

Using Break Statement to exit a loop

In java, the break statement is used to terminate the execution of the nearest looping statement
or switch statement. The break statement is widely used with the switch
statement, for loop, while loop, do-while loop.
Syntax:
break;

// Java program to illustrate the

37 | P a g e
// break keyword in Java
import java.io.*;

class GFG {
public static void main(String[] args)
{
int n = 10;
for (int i = 0; i < n; i++) {
if (i == 6)
break;
System.out.println(i);
}
}
}
Output
0
1
2
3
4
5

Continue Statements
The continue statement pushes the next repetition of the loop to take place, hopping any code
between itself and the conditional expression that controls the loop.

// Java program to illustrate the


// continue keyword in Java
import java.io.*;

class GFG {

38 | P a g e
public static void main(String[] args)
{
for (int i = 0; i < 10; i++) {
if (i == 6){
System.out.println();
// using continue keyword
// to skip the current iteration
continue;
}
System.out.println(i);
}
}
}

Output
0
1
2
3
4
5

7
8
9

return statement
A return statement causes the program control to transfer back to the caller of a method. Every
method in Java is declared with a return type and it is mandatory for all java methods. A return type
may be a primitive type like int, float, double, a reference type or void type(returns nothing).

Example

39 | P a g e
public class ReturnTypeTest2 {
public int add(int x, int y) { // with arguments
int z = x+y;
return z;
}
public static void main(String args[]) {
ReturnTypeTest2 test = new ReturnTypeTest2();
int add = test.add(10, 20);
System.out.println("The sum of x and y is: " + add);
}
}

Output
The sum of x and y is: 30

40 | P a g e

You might also like