Oop CH 1-2
Oop CH 1-2
Oop CH 1-2
4th
Java Language
Features of java
SREZ Page 1
Object Oriented Programming -I B.E. 4th
2. Platform Independent : Java programs are compiled into bytecode, which can be
executed on any device with a Java Virtual Machine (JVM). This "write once, run
anywhere" capability allows Java applications to be platform-independent, making them
highly portable.
3. Secure : Java places a strong emphasis on security, with features such as bytecode
verification, runtime security checks, and a robust security model. These features help
prevent various security vulnerabilities and protect against malicious attacks.
6. Robust : Java makes an effort to eliminate error prone situations by emphasizing mainly
on compile time error checking and runtime checking.
8. Interpreted: Java byte code is translated on the fly to native machine instruction
and is not stored anywhere. The development process is more rapid and analytic
since the linking is an incremental and light weight process.
9. High Performance: With the use of Just-In-Time compilers Java enables high
performance.
10. Distributed: Java is designed for the distributed environment of the internet.
11. Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to
adapt to an evolving environment. Java programs can carry extensive amount of a run-
time information that can be used to verify and resolve accesses to objects an run-time.
SREZ Page 2
Object Oriented Programming -I B.E. 4th
1. Java language and APIs : This is the front-end communication between the developer and
the Java platform.
2. Java Virtual Machine : This is the back-end communication between the Java platform and
the underlying hardware.
SREZ Page 3
Object Oriented Programming -I B.E. 4th
Byte code
it is a intermediate representation of a java source code.
it produce by java compiler by compiling java source code
extension of java class file or byte id called .class
it is a platform independent
The Java Virtual Machine (JVM) serves as a runtime environment for executing Java
bytecode, adhering to a standardized specification.
As the name suggests, the JVM operates as a virtual processor, enabling platform-
independent execution of Java programs. T
he cornerstone of Java's platform independence lies in its JVM, which facilitates seamless
operation .
The JVM performs following operation:
Loads code
Verifies code
Executes code
SREZ Page 4
Object Oriented Programming -I B.E. 4th
class Hello
it is a name of a class.
6. String args[]:
- `String args[]` is the parameter declaration, where `String[]` specifies that `args` is an
array of strings. - The name `args` can be any valid Java identifier, but conventionally it
is named `args`, short for "arguments".
Putting it all together, `public static void main(String[] args)` declares a `main` method
that is:
- Accessible from outside the class (`public`).
- Belongs to the class itself, not to instances of the class (`static`).
- Does not return any value (`void`).
- Takes an array of strings as a parameter, which can be used to pass command-line
arguments to the program (`String[] args`).
System.out.println
SREZ Page 5
Object Oriented Programming -I B.E. 4th
out: out is a public static field (instance) of the System class. It represents the standard
output stream, typically the console or command line.
println(): println() is a method of the PrintStream class, which is the type of the out field.
It is used to print a string to the standard output stream
followed by a newline character (\n). The println() method has several overloaded
versions to print different data types.
SREZ Page 6
Object Oriented Programming -I B.E. 4th
double -> float -> long -> int -> char -> short -> byte
1. Identifiers:
- An identifier in Java is a sequence of characters that consists of letters (uppercase or
lowercase), digits, underscores (_), and dollar signs ($).
- The first character of an identifier must be a letter, underscore (_), or dollar sign ($).
- Identifiers cannot contain spaces or special characters (except for underscores and
dollar signs after the first character).
- Java is case-sensitive, so uppercase and lowercase letters are considered different.
SREZ Page 7
Object Oriented Programming -I B.E. 4th
2. Variables:
- In Java, a variable is a named storage location in memory that holds a value of a
particular data type.
- Variables must be declared before they can be used. The declaration specifies the
variable's name and its data type.
- Java supports different types of variables, including primitive types and reference
types.
Example of variable declaration and initialization:
int age = 30; // Declares and initializes the 'age' variable
double salary = 50000.50; // Declares and initializes the 'salary' variable
String name = "John"; // Declares and initializes the 'name' variable
Data types in Java specify how memory stores the values of the variable. Each variable
has a data type that decides the value the variable will hold.
By assigning different data types to variable, you can store integers, decimal or characters
in these variable.
There are 8 Primitive data types in Java – Boolean, char, byte, int, short, long, float, and
double.
byte:
Byte data type is a 8-bit signed two.s complement integer.
Minimum value is -128(-2^7)
Maximum value is 127 (inclusive)(2^7-1)
Default value is 0
Byte data type is used to save space in large arrays, mainly in place of integers since a byte is
four times smaller than an int
Example: byte a=100 byte b=-50
short:
Short data type is a 16-bit signed two's complement integer
Minimum value is -32,768 (-2^15)
SREZ Page 8
Object Oriented Programming -I B.E. 4th
int :
Int data type is a 32-bit signed two's complement integer.
Minimum value is 2,147,483,648.(-2^31)
Maximum value is 2,147,483,647 (inclusive). (2^31-1)
Int is generally used as the default data type for integral values unless there is. concern about
memory.
The default value is 0.
Example: int a=10000 int b=-200000
long:
Long data type is a 64-bit signed two's complement integer.
Minimum value is -9,223,372,036,854,775,808 (-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63-1)
This type is used when a wider range than int is needed.
Default value is 0L..
Example: int a = 100000L, int b = -200000L
float:
Float data type is a single-precision 32-bit IEEE 754 floating point.
Default value is 0.0f.
Float is mainly used to save memory in large arrays of floating point numbers
Float data type is never used for precise values such as currency. Example: float f1 = 234.5f
double:
double data type is a double-precision 64-bit IEEE 754 floating point.
This data type is generally used as the default data type for decimal values. generally the
default choice.
Double data type should never be used for precise values such as currency.
Default value is 0.0d.
Example: double d1 = 123.4
boolean:
boolean data type represents one bit of information.
There are only two possible values: true and false.
This data type is used for simple flags that track true/false conditions.
Default value is false.
Example: boolean one = true
char.:
char data type is a single 16-bit Unicode character.
Minimum value is '\u0000' (or 0).
Maximum value is '\uffff' (or 65,535 inclusive).
SREZ Page 9
Object Oriented Programming -I B.E. 4th
Java provides a rich set of operators to manipulate variable. Java operators can be divide
into the following group:
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used
in algebra. The following table lists the arithmetic operators −
SREZ Page 10
Object Oriented Programming -I B.E. 4th
SREZ Page 11
Object Oriented Programming -I B.E. 4th
Java defines several bitwise operators, which can be applied to the integer types, long, int,
short, char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b =
13; now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators −
Assume integer variable A holds 60 and variable B holds 13 then
SREZ Page 12
Object Oriented Programming -I B.E. 4th
Miscellaneous Operators
instanceof Operator
This operator is used only for object reference variables. The operator checks whether the
object is of a particular type (class type or interface type). instanceof operator is written as −
If the object referred by the variable on the left side of the operator passes the IS-A check for
the class/interface type on the right side, then the result will be true.
SREZ Page 13
Object Oriented Programming -I B.E. 4th
Operator precedence determines the grouping of terms in an expression. This affects how
an expression is evaluated. Certain operators have higher precedence than others; for
example, the multiplication operator has higher precedence than the addition operator −
For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3 * 2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
SREZ Page 14
Object Oriented Programming -I B.E. 4th
Decision making structures have one or more conditions to be evaluated or tested by the
program, along with a statement or statements that are to be executed if the condition is
determined to be true, and optionally, other statements to be executed if the condition is
determined to be false.
Following is the general form of a typical decision making structure found in most of the
programming languages −
3. nested if statement
You can use one if or else if statement inside another if or else if statement(s).
4. switch statement
A switch statement allows a variable to be tested for equality against a list of values.
SREZ Page 15
Object Oriented Programming -I B.E. 4th
if statement :
Syntax of if Statement :
if(Boolean_expression)
{
// Statements will execute if the Boolean expression is true
Working of if Statement :
If the Boolean expression evaluates to true then the block of code inside the if statement
will be executed. If not, the first set of code after the end of the if statement (after the
closing curly brace) will be executed.
Example 1
In this example, we're showing the use of a if statement to check if a value of variable, x
is less than 20. As x is less than 20, the statement within if block will be printed.
if...else statement :
In java, the if else statement is used to execute two code blocks based on the given
condition.
A java if statement executes when the Boolean expression for the if statement is true. An
if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.
Syntax of if-else Statement in Java :
if(Boolean_expression) {
// Executes when the Boolean expression is true
}else {
// Executes when the Boolean expression is false
}
SREZ Page 16
Object Oriented Programming -I B.E. 4th
If the boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.
Example:
In this example, we're showing the usage of if else statement. We've created a variable x and
initialized it to 30. Then in the if statement, we're checking x with 20. As if statement is false,
the statement within the else block is executed.
if-else-if Statement :
The if...else if...else statement is used for executing multiple code blocks based on the
given conditions (Boolean expressions).
An if statement can be followed by an optional else if...else statement, which is very
useful to test various conditions using a single if...else if statement.
Points to Remember
An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
if(Boolean_expression 1) {
// Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2) {
// Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3) {
// Executes when the Boolean expression 3 is true
}else {
// Executes when the none of the above condition is true.
}
SREZ Page 17
Object Oriented Programming -I B.E. 4th
Example
In this example, we're showing the usage of if...else if...else statement. We've created a
variable x and initialized it to 30. Then in the if statement, we're checking x with 10. As if
statement is false, control jumps to else if statement checking another value with x and so
on.
Output
Value of X is 30
The nested if else statement is used for better decision-making when other conditions are
to be checked when a given condition is true. In the nested if else statement, you can have
an if-else statement block the another if (or, else) block.
Syntax of nested if-else statement :
if(condition1){
// code block
if(condition2){
//code block
}
}
Example
The following examples finds the largest number among three using nested if..else statement.
SREZ Page 18
Object Oriented Programming -I B.E. 4th
if(x >= y)
{
if(x >= z)
System.out.println(x + " is the largest.");
else
System.out.println(z + " is the largest.");
} else
{
if(y >= z)
System.out.println(y + " is the largest.");
else
System.out.println(z + " is the largest.");
}
}
}
Output :
30 is the largest.
The Java switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each case.
The switch statement can be used when multiple if-else statement are required. It can have
multiple code blocks along with the case values and executes one of many code blocks based
on the matches case value.
Syntax :
switch(expression) {
case value :
// Statements
break; // optional
case value :
// Statements
SREZ Page 19
Object Oriented Programming -I B.E. 4th
break; // optional
default : // Optional
// Statements
Rules :
The variable used in a switch statement can only be integers, convertable integers (byte,
short, char), strings and enums.
You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.
The value for a case must be the same data type as the variable in the switch and it must
be a constant or a literal.
When the variable being switched on is equal to a case, the statements following that case
will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps
to the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true.
No break is needed in the default case.
Example:
In this example, we're showing use of switch statement where cases are based on a char.
We've created a variable grade. Based on value of grade, each case is checked. if a case is
satisfied and break statement is present then following cases are not checked
public class Test {
switch(grade) {
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
SREZ Page 20
Object Oriented Programming -I B.E. 4th
There are three types of mathematical functions that are commonly used
1.Trigonometric Function
2.Exponent Method
3.Service Method
Trigonometric function
SREZ Page 21
Object Oriented Programming -I B.E. 4th
Exponent method
Service method
LOOPS
While Loop
The Java while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop.
Syntax:
while(condition){
//code to be executed
}
SREZ Page 22
Object Oriented Programming -I B.E. 4th
DO-WHILE LOOP
The Java do-while loop is used to iterate a part of the program several times. If the
number of iteration is not fixed and you must have to execute the loop at least once, it is
recommended to use do-while loop.
The Java do-while loop is executed at least once because condition is checked after loop
body.
Syntax:
do{
//code to be executed
}while(condition);
SREZ Page 23
Object Oriented Programming -I B.E. 4th
FOR LOOP
A simple for loop is the same as C/C++. We can initialize the variable, check condition and
increment/decrement value. It
consists of four parts:
1. Initialization: It is the initial condition which is executed once when the loop starts. Here,
we can initialize the
variable, or we can use an already initialized variable. It is an optional condition.
2. Condition: It is the second condition which is executed each time to test the condition of
the loop. It continues
execution until the condition is false. It must return boolean value either true or false. It is an
optional condition.
3. Statement: The statement of the loop is executed each time until the second condition is
false.
4. Increment/Decrement: It increments or decrements the variable value. It is an optional
condition.
Syntax:
for(initialization;condition;incr/decr){
//statement or code to be executed
}
SREZ Page 24
Object Oriented Programming -I B.E. 4th
Nested loop
If we have a for loop inside the another loop, it is known as nested for loop. The inner loop
executes completely whenever outer loop executes.
The ? : Operator
SREZ Page 25
Object Oriented Programming -I B.E. 4th
We have covered conditional operator ? : in the previous chapter which can be used to
replace if...else statements. It has the following general form −
o Exp1 ? Exp2 : Exp3;
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
To determine the value of the whole expression, initially exp1 is evaluated.
If the value of exp1 is true, then the value of Exp2 will be the value of the whole
expression.
If the value of exp1 is false, then Exp3 is evaluated and its value becomes the value of the
entire expression.
o Example
In this example, we're creating two variables a and b and using ternary operator we've
decided the values of b and printed it.
Break statement
The break statement in Java terminates the loop immediately, and the control of the
program moves to the next statement following the loop.
It is almost always used with decision-making statements (Java if...else Statement).
Here is the syntax of the break statement in Java:
break;
SREZ Page 26
Object Oriented Programming -I B.E. 4th
Nested Break
Labeled Break
SREZ Page 27
Object Oriented Programming -I B.E. 4th
Continue Statement
The continue statement in Java skips the current iteration of a loop (for, while,
do...while, etc) and the control of the program moves to the end of the loop. And, the
test expression of a loop is evaluated.
In the case of for loop, the update statement is executed before the test expression.
The continue statement is almost always used in decision-making statements (if...else
Statement).
It's syntax is:
continue;
SREZ Page 28
Object Oriented Programming -I B.E. 4th
Nested Continue
Labeled Continue
SREZ Page 29