SlideShare a Scribd company logo
Unit 1:Basic Syntactical
Constructs In Java
Mr. Prashant B. Patil
SY CSE- , JPR
2024-2025
History of Java
• James Gosling, Mike Sheridan, Patrick Naughton
and Vinod Khosala.
• Java language introduced in June 1991. The small
team of sun engineers called Green Team.
• Initially it was designed for small, embedded systems
in electronic appliances like set-top boxes.
• Firstly, it was called "Greentalk" by James Gosling,
and the file extension was .gt.
• After that, it was called Oak
• 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.
Why Java Programming named "Java"?
• 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.
• Java is an island in Indonesia where the first coffee
was produced (called Java coffee). Java name was
chosen by James Gosling while having a cup of
coffee nearby his office.
• JDK 1.0 was released on January 23, 1996.
After the first release of Java, there have been
many additional features added to the
language.
• Features of JAVA
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
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
3. 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
3. Secured
4. 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 (GC) in java
which runs on the Java Virtual Machine
 There are exception handling and the type checking
mechanism in Java. All these points make Java robust.
5. Portable
Java is portable because it facilitates you to carry the Java
bytecode to any platform.
It doesn't require any implementation.
6. Distributed
Java is distributed because it facilitates users to create
distributed applications in Java. This feature of Java makes
us able to access files by calling the methods from any
machine on the internet.
7. Dynamic
Java is a dynamic language. It supports dynamic loading of
classes. It means classes are loaded on demand.
Java supports dynamic collection and automatic memory
management (garbage collection).
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. 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.
10. 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.
11. 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.
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
JAVA Prog. javadoc HTML files
javac
Java class
file
javah Header Files
java jdb
Java Prog.
Output
Commenting Source Program
Compilation
Execution
Debugging
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?
JAVA Programming Environment : 2. JVM – How Works?
Comparison Index C++ Java
Platform-
independent
C++ is platform-dependent. Java is platform-independent.
Mainly used for
C++ is mainly used for
system programming.
Java is mainly used for application
programming. It is widely used in
window, web-based, enterprise and
mobile applications.
goto
C++ supports the goto
statement.
Java doesn't support the goto statement.
Multiple inheritance
C++ supports multiple
inheritance.
Java doesn't support multiple
inheritance through class. It can be
achieved by interfaces in java.
Operator
Overloading
C++ supports operator
overloading.
Java doesn't support operator
overloading.
Pointers C++ supports pointers.
Java supports pointer internally.
However, you can't write the
pointer program in java.
It means java has restricted
pointer support in java.
Compiler and
Interpreter
C++ uses compiler only.
C++ is compiled and run
using the compiler which
converts source code into
machine code so, C++ is
platform dependent.
Java uses compiler and
interpreter both. Java source
code is converted into bytecode
at compilation time.
The interpreter executes this
bytecode at runtime and
produces output.
Java is interpreted that is why it
is platform independent.
Call by Value and
Call by reference
C++ supports both call by value
and call by reference.
Java supports call by value
only. There is no call by
reference in java.
Structure and
Union
C++ supports structures and
unions.
Java doesn't support
structures and unions.
Hardware C++ is nearer to hardware.
Java is not so interactive
with hardware.
Virtual Keyword
C++ supports virtual keyword so
that we can decide whether or
not override a function.
Java has no virtual
keyword. We can override
all non-static methods by
default. In other words,
non-static methods are
virtual by default.
JAVA Program Structure
Chapter One Basics ofJava Programmming.pptx
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
 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 : 1. Keywords
Chapter One Basics ofJava Programmming.pptx
 Identifiers are used as the general terminology for
naming of variables, functions and arrays.
Identifiers in Java are a sequence of characters to
identify something in a program
JAVA Tokens : 2. Identifiers
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.
 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 / Symbolic Constant
JAVA Tokens : 3. Constants – Types of Constant
 The following special symbols are used in Java having some
special meaning and thus, cannot be used for some other purpose.
 [ ] ( ) { } , * =
JAVA Tokens : 4. Special Symbol/Separators
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.
asterick (*): It is used to create pointer variable.
assignment operator: It is used to assign values.
 Operators are the symbols used in the expression for
evaluating them.
An operator, in Java, is a special symbols
performing specific operations on one, two or
three operands and then returning a result
JAVA Tokens : 5. Operators
Data Types
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
Data Types : Standard Default Value & Size
 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.
Variables in JAVA
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.
Chapter One Basics ofJava Programmming.pptx
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.
Types of Variables in JAVA
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
 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;
Dynamic Initialization 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
Scope of a variable in JAVA
 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 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
 Widening casting is done automatically when passing a
smaller size type to a larger size type:
Type Casting in JAVA – 1. Widening Casting
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
}
}
 Narrowing casting must be done manually by placing
the type in parentheses in front of the value:
Type Casting in JAVA – 2. Narrowing Casting
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
}
}
 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:
Array in JAVA
type var-name[];
OR
type[] var-name;
• String[] cars;
• String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
• int[] myNum = {10, 20, 30, 40};
Array in JAVA
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
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++)
{
System.out.println(cars[i]);
}
 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 in JAVA
<String_Type> <string_variable> = “<sequence_of_string>”;
 Strings in Java are Objects that are backed internally
by a char array.
String str = "Geeks";
Example:
Syntax:
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);
• 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
•Bitwise Operators
1.4 Operators in JAVA
•instance of operator
•Dot operators
•Precedence and Associativity
of 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
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
}
}
Arithmetic Operators
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
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
 Relational operators are used to compare two values:
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.*;
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");
}
}
}
Logical Operators
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
class OperatorExample
{
public static void main(String args[])
{
int a=2;
int b=5;
int min = (a<b)?a:b;
System.out.println(min);
}
}
Ternary Operators
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’ Operator
 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
 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 Evaluation of Expression
 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
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
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);
1.4 Mathematical Functions
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)
5. Explain following bitwise operator with an example:
a) Left Shift Operator
b) Right Shift Operator
Chapter One Basics ofJava Programmming.pptx
 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.5 Decision making and Looping
(W15, 16, 17, S-15,16,17,18 – 8 Marks)
 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.
1. If Statement
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 -
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");
}
}
}
1. If Statement
 If else statement is a
decision-making statement
which is having true block as
well as false block.
 In this type of statement,
the condition is evaluated, if
the condition is true then the
true block of the statement is
executed other false block.
2. If…else Statement
Syntax :
if (condition)
{
//true block
}
else
{
//false block
}
2. If..else Statement
 Following is the flowchart of simple 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");
}
}
}
2. If..else Statement
 If statement inside another if statement is known as
nested if statement. Nested means a block inside another
block.
3. Nested If…else Statement
Syntax :
if (condition)
{
//body of parent if
if (condition)
{
//body of nested if
}
}
3. Nested If…else Statement
 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.
4. Else…if Ladder
4. Else…if Ladder
if(condition 1)
{
//first block of statements
}
else if(condition 2)
{
//second block of statements
}
else if(condition 3)
{
//third block of statement
}
else if(condition n)
{
//nth block of statement
}
else
{
//Default block of statement
}
4. Else…if Ladder
 Switch case statement
works same as else … if
ladder but it checks only
one variable.
 Else … if ladder can
check multiple
variables.
 In switch single
variable is checked for
multiple values.
5. Switch Statement switch(variable)
{
case constant 1:
//body of case 1
break;
case constant 2:
//body of case 2
break;
case constant 3:
//body of case 3
break;
case constant n:
//body of case n
break;
default:
//body of default
block
}
Chapter One Basics ofJava Programmming.pptx
A switch case statement
which consists of another
switch case within its
block is known as nested
switch case statement.
6.Nested Switch
Statement
switch(variable 1)
{
case constant1:
//body of case 1
switch(variable 2)
{
//body of nested switch
case constant 1:
//body of case 1
break;
case constant 2:
//body of case 2
break;
case constant n:
//body of case n
break;
default:
//default block of
statement
}
break;
case constant 2:
//body of case 2
break;
case constant n:
//body of case n
break;
default:
//body of default block
}
1. In what ways does a switch statement differ from an
if statement? – W16, 4 Marks
5. Switch Statement – MSBTE Que.
 Looping statements allow the programmer to execute
some group of statement repetitively multiple times.
Looping Statement
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.
While loop is an entry control looping statement that
allows code to be executed until the boolean condition is
true.
1. While Loop
Syntax:
...
//Assignment of counter variable
while(condition)
{
//body of loop
//increment or decrement of variable
}
...
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
}
}
}
1. While Loop
 Do … while is an exit control looping statement which is
also used to execute a block of instructions several times
2. do…While Loop
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
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);
}
}
2. do…While 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.
3. For Loop
Syntax:
for (init; condition; increment or decrement)
{
//body of for loop
}
3. For Loop
class ForLoop
{
public static void main(String args[])
{
for(int i=0;i<10;i++)
{
System.out.println(i);
}
}
}
3. For Loop
 The concept of a nested loop is as same as nested
decision-making statement.
 One loop can contain another looping statement.
4. Nested Loops
class NestedLoop
{
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();
}
}
}
4. Nested Loops
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 in Java is a powerful tool for
controlling the flow of your program. It is used to exit a
loop or switch statement prematurely. It allows us to
customize the behavior of code based on specific
conditions.
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.
The Break Statement
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 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.
The Continue Statement
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
1. Write a program to check whether an entered number
is prime or not.– (W-15,17, S-16, Marks: 4)
 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.
The return Statement
Syntax:
return;
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”)
}
}
The return Statement
1. Write a program to print the following output.–
1 1 1 1 1
2 2 2 2
3 3 3
4 4
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)
3. Write a java program to display following pattern.
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
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.
The Labeled Loops
Syntax:
break label;
public class LabeledBreakExample
{ public static void main(String[] args)
{ outerLoop:
for (int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{ System.out.println("i = " + i + ", j = " + j);
// If j is 2, break out of the outer loop labeled "outerLoop“
if (j == 2)
{ break outerLoop; } } }
System.out.println("Exited from the outer loop"); } }
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.
The Labeled Loops
Syntax:
continue label;
2. Labeled Continue:
 The for – each element is used to access each element of
an array.
The for – Each Version of the for loop
Syntax:
for(declaration : expression)
{
// Statements
}
….
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
System.out.print( x );
System.out.print(",");
}
….
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)

More Related Content

Similar to Chapter One Basics ofJava Programmming.pptx (20)

PPT
javaeanjjisjejrehurfhjhjfeauojksfjdi.ppt
eraqhuzay69
 
PPTX
Java Basics.pptx from nit patna ece department
om2348023vats
 
PPTX
History of java'
deepthisujithra
 
PPTX
Java basic
Pooja Thakur
 
PPTX
Java programming Introduction | Java basic architecture
shaswinayyan
 
DOCX
Srgoc java
Gaurav Singh
 
PDF
Java chapter 1
Mukesh Tekwani
 
PPTX
java slides
RizwanTariq18
 
PPTX
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING
 
PPTX
Chapter 1 (1).pptx
krishnashah277578
 
PPTX
object oriented programming unit one ppt
isiagnel2
 
PPTX
Assignmentjsnsnshshusjdnsnshhzudjdndndjd
tusharjain613841
 
PDF
Java programming material for beginners by Nithin, VVCE, Mysuru
Nithin Kumar,VVCE, Mysuru
 
PPTX
Java Technologies notes of unit 1 and 2.
sumanyadavdpg
 
PPTX
Java (1)
Samraiz Tejani
 
PPTX
Unit-1_GHD.pptxguguigihihihihihihoihihhi
40NehaPagariya
 
PDF
Lec 3 01_aug13
Palak Sanghani
 
ODP
Introduction To Java.
Tushar Chauhan
 
javaeanjjisjejrehurfhjhjfeauojksfjdi.ppt
eraqhuzay69
 
Java Basics.pptx from nit patna ece department
om2348023vats
 
History of java'
deepthisujithra
 
Java basic
Pooja Thakur
 
Java programming Introduction | Java basic architecture
shaswinayyan
 
Srgoc java
Gaurav Singh
 
Java chapter 1
Mukesh Tekwani
 
java slides
RizwanTariq18
 
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING
 
Chapter 1 (1).pptx
krishnashah277578
 
object oriented programming unit one ppt
isiagnel2
 
Assignmentjsnsnshshusjdnsnshhzudjdndndjd
tusharjain613841
 
Java programming material for beginners by Nithin, VVCE, Mysuru
Nithin Kumar,VVCE, Mysuru
 
Java Technologies notes of unit 1 and 2.
sumanyadavdpg
 
Java (1)
Samraiz Tejani
 
Unit-1_GHD.pptxguguigihihihihihihoihihhi
40NehaPagariya
 
Lec 3 01_aug13
Palak Sanghani
 
Introduction To Java.
Tushar Chauhan
 

Recently uploaded (20)

PPTX
Engineering Quiz ShowEngineering Quiz Show
CalvinLabial
 
PDF
Tesia Dobrydnia - An Avid Hiker And Backpacker
Tesia Dobrydnia
 
PDF
FSE-Journal-First-Automated code editing with search-generate-modify.pdf
cl144
 
PDF
June 2025 Top 10 Sites -Electrical and Electronics Engineering: An Internatio...
elelijjournal653
 
PDF
Module - 4 Machine Learning -22ISE62.pdf
Dr. Shivashankar
 
PPTX
Electrical_Safety_EMI_EMC_Presentation.pptx
drmaneharshalid
 
PDF
NFPA 10 - Estandar para extintores de incendios portatiles (ed.22 ENG).pdf
Oscar Orozco
 
PDF
How to Buy Verified CashApp Accounts IN 2025
Buy Verified CashApp Accounts
 
PPTX
Alan Turing - life and importance for all of us now
Pedro Concejero
 
PDF
Designing for Tomorrow – Architecture’s Role in the Sustainability Movement
BIM Services
 
PDF
Artificial Neural Network-Types,Perceptron,Problems
Sharmila Chidaravalli
 
DOCX
Engineering Geology Field Report to Malekhu .docx
justprashant567
 
PPTX
Introduction to File Transfer Protocol with commands in FTP
BeulahS2
 
PPTX
Artificial Intelligence jejeiejj3iriejrjifirirjdjeie
VikingsGaming2
 
PPTX
Precooling and Refrigerated storage.pptx
ThongamSunita
 
PDF
June 2025 - Top 10 Read Articles in Network Security and Its Applications
IJNSA Journal
 
PDF
A Brief Introduction About Robert Paul Hardee
Robert Paul Hardee
 
PDF
Authentication Devices in Fog-mobile Edge Computing Environments through a Wi...
ijujournal
 
PDF
Decision support system in machine learning models for a face recognition-bas...
TELKOMNIKA JOURNAL
 
PDF
LLC CM NCP1399 SIMPLIS MODEL MANUAL.PDF
ssuser1be9ce
 
Engineering Quiz ShowEngineering Quiz Show
CalvinLabial
 
Tesia Dobrydnia - An Avid Hiker And Backpacker
Tesia Dobrydnia
 
FSE-Journal-First-Automated code editing with search-generate-modify.pdf
cl144
 
June 2025 Top 10 Sites -Electrical and Electronics Engineering: An Internatio...
elelijjournal653
 
Module - 4 Machine Learning -22ISE62.pdf
Dr. Shivashankar
 
Electrical_Safety_EMI_EMC_Presentation.pptx
drmaneharshalid
 
NFPA 10 - Estandar para extintores de incendios portatiles (ed.22 ENG).pdf
Oscar Orozco
 
How to Buy Verified CashApp Accounts IN 2025
Buy Verified CashApp Accounts
 
Alan Turing - life and importance for all of us now
Pedro Concejero
 
Designing for Tomorrow – Architecture’s Role in the Sustainability Movement
BIM Services
 
Artificial Neural Network-Types,Perceptron,Problems
Sharmila Chidaravalli
 
Engineering Geology Field Report to Malekhu .docx
justprashant567
 
Introduction to File Transfer Protocol with commands in FTP
BeulahS2
 
Artificial Intelligence jejeiejj3iriejrjifirirjdjeie
VikingsGaming2
 
Precooling and Refrigerated storage.pptx
ThongamSunita
 
June 2025 - Top 10 Read Articles in Network Security and Its Applications
IJNSA Journal
 
A Brief Introduction About Robert Paul Hardee
Robert Paul Hardee
 
Authentication Devices in Fog-mobile Edge Computing Environments through a Wi...
ijujournal
 
Decision support system in machine learning models for a face recognition-bas...
TELKOMNIKA JOURNAL
 
LLC CM NCP1399 SIMPLIS MODEL MANUAL.PDF
ssuser1be9ce
 
Ad

Chapter One Basics ofJava Programmming.pptx

  • 1. Unit 1:Basic Syntactical Constructs In Java Mr. Prashant B. Patil SY CSE- , JPR 2024-2025
  • 2. History of Java • James Gosling, Mike Sheridan, Patrick Naughton and Vinod Khosala. • Java language introduced in June 1991. The small team of sun engineers called Green Team. • Initially it was designed for small, embedded systems in electronic appliances like set-top boxes. • Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt. • After that, it was called Oak
  • 3. • 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.
  • 4. Why Java Programming named "Java"? • 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. • Java is an island in Indonesia where the first coffee was produced (called Java coffee). Java name was chosen by James Gosling while having a cup of coffee nearby his office.
  • 5. • JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been many additional features added to the language.
  • 8. 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.
  • 9. 2. Object - Oriented Java is an object-oriented programming language. Everything in Java is an object.  Object  Class  Inheritance  Polymorphism  Abstraction  Encapsulation
  • 10. 3. 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
  • 12. 4. 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 (GC) in java which runs on the Java Virtual Machine  There are exception handling and the type checking mechanism in Java. All these points make Java robust.
  • 13. 5. Portable Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation. 6. Distributed Java is distributed because it facilitates users to create distributed applications in Java. This feature of Java makes us able to access files by calling the methods from any machine on the internet.
  • 14. 7. Dynamic Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand. Java supports dynamic collection and automatic memory management (garbage collection). 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.
  • 15. 9. 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.
  • 16. 10. 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.
  • 17. 11. 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.
  • 18. 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.
  • 19. 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
  • 20. JAVA Programming Environment : 1. JDK Text Editor JAVA Prog. javadoc HTML files javac Java class file javah Header Files java jdb Java Prog. Output Commenting Source Program Compilation Execution Debugging Fig. Execution Process of application program
  • 21. JAVA Programming Environment : 2. JVM  The Java Virtual Machine (JVM) is a software and program components.
  • 22. JAVA Programming Environment : 2. JVM – How Works?
  • 23. JAVA Programming Environment : 2. JVM – How Works?
  • 24. Comparison Index C++ Java Platform- independent C++ is platform-dependent. Java is platform-independent. Mainly used for C++ is mainly used for system programming. Java is mainly used for application programming. It is widely used in window, web-based, enterprise and mobile applications. goto C++ supports the goto statement. Java doesn't support the goto statement. Multiple inheritance C++ supports multiple inheritance. Java doesn't support multiple inheritance through class. It can be achieved by interfaces in java.
  • 25. Operator Overloading C++ supports operator overloading. Java doesn't support operator overloading. Pointers C++ supports pointers. Java supports pointer internally. However, you can't write the pointer program in java. It means java has restricted pointer support in java. Compiler and Interpreter C++ uses compiler only. C++ is compiled and run using the compiler which converts source code into machine code so, C++ is platform dependent. Java uses compiler and interpreter both. Java source code is converted into bytecode at compilation time. The interpreter executes this bytecode at runtime and produces output. Java is interpreted that is why it is platform independent.
  • 26. Call by Value and Call by reference C++ supports both call by value and call by reference. Java supports call by value only. There is no call by reference in java. Structure and Union C++ supports structures and unions. Java doesn't support structures and unions. Hardware C++ is nearer to hardware. Java is not so interactive with hardware. Virtual Keyword C++ supports virtual keyword so that we can decide whether or not override a function. Java has no virtual keyword. We can override all non-static methods by default. In other words, non-static methods are virtual by default.
  • 29. 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
  • 30.  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 : 1. Keywords
  • 32.  Identifiers are used as the general terminology for naming of variables, functions and arrays. Identifiers in Java are a sequence of characters to identify something in a program JAVA Tokens : 2. Identifiers 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.
  • 33.  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 / Symbolic Constant
  • 34. JAVA Tokens : 3. Constants – Types of Constant
  • 35.  The following special symbols are used in Java having some special meaning and thus, cannot be used for some other purpose.  [ ] ( ) { } , * = JAVA Tokens : 4. Special Symbol/Separators 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. asterick (*): It is used to create pointer variable. assignment operator: It is used to assign values.
  • 36.  Operators are the symbols used in the expression for evaluating them. An operator, in Java, is a special symbols performing specific operations on one, two or three operands and then returning a result JAVA Tokens : 5. Operators
  • 38. 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 Data Types : Standard Default Value & Size
  • 39.  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. Variables in JAVA 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.
  • 41. 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. Types of Variables in JAVA
  • 42. 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
  • 43.  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; Dynamic Initialization in JAVA
  • 44.  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 Scope of a variable in JAVA  Instance & class variables are declared inside the class.  The Local Variables are declared inside the method.
  • 45. 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(); } }
  • 46.  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
  • 47.  Widening casting is done automatically when passing a smaller size type to a larger size type: Type Casting in JAVA – 1. Widening Casting 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 } }
  • 48.  Narrowing casting must be done manually by placing the type in parentheses in front of the value: Type Casting in JAVA – 2. Narrowing Casting 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 } }
  • 49.  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: Array in JAVA type var-name[]; OR type[] var-name;
  • 50. • String[] cars; • String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; • int[] myNum = {10, 20, 30, 40}; Array in JAVA Access the Elements of an Array String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; System.out.println(cars[0]); // Outputs Volvo
  • 51. 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
  • 52. Loop Through an Array String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for (int i = 0; i < cars.length; i++) { System.out.println(cars[i]); }  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.
  • 53. String in JAVA <String_Type> <string_variable> = “<sequence_of_string>”;  Strings in Java are Objects that are backed internally by a char array. String str = "Geeks"; Example: Syntax:
  • 54. 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"
  • 55. String Concatenation String firstName = "John"; String lastName = "Doe"; System.out.println(firstName + " " + lastName);
  • 56. • 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 •Bitwise Operators 1.4 Operators in JAVA •instance of operator •Dot operators •Precedence and Associativity of operators
  • 57. Arithmetic Operators  They are used to perform simple arithmetic operations on primitive data types. 1. * : Multiplication 2. / : Division 3. % : Modulo 4. + : Addition 5. – : Subtraction
  • 58. 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 } } Arithmetic Operators
  • 59. 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.
  • 60. 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.
  • 61. 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  Relational operators are used to compare two values:
  • 62. 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.
  • 63. import java.util.*; 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"); } } } Logical Operators
  • 64. 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
  • 65. class OperatorExample { public static void main(String args[]) { int a=2; int b=5; int min = (a<b)?a:b; System.out.println(min); } } Ternary Operators
  • 66. 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.
  • 67. 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
  • 68. ‘Instance of’ Operator  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
  • 69. 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.
  • 71.  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 Evaluation of Expression
  • 72.  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
  • 73. 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
  • 74. 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); 1.4 Mathematical Functions
  • 75. 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)
  • 76. 5. Explain following bitwise operator with an example: a) Left Shift Operator b) Right Shift Operator
  • 78.  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.5 Decision making and Looping (W15, 16, 17, S-15,16,17,18 – 8 Marks)
  • 79.  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. 1. If Statement Syntax : if (condition) { // block of statements which will be executed if condition is true. }
  • 80. 1. If Statement  Following is the flowchart of simple if statement -
  • 81. 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"); } } } 1. If Statement
  • 82.  If else statement is a decision-making statement which is having true block as well as false block.  In this type of statement, the condition is evaluated, if the condition is true then the true block of the statement is executed other false block. 2. If…else Statement Syntax : if (condition) { //true block } else { //false block }
  • 83. 2. If..else Statement  Following is the flowchart of simple if..else statement -
  • 84. 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"); } } } 2. If..else Statement
  • 85.  If statement inside another if statement is known as nested if statement. Nested means a block inside another block. 3. Nested If…else Statement Syntax : if (condition) { //body of parent if if (condition) { //body of nested if } }
  • 86. 3. Nested If…else Statement
  • 87.  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. 4. Else…if Ladder
  • 88. 4. Else…if Ladder if(condition 1) { //first block of statements } else if(condition 2) { //second block of statements } else if(condition 3) { //third block of statement } else if(condition n) { //nth block of statement } else { //Default block of statement }
  • 90.  Switch case statement works same as else … if ladder but it checks only one variable.  Else … if ladder can check multiple variables.  In switch single variable is checked for multiple values. 5. Switch Statement switch(variable) { case constant 1: //body of case 1 break; case constant 2: //body of case 2 break; case constant 3: //body of case 3 break; case constant n: //body of case n break; default: //body of default block }
  • 92. A switch case statement which consists of another switch case within its block is known as nested switch case statement. 6.Nested Switch Statement switch(variable 1) { case constant1: //body of case 1 switch(variable 2) { //body of nested switch case constant 1: //body of case 1 break; case constant 2: //body of case 2 break; case constant n: //body of case n break; default: //default block of statement } break; case constant 2: //body of case 2 break; case constant n: //body of case n break; default: //body of default block }
  • 93. 1. In what ways does a switch statement differ from an if statement? – W16, 4 Marks 5. Switch Statement – MSBTE Que.
  • 94.  Looping statements allow the programmer to execute some group of statement repetitively multiple times. Looping Statement 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.
  • 95. While loop is an entry control looping statement that allows code to be executed until the boolean condition is true. 1. While Loop Syntax: ... //Assignment of counter variable while(condition) { //body of loop //increment or decrement of variable } ...
  • 97. 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 } } } 1. While Loop
  • 98.  Do … while is an exit control looping statement which is also used to execute a block of instructions several times 2. do…While Loop Syntax: //Assignment of counter variable do { //body of statement //increment or decrement of counter variable } while(condition); //You must put semicolon here
  • 100. 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); } } 2. do…While Loop
  • 101. 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. 3. For Loop Syntax: for (init; condition; increment or decrement) { //body of for loop }
  • 103. class ForLoop { public static void main(String args[]) { for(int i=0;i<10;i++) { System.out.println(i); } } } 3. For Loop
  • 104.  The concept of a nested loop is as same as nested decision-making statement.  One loop can contain another looping statement. 4. Nested Loops
  • 105. class NestedLoop { 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(); } } } 4. Nested Loops
  • 106. 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)
  • 107. The `break` statement in Java is a powerful tool for controlling the flow of your program. It is used to exit a loop or switch statement prematurely. It allows us to customize the behavior of code based on specific conditions. 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. The Break Statement Syntax: break;
  • 110. 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
  • 111.  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. The Continue Statement Syntax: continue;
  • 113. 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
  • 114. 1. Write a program to check whether an entered number is prime or not.– (W-15,17, S-16, Marks: 4)
  • 115.  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. The return Statement Syntax: return;
  • 116. 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”) } } The return Statement
  • 117. 1. Write a program to print the following output.– 1 1 1 1 1 2 2 2 2 3 3 3 4 4 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)
  • 118. 3. Write a java program to display following pattern. * * * * * * * * * * * * * * * * * * * * * * * * *
  • 119. 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. The Labeled Loops Syntax: break label;
  • 120. public class LabeledBreakExample { public static void main(String[] args) { outerLoop: for (int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { System.out.println("i = " + i + ", j = " + j); // If j is 2, break out of the outer loop labeled "outerLoop“ if (j == 2) { break outerLoop; } } } System.out.println("Exited from the outer loop"); } }
  • 121. 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. The Labeled Loops Syntax: continue label;
  • 123.  The for – each element is used to access each element of an array. The for – Each Version of the for loop Syntax: for(declaration : expression) { // Statements } …. int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { System.out.print( x ); System.out.print(","); } ….
  • 124. 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)