Вы находитесь на странице: 1из 118

Features of JAVA

1st Unit

Mr. R. M. Patil
SY CO, JPR
2019-2020
1.1
Features
of
JAVA

or

JAVA
buzzwords
1. Simple
Java is very easy to learn, and its syntax is simple, clean
and easy to understand.

 Java syntax is based on C++ (so easier for programmers


to learn it after C++).

 Java has removed many complicated and rarely-used


features, for example, explicit pointers, operator
overloading, etc.

 There is no need to remove unreferenced objects


because there is an Automatic Garbage Collection in Java.
2. Object - Oriented
Java is an object-oriented programming language.
Everything in Java is an object.
Object-oriented means we organize our software as a
combination of different types of objects that incorporates
both data and behavior.
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
3. Platform Independent
Java is platform independent because it is different from
other languages like C, C++, etc. which are compiled into
platform specific machines while Java is a write once, run
anywhere language.
4. Secured
Java is best known for its security.

With Java, we can develop virus-free systems.

Java is secured because:

 No explicit pointer

 Java Programs run inside a virtual machine


sandbox
4. Secured

 Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE)


which is used to load Java classes into the Java Virtual Machine dynamically.
 Bytecode Verifier: It checks the code fragments for illegal code that can violate
access right to objects.
 Security Manager: It determines what resources a class can access such as
reading and writing to the local disk.
5. Robust
Robust simply means strong.
Java is robust because:
 It uses strong memory management.
 There is a lack of pointers that avoids security
problems.
 There is automatic garbage collection in java which
runs on the Java Virtual Machine to get rid of objects
which are not being used by a Java application anymore.

 There are exception handling and the type checking


mechanism in Java. All these points make Java robust.
6. Architecture-neutral
Java is architecture neutral because there are no
implementation dependent features,
for example, the size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of


memory for 32-bit architecture and 4 bytes of memory for
64-bit architecture.

However, it occupies 4 bytes of memory for both 32 and 64-


bit architectures in Java.
7. Portable
Java is portable because it facilitates you to carry the Java
bytecode to any platform.

It doesn't require any implementation.

8. High Performance
Java is faster than other traditional interpreted programming
languages because Java bytecode is "close" to native code.

It is still a little bit slower than a compiled language (e.g.,


C++). Java is an interpreted language that is why it is slower
than compiled languages, e.g., C, C++, etc.
9. Distributed
Java is distributed because it facilitates users to create
distributed applications in Java. Some methods are used for
creating distributed applications. This feature of Java makes
us able to access files by calling the methods from any
machine on the internet.
10. Multi-threaded
A thread is like a separate program, executing concurrently.

We can write Java programs that deal with many tasks at


once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each
thread. It shares a common memory area.
11. Dynamic
Java is a dynamic language. It supports dynamic loading of
classes. It means classes are loaded on demand.

Java supports dynamic compilation and automatic memory


management (garbage collection).
JAVA Programming Environment

 The JAVA Environment is made up of three things –


Development tools, classes and methods, JAVA
runtime environment.

 The JAVA development tools constitute JDK.

 The classes and methods are called Application


Programming Interface (API).

 The JAVA runtime environment is supported by


JVM.
JAVA Programming Environment : 1. JDK
 The Java Development Kit (JDK) is a software
development environment used for developing Java
applications and applets.

 It consists of :
- javac : JAVA Compiler
- java : JAVA interpreter
- javadoc : Creating HTML Documents
- javah : Produces Header Files
- jdb : JAVA Debugger
-appletviewer : Execute Applet
- javap : Convert byte code to program description
JAVA Programming Environment : 1. JDK
Text Editor
Commenting Source Program

JAVA Prog. javadoc HTML files

javac Compilation

Java class
javah Header Files
file
Debugging
java jdb
Execution

Java Prog.
Output Fig. Execution Process of application program
JAVA Programming Environment : 2. JVM
 The Java Virtual Machine (JVM) is a software and
program components.
JAVA Programming Environment : 2. JVM – How Works?
Comparison Index C++ Java
Platform-
C++ is platform-dependent. Java is platform-independent.
independent

Java is mainly used for application


C++ is mainly used for programming. It is widely used in
Mainly used for
system programming. window, web-based, enterprise and
mobile applications.

Java was designed and created as an


C++ was designed for
interpreter for printing systems but later
systems and applications
extended as a support network
Design Goal programming.
computing. It was designed with a goal
It was an extension of C
of being easy to use and accessible to a
programming language.
broader audience.

C++ supports the goto


goto Java doesn't support the goto statement.
statement.
Java doesn't support multiple
C++ supports multiple
Multiple inheritance inheritance through class. It can be
inheritance.
achieved by interfaces in java.
Operator C++ supports operator Java doesn't support operator
Overloading overloading. overloading.
Java supports pointer
internally. However, you can't
write the pointer program in
Pointers C++ supports pointers.
java.
It means java has restricted
pointer support in java.
Java uses compiler and
interpreter both. Java source
C++ uses compiler only. code is converted into
bytecode at compilation time.
C++ is compiled and run
Compiler and
using the compiler which The interpreter executes this
Interpreter
converts source code into bytecode at runtime and
machine code so, C++ is produces output.
platform dependent.
Java is interpreted that is why
it is platform independent.
Java supports call by value
Call by Value and C++ supports both call by value
only. There is no call by
Call by reference and call by reference.
reference in java.
Structure and C++ supports structures and Java doesn't support
Union unions. structures and unions.
C++ doesn't have built-in support
Java has built-in thread
Thread Support for threads. It relies on third-
support.
party libraries for thread support.
Java supports
documentation comment
Documentation C++ doesn't support
(/** ... */) to create
comment documentation comment.
documentation for java
source code.
Java has no virtual
keyword. We can override
C++ supports virtual keyword so
all non-static methods by
Virtual Keyword that we can decide whether or
default. In other words,
not override a function.
non-static methods are
virtual by default.
C++ is nearer to Java is not so interactive with
Hardware
hardware. hardware.
Java is also an object-oriented
C++ is an object- language. However, everything
Object-oriented
oriented language. (except fundamental types) is an
object in Java.
JAVA Program Structure
1.3 JAVA Tokens
 A token is the smallest element of a program that is
meaningful to the compiler.

 Tokens can be classified as follows:

• Keywords
• Identifiers
• Constants
• Special Symbols/Separators
• Operators
JAVA Tokens : 1. Keywords

 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 Tokens : 2. Identifiers

 Identifiers are used as the general terminology for


naming of variables, functions and arrays.
1. Uppercase Letters and Lower Case letters are different
2. The name of identifier cannot begin with a digit.
However, Underscore can be used as first character while
declaring the identifier
3. Only alphabetic characters, digits and underscore (_)
are permitted for declaring identifier.
4. Other special characters are not allowed for naming a
variable / identifier
5. Keywords cannot be used as Identifier.
JAVA Tokens : 3. Constants / Symbolic Constant
 Constants are also like normal variables.

 But, the only difference is, their values can not be


modified by the program once they are defined.

 Constants refer to fixed values.

 Constants may belong to any of the data type.

Syntax: (Symbolic Constants)

final data_type variable_name;


JAVA Tokens : 3. Constants – Types of Constant
JAVA Tokens : 4. Special Symbol/Separators
 The following special symbols are used in Java having some
special meaning and thus, cannot be used for some other purpose.
 [](){}, ; * =
Brackets[]: Opening and closing brackets are used as array element
reference. These indicate single and multidimensional subscripts.
Parentheses(): These special symbols are used to indicate function calls
and function parameters.
Braces{}: These opening and ending curly braces marks the start and end
of a block of code containing more than one executable statement.
comma (, ): It is used to separate more than one statements like for
separating parameters in function calls.
semi colon : It is an operator that essentially invokes something called an
initialization list.
asterick (*): It is used to create pointer variable.
assignment operator: It is used to assign values.
JAVA Tokens : 5. Operators
 Operators are the symbols used in the expression for
evaluating them.
Data Types
Data Types : Standard Default Value & Size
Data Type Default Value Default size
boolean false 1 bit
char Null character 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
Variables in JAVA
 A variable is a name given to a memory location. It is the basic
unit of storage in a program.
 The value stored in a variable can be changed during program
execution.
 A variable is only a name given to a memory location, all the
operations done on the variable effects that memory location.
 In Java, all the variables must be declared before use.

datatype: Type of data that can be


stored in this variable.
variable_name: Name given to the
variable.
value: It is the initial value stored in
the variable.
Types of Variables in JAVA
1) Local Variable
- A variable declared inside the body of the method is called local
variable.
- You can use this variable only within that method and the other
methods in the class aren't even aware that the variable exists.

2) Instance Variable
- A variable declared inside the class but outside the body of the
method, is called instance variable.
3) Static variable
- A variable which is declared as static is called static variable.
- You can create a single copy of static variable and share among all
the instances of the class.
- Memory allocation for static variable happens only once when the
class is loaded in the memory.
Example to understand the types of variables in java

class A
{
int data=50; //instance variable
static int m=100; //static variable
void method()
{
int n=90; //local variable
}

} //end of class
Dynamic Initialization in JAVA

 When variable initialized at the time when it is


declared this type of initialization is called
dynamic initialization .

Example of Dynamic initialization :

int count = 10;


Scope of a variable in JAVA

 Variable Scope means - That limit, as far as the variable can


be used.
 In Java there are various types of variable scope:
- Instance variables
- Class variables
- Local variables

 Instance & class variables are declared inside the class.

 The Local Variables are declared inside the method.


public class Example
{
int salary; // Instance Variable

public void show()


{
int value = 2; // Local variable
value = value + 10;
System.out.println("The Value is : " + value);
salary = 10000;
System.out.println("The salary is : " + salary);
}

public static void main(String args[])


{
Example eg = new Example();
eg.show();
}
}
Type Casting in JAVA
 Type casting is when you assign a value of one primitive
data type to another type.
 In Java, there are two types of casting:
Type Casting in JAVA – 1. Widening Casting

 Widening casting is done automatically when passing a


smaller size type to a larger size type:

public class MyClass


{
public static void main(String args [])
{
int a= 9;
double b= a; // Automatic casting: int to double

System.out.println(a); // Outputs 9
System.out.println(b); // Outputs 9.0
}
}
Type Casting in JAVA – 2. Narrowing Casting

 Narrowing casting must be done manually by placing


the type in parentheses in front of the value:

public class MyClass


{
public static void main(String args [])
{
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78


System.out.println(myInt); // Outputs 9
}
}
Array in JAVA
 Arrays are used to store multiple values in a single
variable, instead of declaring separate variables for each
value.
 To declare an array, define the variable type with square
brackets:

 Syntax: type var-name[];

OR

type[] var-name;
Array in JAVA
• String[] cars;
• String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
• int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

System.out.println(cars[0]);

// Outputs Volvo
Change an Array Element

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


cars[0] = "Opel";
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo

Array Length

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


System.out.println(cars.length);
// Outputs 4
Loop Through an Array

 You can loop through the array elements with the for
loop, and use the length property to specify how many
times the loop should run.

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (int i = 0; i < cars.length; i++)


{
System.out.println(cars[i]);
}
String in JAVA
 Strings in Java are Objects that are backed internally
by a char array.
Syntax:

<String_Type> <string_variable> = “<sequence_of_string>”;

Example:

String str = "Geeks";


String Length
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

System.out.println("The length of the txt string is: " + txt.length());

toUpperCase() and toLowerCase()


String txt = "Hello World";
System.out.println(txt.toUpperCase());

// Outputs "HELLO WORLD"


System.out.println(txt.toLowerCase());
// Outputs "hello world"
String Concatenation

String firstName = "John";

String lastName = "Doe";

System.out.println(firstName + " " + lastName);


1.4 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 •instance of operator


•Unary Operators •Dot operators
•Assignment Operator •Precedence and Associativity
•Relational Operators of operators
•Logical Operators
•Ternary Operator
•Bitwise Operators
Arithmetic Operators
 They are used to perform simple arithmetic operations
on primitive data types.

1. * : Multiplication
2. / : Division
3. % : Modulo
4. + : Addition
5. – : Subtraction
Arithmetic Operators
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b); //15
System.out.println(a-b); //5
System.out.println(a*b); //50
System.out.println(a/b); //2
System.out.println(a%b); //0
}
}
Unary Operators
 Unary operators need only one operand. They are used to increment,
decrement or negate a value.
1. – :Unary minus, used for negating the values.
2. + :Unary plus, used for giving positive values. Only used when
deliberately converting a negative value to positive.
3. ++ :Increment operator, used for incrementing the value by 1.
There are two varieties of increment operator.
Post-Increment : Value is first used for computing the result and
then incremented.
Pre-Increment : Value is incremented first and then result is
computed.
4. — : Decrement operator, used for decrementing the value by 1.
There are two varieties of decrement operator.
Post-decrement : Value is first used for computing the result and
then decremented.
Pre-Decrement : Value is decremented first and then result is
computed.
Assignment Operators
 ‘=’ Assignment operator is used to assign a value to any variable.
 It has a right to left associativity,
• In many cases assignment operator can be combined with other
operators to build a shorter version of statement called Compound
Statement. For example, instead of a = a+5, we can write a += 5.
+=, for adding left operand with right operand and then assigning it to
variable on the left.
-=, for subtracting left operand with right operand and then assigning
it to variable on the left.
*=, for multiplying left operand with right operand and then assigning
it to variable on the left.
/=, for dividing left operand with right operand and then assigning it
to variable on the left.
%=, for assigning modulo of left operand with right operand and then
assigning it to variable on the left.
Relational Operators
 Relational operators are used to compare two values:

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
 These operators are used to perform “logical AND” and
“logical OR” operation.

1. && (Logical AND ): returns true when both conditions


are true.

2. ||, (Logical OR) : returns true if at least one condition is


true.
import java.util.*;
Logical Operators
public class operators {
public static void main(String[] args)
{
String x = "Sher";
String y = "Locked";

Scanner s = new Scanner(System.in);


System.out.print("Enter username:");
String uuid = s.next();
System.out.print("Enter password:");
String upwd = s.next();

// Check if user-name and password match or not.


if ((uuid.equals(x) && upwd.equals(y)) || (uuid.equals(y) && upwd.equals(x)))
{
System.out.println("Welcome user.");
}
else {
System.out.println("Wrong uid or password");
}
}
}
Ternary Operators
 Ternary operator is a shorthand version of if-else
statement.

 It has three operands and hence the name ternary.

 General format is-

condition ? if true : if false


Ternary Operators

class OperatorExample
{
public static void main(String args[])
{
int a=2;
int b=5;
int min = (a<b)?a:b;
System.out.println(min);
}
}
Bitwise Operators
 These operators are used to perform manipulation of
individual bits of a number.

• &, Bitwise AND operator: returns bit by bit AND of


input values.
• |, Bitwise OR operator: returns bit by bit OR of input
values.
• ^, Bitwise XOR operator: returns bit by bit XOR of
input values.
• ~, Bitwise Complement Operator: This is a unary
operator which returns the one’s compliment representation
of the input value, i.e. with all bits inversed.
Bitwise Operators
• << , Left Shift operator: The left operands value is
moved left by the number of bits specified by the right
operand.
Ex: 00100011<<2
= 10001100

• >>, Right Shift operator: The left operand value is


moved right by the number of bits specified by the right
operand.
Ex: 00100011>>2
= 00001000
‘Instance of’ Operators
 Instance of operator is used for type checking.

 It can be used to test if an object is an instance of a class,


a subclass or an interface.

 General format-

object instance of class/subclass/interface


Precedence and Associativity of Operators
 Precedence and associative rules are used when dealing
with hybrid equations involving more than one type of
operator.

 Precedence is the priority order of an operator, if there


are two or more operators in an expression then the
operator of highest priority will be executed first then
higher, and then high.

 Associativity tells the direction of execution of


operators that can be either left to right or right to left.
Precedence and Associativity of Operators
1.4 Evaluation of Expression
 Expression is a combination of operators and operands in
specific manner.

 For example :
c=a+b*c //Expression with arithmetic operators

(a>b)&&(b<c) //Expression with logical operators and


relational operators

 Evaluation of expression is an order of evaluating the


expression using precedence and associativity rules.

 For example – 2+3*4, first perform 3*4=12, then add 2


to 12, and result of expression will be 14.
1.4 Mathematical Functions
 The java.lang.Math class contains methods for
performing basic numeric operations such as the elementary
exponential, logarithm, square root, and trigonometric
functions.

 The functions should be used as follows:

Math.function_name()

Example :
double y = Math.sqrt(x);
1.4 Mathematical Functions
Functions Actions
sin(x) Returns the sign of the angle x in radius
cos(x) Returns the cosine of the angle x in radius
tan(x) Returns the tangent of the angle x in radius
pow(x,y) Returns x raised to y (xy )
exp(x) Returns e raised to x (ex )
log(x) Returns the log of x
sqrt(x) Returns the square root of x
round(x) Returns the integer closest to the argument
abs(a) Returns the absolute value of a
max(a,b) Returns the maximum of a and b
min(a,b) Returns the minimum of a and b
1.4 Mathematical Functions
x = Math.max(22,33);

x = Math.sqrt(64);

x = Math.abs(-55);

x = Math.pow(16,3);

x = Math.min(22,33);

x = Math.round(4567.9874f);

x = Math.exp(5.98);
MSBTE Que.
1. Describe any 2 relational operators and any 2 logical
operators in java with simple example. –
(S-16,Marks: 4)

2. Explain any 2 relational operators in java with


example. – (S-17, Marks: 4)

3. ‘ : ? ’ What this operator is called? Explain with


suitable example. – (W-15,S-15, Marks: 4)

4. Explain any 2 bit wise operators with example. – (W-


15, Marks:4)
MSBTE Que.
5. Explain following bitwise operator with an example:
a) Left Shift Operator
b) Right Shift Operator

(S-18, Marks: 04)


1.5 Decision making and Looping
(W15, 16, 17, S-15,16,17,18 – 8 Marks)
 Decision making and looping are the concepts which
works as a control statement in Java.
 Control statements in Java are the instructions which
can control the flow of execution of a program.
 In control statement, there are some conditions which are
specified by a programmer.
 These conditions are evaluated by the system and a
particular block of statements are executed.

 Following are the types of control statements:


- Decision-making statements
- Looping statements
1. If Statement
 Simple if statement is used to execute a particular block
of statements if the condition is true otherwise program
continues its execution excepting the block of statement
inside if block.

Syntax :
if (condition)
{
// block of statements which will be executed if
condition is true.
}
1. If Statement
 Following is the flowchart of simple if statement -
1. If Statement
class SimpleIf
{
public static void main(String args[])
{
int i=3;

if(i<5) //i<5 is a condition


{
//this block is executed only if condition is true

System.out.println("If block executed");


}
}
}
2. If…else Statement

 If else statement is a Syntax :


decision-making statement
which is having true block as if (condition)
well as false block. {
//true block
 In this type of statement, }
the condition is evaluated, if else
the condition is true then the {
true block of the statement is //false block
executed other false block. }
2. If..else Statement
 Following is the flowchart of simple if..else statement -
2. If..else Statement
class Ifelse
{
public static void main(String args[])
{
int i=3;
if (i<5)
{
System.out.println("Value of i is less than 5");
}
else
{
System.out.println("Value of i is not less than 5");
}
}
}
3. Nested If…else Statement
 If statement inside another if statement is known as
nested if statement. Nested means a block inside another
block.
Syntax :

if (condition)
{
//body of parent if
if (condition)
{
//body of nested if
}
}
3. Nested If…else Statement
4. Else…if Ladder
 Else … if ladder is a decision-making statement which
is used to test sequence of test conditions.

 In this type of statement it checks for the condition and


if the condition is satisfied then associated block of the
statement will be executed.

 If the condition is false then next condition in the Else


… if ladder will be checked.

 If none of the conditions is true, the default block is


executed.
else if(condition 3)
4. Else…if Ladder {
//third block of statement
if(condition 1) }
{
else if(condition n)
//first block of statements {

} //nth block of statement

else if(condition 2) }
{ else
{
//second block of statements
//Default block of statement
}
}
4. Else…if Ladder
5. Switch Statement switch(variable)
{
 Switch case statement case constant 1:
works same as else … if //body of case 1
break;
ladder but it checks only case constant 2:
one variable. //body of case 2
break;
case constant 3:
 Else … if ladder can
//body of case 3
check multiple break;
variables. case constant n:
//body of case n
break;
 In switch single default:
variable is checked for //body of default
multiple values. block
}
switch(variable 1) 6.Nested Switch
{ Statement
case constant1:
//body of case 1
switch(variable 2)
A switch case statement
{ which consists of another
//body of nested switch switch case within its
case constant 1: block is known as nested
//body of case 1 switch case statement.
break;
case constant 2:
//body of case 2 case constant 2:
break; //body of case 2
case constant n: break;
//body of case n case constant n:
break; //body of case n
default: break;
//default block of statement default:
} //body of default block
break;
}
5. Switch Statement – MSBTE Que.
1. In what ways does a switch statement differ from an
if statement? – W16, 4 Marks
Looping Statement
 Looping statements allow the programmer to execute
some group of statement repetitively multiple times.
There are two types of loop:

1. Entry control loop (while loop and for loop)


2. Exit control loop (do … while loop)

 Entry control loops are the loop in which condition is


tasted at the beginning of the loop.

 Exit control loops are the loop which condition is


tasted at the end of the loop.
1. While Loop
While loop is an entry control looping statement that
allows code to be executed until the boolean condition is
true.
Syntax:

...
//Assignment of counter variable

while(condition)
{
//body of loop
//increment or decrement of variable
}
...
1. While Loop
1. While Loop
class WhileLoop
{
public static void main(String args[])
{
int i=0; // Assignment of counter variable
while(i<10)
{

//This loop will be executed 10 times.


System.out.println(i);
i++; //increment of counter variable
}
}
}
2. do…While Loop
 Do … while is an exit control looping statement which is
also used to execute a block of instructions several times

Syntax:

//Assignment of counter variable


do
{
//body of statement
//increment or decrement of counter variable
}
while(condition);
//You must put semicolon here
2. do…While Loop
2. do…While Loop
class DoWhileLoop
{
public static void main(String args[])
{
int i=0; // Assignment of counter variable
do
{

//this body will be executed at least once


System.out.println(i);
i++; //increment of counter variable
}
while(i<10);
}
}
3. For Loop
For loop is an entry control loop which works same as the
other two loop but its syntax is different.

 In other two loop counter variable is declared outside the


body of the loop.

Syntax:

for (init; condition; increment or decrement)


{
//body of for loop
}
3. For Loop
3. For Loop
class ForLoop
{
public static void main(String args[])
{
for(int i=0;i<10;i++)
{
System.out.println(i);
}
}
}
4. Nested Loops
 The concept of a nested loop is as same as nested
decision-making statement.

 One loop can contain another looping statement.


class NestedLoop
{
4. Nested Loops
public static void main(String args[])
{
int j;
for(int i=0;i<5;i++)
{
j=1;
while(j<=i)
{
System.out.print("*");
j++;
}
System.out.println();
}
}
}
MSBTE Que.
1. Define a class having one 3 digit number, num as a
data member, initialize and display reverse of that
number. – (S-15,16, Marks: 4)

2. Write a program to find sum of digit of number


entered by user. – (W-16, S-17, Marks: 4)

3. Write a program to find the number of and sum of all


integers greater than 100 and less than 200 that are
divisible by 7. – (W-16, Marks: 4)

4. Write a program to generate Fibonacci series: 1 1 2 3 5


8 13 21 34 89. – (S-17, Marks:4)
The Break Statement
 The break statement in Java programming language has
the following two usages −

When the break statement is encountered inside a


loop, the loop is immediately terminated and the program
control resumes at the next statement following the loop.

Syntax:

break;
The Break Statement
The Break Statement
The Break Statement
class breakDemo
{
public static void main(String args[])
{
for (int i=1; i<=10; i++)
{
if (i==5)
{
break;
}
System.out.println(i+ “”);
}
System.out.println(“Loop is terminated using break”);
}
} Output: 1 2 3 4 Loop is terminated using break
The Continue Statement
 The continue keyword can be used in any of the loop
control structures.

 It causes the loop to immediately jump to the next


iteration of the loop.

Syntax:

continue;
The Continue Statement
The Continue Statement
class continueDemo
{
public static void main(String args[])
{
for(int i=0; i<=10; i++)
{
if(i==5)
{
continue;
}
System.out.println(i + “”);
}
}
}
Output: 1 2 3 4 6 7 8 9 10
MSBTE Que.
1. Write a program to check whether an entered number
is prime or not.– (W-15,17, S-16, Marks: 4)
The return Statement
 The return statement is used to return from a function.
That means using return statement the control goes back to
the caller function.

 At any time the return statement can be used to transfer


back the control to the caller function.

 The return function causes to terminate the function


immediately.
Syntax:

return;
The return Statement
class continueDemo
{
public static void main(String args[])
{
int a=10;
System.out.println(“This statement is executed before
execution of return..”)
if (a==10)
return;
System.out.println(“This statement is will not be
executed”)
}
}
MSBTE Que.
1. Write a program to print the following output.–
11111
2222
333
44
5
(W-17, Marks: 4)

2. Write a java program to display all the odd numbers


between 1 to 30 using for loop and if statement.
(S-18, Marks: 4)
MSBTE Que.
3. Write a java program to display following pattern.
*
* * *
* * * * *
* * * * * * *
** * * * * * * *
The Labeled Loops
1. Labeled break:
• Sometimes the control to be transferred to a
specific instruction. This can be done using the
statement like goto.

• Java provides the support for jump statement


using labeled break.

• label is the name of the block which need to be


skipped.
Syntax:

break label;
The Labeled Loops
 Here, label is an identifier.
 When break statement executes, it terminates the
labeled statement, and control of the program jumps to
the statement immediately following the labeled
statement.
The Labeled Loops
2. Labeled Continue:

• There is another form of continue statement,


labeled form, that can be used to skip the
execution of statement(s) that lies inside the outer
loop.

Syntax:

continue label;
2. Labeled Continue:
The for – Each Version of the for loop
 The for – each element is used to access each element of
an array.

Syntax: ….
int [] numbers = {10, 20, 30, 40, 50};
for(declaration : expression) for(int x : numbers )
{ {
// Statements System.out.print( x );
} System.out.print(",");
}
….
MSBTE Que.
1. Write a general syntax of any 2 decision making
statements and also give its example. –(S-16,Marks: 4)
2. Explain break and continue statements with example.
– (S-16, Marks: 4)
3. State syntax and describe working of ‘for-each’
version of for loop with one example. – (W-16, Marks:
4)
4. Illustrate with example the use of switch case
statement. – (W-17, Marks:4)

5. Describe break & continue statement with example. –


(W-15, Marks:4)

Вам также может понравиться