Java Notes week 1-4
Java Notes week 1-4
1 History of Java
Java does not have an official full form or abbreviation. The name comes from Java coffee, a
type of coffee from Indonesia. Java is not an abbreviation but some programmers made a full
form as "Just Another Virtual Accelerator".
Java was invented in the early 1990s by James Gosling.
James Arthur Gosling OC is a Canadian computer scientist, best known as the founder and
lead designer behind the Java programming language
The first version of the Java Development Kit (JDK) was released on January 23, 1996, and was
originally called Oak.
The first stable version of JDK was JDK 1.0.2, which was also called Java 1. This version
included around 250 classes and applets, but was slow and had many bugs.
The latest version of JDK is JDK 23.
1
CC-121 Object Oriented Programming
25 java 23
2
CC-121 Object Oriented Programming
main() body
7 System.out.println(“Hello World”);
}
1. Class Name:
The basic unit of problem decomposition is a class in Java or object oriented design.
The class name in Java must start with capital Alphabet and remaining alphabets are
small. The class name is in the form of Singular Noun. (Convention not a rule)
When class name is the combination of two words then every word first letter is also
capital.
If the class contains the main() the source code file name is same as the class name
with .java extension.
One source code file contains more than one classes.
2. public: is an access Modifier having highest level of accessibility because main() call occurs
outside the class, so it contain maximum accessibility.
3
CC-121 Object Oriented Programming
3. Static: static qualifier is used to call the method with class Name. Normally method is invoked
with object Name of the class. But static method is invoked with class Name as far as object
name.
5. main: is a method name. main is the starting point of program execution in C-based
languages or control panel of java source code file. main() is called by runtime environment
outside the class. Due to this main() method accessibility is public. Due to static, main is
invoked with class Name and no need to create the object of the class for calling the main()
method.
6. String[] args or String arg[] or String[] a: is the formal String array parameter of the main()
that received the value from command line at time of running the program. String is built-in
class in java since JDK 1.0 in java.lang package. [] symbol is used for array and arg is the string
Array Name.
C:\ > java MyFirst 1 2 3
args[0] args[1] args[2]
“1” “2” “3”
7. System.out.println(“Hello World”);
Or System.out.println(“Value:” +a); Equivalent to System.out.print(“Value:” +a+ “\n”);
is a escape sequence.
4
CC-121 Object Oriented Programming
Editing
(Notepad)
(javac)
JDK = Java
Tool available in JDK Bin folder
Development Kit
JRE = Java
Runtime
Environment
MyFirst.class JVM = Java
Virtual Machine
(Byte code)
JRE
Java Virtual Machine (JVM)
Interpreter (java)
Executing
5
CC-121 Object Oriented Programming
Java compiler that is” javac” creates a file with “.class” extension called bytecode file.
A byte code is a special form of machine code for java virtual machine (JVM).
Java interpreter is called” java” and it’s also called just-in-time compiler.
To download the JDK (Java Development Kit), go to the official Oracle website, navigate to the Java SE
Downloads page, and select the appropriate download option for your operating system based on
your system specifications.
Due to this java source code file can be saved at any drive and folder.
Steps:
1. Access System Properties: Right-click the My Computer icon and select "Properties."
2. Open Advanced System Settings: In the System window, click on "Advanced system settings."
3. Access Environment Variables: Under the "Advanced" tab, click on the "Environment Variables"
button.
4. Edit User Variables: In the "Environment Variables" window, under "User variables," find and
select the "Path" variable.
5. Edit Path Variable: Click on the "Edit" button to modify the Path variable.
6. Add Java Bin Directory: Click "New" and add the path to your Java bin directory (e.g., C:\Program
Files\Java\jdk-23\bin) by using browse option (not typed manually).
7. Confirm Changes: Click "OK" to save the changes to the environment variables.
6
CC-121 Object Oriented Programming
To compile the MyFirst program, execute the compiler, javac, specifying the name of the
C:\>javac MyFirst.java
name of the source file
The javac compiler creates a file called MyFirst.class that contains the bytecode version of the
program. The Java bytecode is the intermediate representation of your program that contains
instructions the Java Virtual Machine will execute. Thus, the output of javac is not code that can be
directly executed.
To actually run the program, you must use the Java Runtime Environment (JRE) that contains Java
Virtual Machine (JVM). The JVM having Just-in-time compiler in the form of java tool. To do so, pass
the class name MyFirst as a command-line argument (actually MyFirst.class i.e. bytecode file but
never mentioned .class extension) as shown here:
C:\>java MyFirst
class name
7
CC-121 Object Oriented Programming
class MyFirstWithVariable
{
public static void main(String[] arg)
{
int a = 20;
System.out.print("a=" + a);
}
} In this statement, the plus sign causes the value of a to be appended to the string that precedes it,
and then the resulting string is output. Actually, a is first converted from an integer into its string
equivalent and then concatenated with the string that precedes it. Using the + operator, you can
join together as many items as you want within a single println( ) statement.
class MyFirstTable
{
public static void main(String[] arg)
{
System.out.print(2 + "*" + 1 + "=" + (2*1) + "\n");
System.out.print(2 + "*" + 2 + "=" + (2*2) + "\n");
System.out.print(2 + "*" + 3 + "=" + (2*3) + "\n");
}
}
When the program is run, the following output is displayed:
8
CC-121 Object Oriented Programming
8 Datatype
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean.
9
CC-121 Object Oriented Programming
long:
long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to
hold the desired value. The range of a long is quite large. This makes it useful when big, whole
numbers are needed. For example, here is a program that computes the number of miles that light
will travel in a specified number of days:
class Light
int lightspeed;
long seconds;
lightspeed = 186000;
days * 24 * 60 * 60
days = 1000;
long int int int
long
distance = lightspeed * seconds;
long
System.out.print("In " + days);
10
CC-121 Object Oriented Programming
Clearly, the result could not have been held in an int variable
double:
Here is a short program that uses double variables to compute the area of a circle:
class Area
double pi, r, a;
a = pi * r * r; // compute area
char:
class CharDemo
11
CC-121 Object Oriented Programming
ch2 = 'Y';
You can add two characters together, or increment the value of a character variable. Consider the
following program:
class CharDemo2
char ch1;
ch1 = 'X';
12
CC-121 Object Oriented Programming
Booleans:
Java has a primitive type, called boolean, for logical values. It can have only one of two possible
values, true or false. This is the type returned by all relational operators, as in the case of a < b.
boolean is also the type required by the conditional expressions that govern the control statements
such as if and for.
class BoolTest
boolean b;
b = false;
b = true;
13
CC-121 Object Oriented Programming
b = false;
Literals:
Assigning a constant value to a variable or using constant value in an expression is called literal.
a = 20;
20 is a literal
Integer literals:
int literal:
e.g. 2,-2,30.
14
CC-121 Object Oriented Programming
long literal:
int x = 0b1010;
128 64 32 16 8 4 2 1
0 0 0 0 1 0 1 0
We can use underscores to make large numbers easier to read in Java. These underscores are
ignored by the compiler. For example,
int x = 123_456_789;
Here, x is assigned the value 123,456,789, but the underscores are simply for visual clarity.
Underscores are only allowed between digits. They cannot place them at the start or end of
the number. Multiple underscores are also allowed. For example:
int x = 123___456___789;
Underscores are also helpful for grouping digits in binary numbers, making them easier to
understand. For example, binary digits are often grouped in sets of four:
int x = 0b1101_0101_0001_1010;
15
CC-121 Object Oriented Programming
Floating-Point Literals:
Standard notation consists of a whole number component followed by a decimal point followed by a fractional
component.
Scientific notation uses a standard-notation, floating-point number plus a suffix that specifies a power
of 10 by which the number is to be multiplied. The exponent is indicated by an E or e followed by a
decimal number,literals
Floating-point which in
can be default
Java positivetoordouble
negative.
precision
double literal:
We can also specify a number as a double literal by adding D or d at the end. However, this is not
necessary.
Hexadecimal floating-point literals are also supported, but they are rarely used. They must be
in a form similar to scientific notation, but a P or p, rather than an E or e, is used.
For example, 0x12.2P2 is a valid floating-point literal
The value following the P, called the binary exponent, indicates the
power-of-two by which the number is multiplied.
= (16 + 2 + 0.125 ) x 4
= 72.5
Therefore, 0x12.2P2 represents 72.5
16
CC-121 Object Oriented Programming
Boolean Literals:
Required by relational, conditional and control expressions (if, for etc.)
Two logical literals: true or false.
Never equal to 0 or 1. In java true is true literal and false is false literal.
Boolean literals are only assigned to the variables declared as boolean or used in expressions
with Boolean operators (like relational and logical etc.).
Character Literals:
Character literal in java support Unicode character set.
All of the visible ASCII characters can be directly entered inside the quotes, such as ‘a’, ‘z’,
and ‘@‘.
For some characters that are impossible to enter, these are several escape sequences
which allow us to enter any character.
' \' ' for the single-quote character
' \n' for the newline character.
There is also a mechanism which allow us to enter the value of character in octal and
hexadecimal.
String Literals:
Enclosed in double quotes
They must begin and end on the same line.
There is no line-continuation escape sequence as there is in some other languages.
17
CC-121 Object Oriented Programming
For example:
"Hello World"
"two\nlines"
" \"This is in quotes\""
Long Literals Whole numbers suffixed with L or l for long long x = 9223372036875807L;
integers.
Floating-Point Decimal values with a fractional component, float x = 2.5f;
Literals using f/F for float. float y = 6.02E23f;
Double Literals By default, floating-point literals are double. double x = 2.5;
Use d/D optionally. double y = 2.5D or 2.5d ;
double z = 6.02E23;
Hexadecimal Rarely used; uses P / p instead of E/e. double x = 0x12.2P2;
Floating-Point
Boolean Literals Boolean literals: true or false. boolean b = true;
boolean b= false;
Character Literals Single character enclosed in single quotes. 'a', '\n', '\141', '\u0061'
Supports escape sequences.
String Literals Sequence of characters enclosed in double "Hello World", "two\nlines"
quotes.
18
CC-121 Object Oriented Programming
10 Escape sequence
feed)
\\ System.out.println("C:\\nfc\\tc\\xyz.java");
Backslash
19
CC-121 Object Oriented Programming
Typecasting
Implicit Explicit
(Widening) (Narrowing)
When these two conditions are met, a widening conversion takes place.
For widening conversions, the numeric types, including integer and floating-point types, are
compatible with each other.
20
CC-121 Object Oriented Programming
Input:
class WideningConversion
{
public static void main(String[] args)
{
byte a = 50;
short s = a; // byte to short (widening type casting)
System.out.println(" Value of s is:" + s);
}
}
This program generates the following output:
There are no automatic conversions from the numeric types to char or boolean.
Here is a simple program demonstrating no automatic conversion from int to char:
Input:
class WideningConversion1
{
public static void main(String[] args)
{
int a = 50;
char ch = a;
System.out.println(" Value of ch is:" + ch);
}
}
21
CC-121 Object Oriented Programming
This is useful for incompatible data types where automatic conversion cannot be done.
Here, the target type specifies the desired type to convert the specified value to.
To create a conversion between two incompatible types, you must use a cast. A cast is simply an
explicit type conversion. It has this general form:
(target-type) value
22
CC-121 Object Oriented Programming
For example, the following fragment casts an int to a byte. If the integer’s value is larger than the
range of a byte, it will be reduced modulo (the remainder of an integer division by the) byte’s range.
int a = 257;
byte b;
// …
So, answer is 1.
Truncation:
When a floating-point value is assigned to an integer type, the fractional component is lost. If the size
of the whole number component is too large to fit into the target integer type, then that value will be
reduced modulo the target type’s range.
23
CC-121 Object Oriented Programming
The following program demonstrates some type conversions that require casts:
// Demonstrate casts.
class Conversion
byte b;
int i = 257;
double d = 323.142;
b = (byte) i;
i = (int) d;
b = (byte) d;
24
CC-121 Object Oriented Programming
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
The result of the intermediate term a*b easily exceeds the range of either of its byte operands. To
handle this kind of problem, Java automatically promotes each byte, short, or char operand to int
when evaluating an expression. This means that the subexpression
25
CC-121 Object Oriented Programming
As useful as the automatic promotions are, they can cause confusing compile-time errors. For
example, this seemingly correct code causes a problem:
byte b = 50;
b = b * 2;
int
byte int
100 (int)
Thus, the result of the expression is now of type int, which cannot be assigned to a byte without the
use of a cast.
byte b = 50;
b = (byte)(b * 2);
First, all byte, short, and char values are promoted to int, as just described.
Then, if one operand is a long, the whole expression is promoted to long.
If one operand is a float, the entire expression is promoted to float.
If any of the operands are double, the result is double.
26
CC-121 Object Oriented Programming
The following program demonstrates how each value in the expression gets promoted:
class Promote
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
Let’s look closely at the type promotions that occur in this line from the program:
float
double
27
CC-121 Object Oriented Programming
11 Expression:
An expression is the combination of operator(s) and operand(s).
Operands
a* 2
Operator
a+b s
4-3
2*a
11.2 Operators:
Operators are the symbols that are used to perform certain operations on data.
11.3 Operands:
Operands may be constants values (literals), variable names and functions (and those functions that
returns a single value after execution).
28
CC-121 Object Oriented Programming
11.4 Types:
The types of operators are as follows:
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Others operators (Conditional operator)
Depending upon Number of operands, operators are divided into three categories.
Operator type
%
Unary Operator: The operator having one operand is called unary operator.
+ unary plus
- unary minus
Unary
For example: -2 , -a , 2 – (- 1)
Binary
max = (a>b) ? a : b;
29
CC-121 Object Oriented Programming
Applicable on - Subtract
all numeric
Data Type. * Multiply
/ Divide
% Remainder (Modulus Operator)
No arithmetic operation is performed until the compiler makes sure that both operands having the
same data type.
First compiler implicitly / automatically converts both operands into same Data Type.
1. Data Types are compatible (numeric data type is compatible with numeric data type).
2. Convert Lower Order Data Type into Higher Order Data Type.
30
CC-121 Object Oriented Programming
When the operand is int and the other operand is float, the result is float. In this case
compiler implicitly converts the int type operand to float and end result is float.
1 / 2.0f
int float
float
float
0.5f
1.0 / 2
double type literal int type literal
31
CC-121 Object Oriented Programming
int k = 2.5;
In Java, this results in a compile-time error, as Java enforces strict type-checking. Due to this
behavior, Java is considered a more strongly typed language compared to C, where such
implicit conversions are allowed without error.
Input:
class Main
{
public static void main(String[] args)
{
int a = 2.5;
System.out.println("The value of a is:"+a);
}
}
Output:
32
CC-121 Object Oriented Programming
(type) expression;
The remainder operator (%) returns the remainder when two numbers are divided
3%2 42.25 % 10
1 4
2.25
1 2 ⟌3 10 ⟌42.25
2 40
1 Remainder 2.25 Remainder
Note 1:
If LHS operand of remainder operator is less than RHS operand, then LHS operand is treated as
“remainder”.
33
CC-121 Object Oriented Programming
3%5 26 % 30
26
3
Note 2:
The sign with LHS operand of remainder operator must be mentioned with the sign of result.
5 % -3 -5 % 3 -5 % -3
2 -2 -2
Remainder operator has many uses, specially use for digit separation. For example, if number is 25,
and we divide this number by 10 so 2 is quotient and 5 is remainder
2
10 ⟌25
20
5
fd = 25 % 10; 5
sd = 25 / 10; 2
nRev = fd * 10 + sd * 1
5 * 10 + 2 * 1
50 + 2
52
34
CC-121 Object Oriented Programming
Input:
import java.util.Scanner;
class Main
a = scanner.nextInt();
fd = a % 10;
sd = a / 10;
res = fd * 10 + sd*1;
scanner.close();
Output:
35
CC-121 Object Oriented Programming
11.11 Assignments:
1. If a five-digit number is input through the keyboard, write a program to calculate the sum of
its digits. (Hint: Use the modulus operator ‘%’)
2. If a five-digit number is input through the keyboard, write a program to reverse the number.
3. If a four-digit number is input through the keyboard, write a program to obtain the sum of the
first and last digit of this number
4. If a five-digit number is input through the keyboard, write a program to print a new number
by adding one to each of its digits. For example, if the number that is input is 12391 then the
output should be displayed as 23402.
5. Calculate and display the multiplication of two numbers as shown below:
7 6
2 5
3 8 0
1 5 2
1 9 0 0
36
CC-121 Object Oriented Programming
The order or sequence in which operators are evaluated is called precedence order.
Associativity: Refers the order of operators evaluation when operators precedence level is same. The
associativity of operators is either Left-to-Right or Right-to-Left.
Java applies the operators in arithmetic expressions in a precise sequence determined by the
following rules of operator precedence, which are generally the same as those in algebra:
2. Multiplication, division and remainder operations are applied next. If an expression contains
several multiplication, division and remainder operations, evaluation proceeds from left to
right. Multiplication (*), division (/) and remainder (%) are said to be on the same level of
precedence.
3. Addition (+) and subtraction (-) operations are evaluated next. If an expression contains
several addition and subtraction operations, evaluation proceeds from left to right. Addition
and subtraction also have the same level of precedence, which is lower
than the precedence of the multiplication, division and remainder operations.
To overwrite the precedence of Arithmetic operator (+, - ,* , /, %) the small parenthesis are used.
Parentheses are used to overwrite the precedence of arithmetic operators.
37
CC-121 Object Oriented Programming
For example:
Step 3 11 Step 3 14
Example: 2+3/4*2%7
In above expression, the operator /, *, % having same precedence level and the operator ‘+’ having
low precedence than *, /, % so according to associativity of operator, the evaluation sequence is from
L-to-R for *, / , %.
Step 2 2 + 0 * 2 % 7 (multiplication)
0 * 2 is 0
Step 3 2 + 0 % 7 (remainder)
0 % 7 is 0
Step 4 2 + 0 (addition)
Step 5 2
Precedence Table:
High
Operator Associativity
() L-To-R
(type) - Unary Minus + Unary Plus R-To-L
* / % L-To-R
Low + - L-To-R
38
CC-121 Object Oriented Programming
13 Assignment Statement:
LValue RValue
a=b; 2 *a = b;
LValue always variable or container
a=10;
Not Expression 12 = c;
a=10+b;
Not Constant
Not Literal
1. Two numbers are input through the keyboard into two locations C and D. Write a program to
interchange the contents of C and D without creating third variable.
The assignment statement can also be used to assign one value to many variables. This type of
assignment statement is called compound assignment statement.
a = b = 10;
The assignment operator precedence level is same, so now check its associativity. Assignment
operator associativity is Right to Left. So, the value 10 is first assignment to b and then a.
39
CC-121 Object Oriented Programming
a + = b * = 9;
First this expression b = b * 9 will be solved, and then the answer that comes from it will be used to solve the
next one.
Equivalent to
a + = b*2; a = a + (b*2);
Equivalent to
a = a *(b+2); a = a* (b+2);
Suppose a=2;
b=3;
a + = b * 2; 8 a = a + (b*2);
2+6
8
a * = b + 2; a = a * ( b + 2 );
Who has more precedence here? a * b but it's not like that; first, the b + 2 part will be solved because
its associativity is right to left. When solving a compound assignment expression, you need to place
parentheses around the expression on the right side. (b+2) this will solve first.
40
CC-121 Object Oriented Programming
a = a * (b+2); 10 a = a * (b+2);
2*(3+2)
2*5
10
Ramesh’s basic salary is input through the keyboard. His dearness allowance is 40% of basic salary,
and house rent allowance is 20% of basic salary. Write a program to calculate his gross salary.
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Ramesh's basic salary: ");
double basicSalary = scanner.nextDouble();
double dearnessAllowance = basicSalary *40/100;
double houseRentAllowance = basicSalary * 20/100;
double grossSalary = basicSalary + dearnessAllowance + houseRentAllowance;
System.out.println("Ramesh's Dearness Allowance is: " + dearnessAllowance);
System.out.println("Ramesh's HouseRent Allowance is: " + houseRentAllowance);
System.out.println("Ramesh's Gross Salary is: " + grossSalary);
scanner.close();
}
}
Output:
41
CC-121 Object Oriented Programming
13.4 Assignment:
1. The distance between two cities (in km.) is input through the keyboard. Write a program to
convert and print this distance in meters, feet, inches and centimeters.
2. Write a program to assign the numeric value to a variable year. Calculate the number of
months, and print the result on the screen.
3. If the marks obtained by a student in five different subjects are input through the keyboard,
find out the aggregate marks and percentage marks obtained by the student. Assume that the
maximum marks that can be obtained by a student in each subject is 100.
4. Temperature of a city in Fahrenheit degrees is input through the keyboard. Write a program
to convert this temperature into Centigrade degrees
5. The length & breadth of a rectangle and radius of a circle are input through the keyboard.
Write a program to calculate the area & perimeter of the rectangle, and the area &
circumference of the circle.
42
CC-121 Object Oriented Programming
2 ++
2 = 2+1 Invalid, LValue can never be
literal.
(2*a)++ Invalid
++a a++
Prefix operator Postfix operator
Standalone postfix and prefix increment operator having same meaning. Both increase one in
its operand.
Postfix Prefix
a++ ++a
a= a+1 a= a+1
If the value of "a" is 2, whether you do a++ or ++a, both will increase the value of "a" to 3.
a=2
a++ ++a
43
CC-121 Object Oriented Programming
Difference
Prefix and postfix operators have different effects when they are used in
Assume int b = 3, a = 2;
expressions or with other operators.
Assume if int a = 2;
2 2
-4 b = a % a -- - a++ *a; b = -4
-4 a= 2
Effect in System.out.println();
{
int a = 2;
Note: The output will be: The value is: 2 and 2 because in java values are evaluated from left to right.
In pre-incremented ++a it will increase the value by 1 before printing and in post increment
i.e., a++ it will print the value at first, and the value is incremented by 1.
{
int a =2;
System.out.println("The value is: " + a + " , " + ++a + " and " + a++);
}
Note: The output will be: The value is: 2 , 3 and 3
44
CC-121 Object Oriented Programming
15 Relational Operators:
Relational operators are used to make conditions. There are six types of relational operators:
Relational operators in Java return true or false because Java has a built-in boolean data type.
If a condition involving a relational operator evaluates to true, it returns true. Otherwise, it
returns false.
Boolean literals (true or false) are only assigned to the variables declared as boolean or used
in expressions with Boolean operators (like relational and logical etc.).
Variables
a<b
a<9
45
CC-121 Object Oriented Programming
The relational operators are used to make a condition for the reverse of the condition. the
equivalent reversed operators are as under:
Original Operator Reversed Operator
< (less than) >= (greater than or equal to)
46
CC-121 Object Oriented Programming
Operator Result
& Logical AND
| Logical OR
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
In case of boolean AND or OR operators, both operands (left or right) are checked and according to
that boolean value is evaluated
int a = 9;
int b= 25;
47
CC-121 Object Oriented Programming
Because Java will not bother to evaluate the righthand operand when the outcome of the expression
can be determined by the left operand alone.
For example, the following code fragment shows how you can take advantage of short-circuit logical
evaluation to be sure that a division operation will be valid before evaluating it:
Since the short-circuit form of AND (&&) is used, there is no risk of causing a run-time exception
when denom is zero. If this line of code were written using the single & version of AND, both sides
would be evaluated, causing a run-time exception when denom is zero.
48
CC-121 Object Oriented Programming
if statement executes the block of statement(s) only when the condition is true.
if(condition) if(condition)
If condition is true.
If condition is false statement; {
Java-instructions; If condition is statement 1; If condition is
false true
statement n;
}
Java-instructions;
17.3 Flowchart of if statement:
49
CC-121 Object Oriented Programming
import java.util.Scanner;
class MainMethod
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
if (num % 2 == 0)
{
System.out.println(num + " is Even");
}
Output:
50
CC-121 Object Oriented Programming
In if-else structure, the programmer only writes the if condition. The programmer has not to think
about second condition that is the reverse of first one but takes the benefit of else part in if
statement.
if(condition)
else
Statement-2;
Statement_outside_if-else;
51
CC-121 Object Oriented Programming
The programmer is used if-else-if structure when multiple conditions means more than one
conditions are available and one condition is true from out of all the conditions.
Thus if-else-if is more efficient than using the multiple if statement for each condition.
In multiple if statements, all conditions are checked or executed irrespective whether one condition
is true out of all others.
In if-else-if programming construct the conditions are checked from top until first true condition is
met. Then remaining conditions are not even checked or executed.
The statements under the first true conditions are executed and control exit from if-else-if
programming construct irrespective how many remaining conditions are true.
52
CC-121 Object Oriented Programming
if(condition-1)
if first
condition is
{ if first condition is true
false Statement-1;
} if first If none of the
and conditions are
else if(condition-2) second true
condition
{ is false
Statement-2;
else if(condition-3)
Statement-3;
else
else_statement;
Statements_outside_if-else
53
CC-121 Object Oriented Programming
54
CC-121 Object Oriented Programming
55
CC-121 Object Oriented Programming
if(n2>n1) if (n2>n1)&&(n2>n3)
{ {
if(n2>n3) System.out.println(n2 + " is the greatest
{ number.");
System.out.println(n2 + " is the
greatest number.");
} }
}
if (n3>n1)&&(n3>n2)
if(n3>n1) {
{ System.out.println(n3 + " is the greatest
if(n3>n2) number.");
{ }
System.out.println(n3 + " is the
greatest number.");
}
}
56
CC-121 Object Oriented Programming
Comparison:
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
int marks;
char grade;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Marks: ");
marks = scanner.nextInt();
Multiple-if If-else-if
if (marks>=90); if (marks>=90);
{ {
grade=’A’; grade=’A’;
} }
if (marks>=80 && marks <90) else if (marks>=80) // no need to make full condition
{ {
grade=’B’; grade=’B’;
} }
if (marks>=70 && marks <80) else if (marks>=70)
{ {
grade=’C’; grade=’C’;
} }
if (marks>=60 && marks <70) else if (marks>=60)
{ {
grade=’D’; grade=’D’;
} }
if (marks>=50 && marks <60) else if (marks>=50)
{ {
grade=’E’; grade=’E’;
} }
if (marks <50) else
{ {
grade=’F’; grade=’F’;
} }
System.out.println("Grade = " + grade);
scanner.close();}
57
CC-121 Object Oriented Programming
18 Loop
To repeatedly execute a statement or set of statements until condition is true. Then loop
programming construct is used.
Loops
To 10 or 20 or 1000 times etc, to repeatedly execute a statement or set of statements are written
once in the body of loop until condition remains true.
In this way length of the source code file has been significantly reduced.
This improves the readability and writability of the source code file.
Loop_body
58
CC-121 Object Oriented Programming
Example 1
+1 +1 +1 +1
System.out.print("\t" +i);
}
Exit from
Example 2
-2 -2 -2 -2
Start point 100 98 96 94 92 End point
Greater than To Less than
> or >=
System.out.print(("\t" +sp);
}
Exit from
59
CC-121 Object Oriented Programming
Example 3
+2 +2 +2 +2
Start point 1 3 5 7 9 End point
System.out.print("\t" +a);
}
Exit from
Example 4
60
CC-121 Object Oriented Programming
Example 5
1 = 1* 1
product=product*i;
2= 1* 2
}
System.out.println(product);
6 = 2*3
}
24= 6 * 4
120 =24*5
Example 6
61
CC-121 Object Oriented Programming
Comparison:
1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
Activity:
Convert the source code from example No. 1 to example No.6 into while and do-while loops.
62
CC-121 Object Oriented Programming
class MainLoop1
{
public static void main(String args[])
{
for (int i=1;i<=2;i++)
{
for (int j=1;j<=5;j++)
{
System.out.print("*");
}
System.out.println();
}
}
}
Example 2:
Input: Output:
class MainLoop2
{
public static void main(String args[])
{
for (int i=1;i<=5;i++)
{
for (int j=1;j<=5;j++)
{
System.out.print("*");
}
System.out.println();
}
}
}
Example3:
63
CC-121 Object Oriented Programming
Input: Output:
class MainLoop3
{
public static void main(String args[])
{
for (int i=1;i<=5;i++)
{
for (int j=1;j<=i;j++)
{
System.out.print("*");
}
System.out.println();
}
}
}
Example 4:
Input: Output:
class MainLoop4
{
public static void main(String args[])
{
for (int i=1;i<=5;i++)
{
for (int j=5;j>=i;j--)
{
System.out.print("*");
}
System.out.println();
}
}
}
64
CC-121 Object Oriented Programming
Example 5:
Input: Output:
class MainLoop5
{
public static void main(String args[])
{
for (int r=1;r<=5;r++)
{
for (int s=1;s<=11+r;s++)
{
System.out.print(" ");
}
for (int c=1;c<=r;c++ )
{
System.out.print("*");
}
System.out.println();
}
}
}
Example 6:
Input: Output:
class MainLoop6
{
public static void main(String args[])
{
for (int r=1;r<=5;r++)
{
for (int s=1;s<=10-r;s++)
{
System.out.print(" ");
}
for (int c=1;c<=r;c++ )
{
System.out.print("*");
}
System.out.println();
}
}
}
65
CC-121 Object Oriented Programming
Example 7:
Input: Output:
class MainLoop7
{
public static void main(String args[])
{
for (int r=1;r<=5;r++)
{
for (int s=1;s<=5;s++)
{
System.out.print(" ");
}
for (int c=1;c<=r;c++ )
{
System.out.print("*");
}
System.out.println();
}
}
}
66
CC-121 Object Oriented Programming
21 Class:
Class is a template or pattern or model that is used to create object.
Class is user defined data type.
Class has two types of Members:
67
CC-121 Object Oriented Programming
class ClassName
{
// Class_Level_Variables (Both Instance and Shared Variables)
dataType VariableName;
// Behaviours / Methods
returnType methodName(List_of_Parameters)
{
return variable/expression/literal; // Method Body
}
// ……More methods
}
22 Object:
Everything which has some properties/attributes (data members of a class) and behaviors
(methods of a class) is called object.
Object is an instance of a class. Every object/instance of the class maintain its own copy of data
members or instance variables of the class.
Everything in real world is an object whether living or non-living.
Every object is classified according to their features and behaviours.
The object having common features and behaviours belongs to same class.
68
CC-121 Object Oriented Programming
Step 1: Step 2:
Step 3:
Add behaviors/methods
class Rectangle
{
double width;
double height;
double area() method
{
return width * height;
}
}
69
CC-121 Object Oriented Programming
How to access Rectangle class states and behaviors in class inside main method:
Step 1:
Synatx:
Create Object
ClassName varName;
class MainDemoRectangle
varName = new ClassName();
{
public static void main(String args[])
{
Rectangle r1= new Rectangle();
// or can be split into Two Statements
Rectangle r1; allocates stack memory to r1
at the time of declaration.
r1=new Rectangle();
new operator used to allocate
}
heap memory for class level
variables at runtime.
Memory Map:
Rectangle r1;
main() Stack
r1 null
r1=new Rectangle();
'0000
main() Stack
default constructor
Heap initializes the real
width 0.0 type variables with
height 0.0 default values 0.0
area()
r1 null 0x001A 0x001A
70
CC-121 Object Oriented Programming
Step 2:
Syntax:
Access members (variables and methods)
objectName.InstanceVariable/method;
class MainDemoRectangle
{
public static void main(String args[])
{
Rectangle r1= new Rectangle();
r1.width= 5.8;
r1.height= 60.5;
double ar = r1.area();
System.out.println(r1.width); // 5.8
System.out.println(r1.height); // 60.5
System.out.println(ar);
}
}
Memory Map:
'0000
main() Stack
Heap
width 5.8
height 60.5
area()
r1 null 0x001A 0x001A
71
CC-121 Object Oriented Programming
1. Class Name:
The name of the class is typically written in the top compartment of the class box and is centered.
2. Attributes:
Attributes, also known as properties or fields, represent the data members of the class. They are listed in
the second compartment of the class box.
Every object of the class has a specific value for every attribue. The object's name starts with a lowercase
letter, followed by a colon, then the class name, and the entire name is underlined.
72
CC-121 Object Oriented Programming
Figure 3 An object has a specific value for each one of its class's attributes
Methods:
Methods, also known as functions or operations, represent the behavior or functionality of the class.
They are listed in the third compartment of the class box.
73
CC-121 Object Oriented Programming
24 Constructor:
Constructor is a special method.
Constructor name is similar as class Name.
Constructor having no return type. Not even a void.
Constructor is called at the time of object creation.
The major purpose of constructor is to initialize the class level variables specially
instance variable of an object.
When no constructor is available in a class, the default constructor is called by Java
Runtime environment.
The default constructor initializes the instance variable with default values:
74
CC-121 Object Oriented Programming
class A
{
int x;
double y;
char c;
A o;
boolean b;
void show()
{
System.out.println(" x="+x + "\t" + "y=" +y + "\t" + "c=" +c + "\t" + "o=" +o + "\t"
+ "b=" +b);
}
}
class MainDemo
{
public static void main(String[] arg)
{
A obj = new A();
default constructor is called
obj.show();
}
}
Output of the following program:
75
CC-121 Object Oriented Programming
class A
{
int x;
double y;
void show()
{
System.out.println(" x="+ x + "\t" + "y=" + y);
}
}
class MainDemo1
{
public static void main(String[] arg)
{
A obj = new A();
obj.show();
}
}
76
CC-121 Object Oriented Programming
/***Limitation: Without parameter constructor initialize instance variables for each object of
the class A with same values. Solution: Use Parameterized Constructor ***/
class A
{
int x;
double y;
A(int i, double j)
{ Formal parameters
x=i;
y=j;
}
void show()
{
System.out.println(" x="+ x + "\t" + "y=" + y);
}
}
class MainDemo3
{
public static void main(String[] arg)
{
A obj = new A(10,20.5);
obj.show(); Actual parameters
77
CC-121 Object Oriented Programming
25 Constructor overloading:
When a class having more than one constructor, then call of constructor is resolved with
number of parameters or type of parameters or with both.
Benefit:
Every object created by the programmer by calling the relevant constructor according to the
requirement.
class A
{
int x;
double y;
A()
{
x = 10;
y = 5.6;
}
A(int i, double j)
{
x = i;
78
CC-121 Object Oriented Programming
y = j;
}
A(double i)
{
x = (int) i; // Explicit typecasting
y = i;
}
void show()
{
System.out.println("x = " + x + "\ty = " + y);
}
}
public class MainDemo4
{
public static void main(String[] args)
{
A obj1 = new A(600, 0.75); // Constructor with int and double
A obj2 = new A(10.5); // Constructor with double
A obj3 = new A(); // Default constructor
obj1.show();
obj2.show();
obj3.show();
}
}
Output of the following program:
79