0% found this document useful (0 votes)
3 views

Java Notes week 1-4

The document provides an introduction to Java programming, covering its history, features, and basic structure of Java programs. It explains how to create, compile, and run Java programs, as well as details on Java data types and literals. Additionally, it includes instructions for downloading the Java Development Kit (JDK) and setting up the environment for Java programming.

Uploaded by

mujrim36102
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java Notes week 1-4

The document provides an introduction to Java programming, covering its history, features, and basic structure of Java programs. It explains how to create, compile, and run Java programs, as well as details on Java data types and literals. Additionally, it includes instructions for downloading the Java Development Kit (JDK) and setting up the environment for Java programming.

Uploaded by

mujrim36102
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

CC-121 Object Oriented Programming

Java For Beginners: The Basics of Object-Oriented Programming

Dr. Naeem Aslam Ms. Hira Saleem Ms. Shaista Malik


Head of Department Lecturer Lecturer

Department of Computer Science


NFC-IET Multan
CC-121 Object Oriented Programming

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.1 Some Important Sentences/Features of Java:

 Java is a True object-oriented language.


 Java is an internationalized (used in internet) language.
 Java is a platform (Operating system/Hardware) independent language. In other words Java
language specification can never depend upon operating system or CPU.
 Java is a strongly typed language.

1
CC-121 Object Oriented Programming

2 Evolution of the Java Programming Language:

25 java 23

2
CC-121 Object Oriented Programming

3 The structure of Basic Java Program:

Keyword Class name


1
class MyFirst

{ Access modifier qualifier


method returning
nothing
Built-in class Indicate Array ArrayName (Select
any name like a,b,c
5 6 etc.
3 4
2
public static void main(String [] args) Method Parameter
Call outside Calling with class name Starting point of program execution
the class
class
body { MyFirst.main()

main() body
7 System.out.println(“Hello World”);

} Built-in class object method

}
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.

4. void: means method returns nothing.

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

4 How to create and run the java program.

Editing

(Notepad)

Save source code file on Secondary storage device.

Normally Class Name of


MyFirst.java
Source Code file that
contains main() Is the special type of
machine code for Java
Virtual Machine
JDK
Compiling

(javac)
 JDK = Java
Tool available in JDK Bin folder
Development Kit
 JRE = Java
Runtime
Environment
MyFirst.class  JVM = Java
Virtual Machine
(Byte code)

Take Input by JRE

JRE
Java Virtual Machine (JVM)

Interpreter (java)

(Just-in time compiler)

Tool Available in JDK bin folder or JRE bin


folder

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.

5 How to download JDK?

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.

6 How to set a path?


Path setting is required for the availability of javac and java tools (available at JDK bin folder) at any
drive and folder. Path is the operating system level variable. Which is initialize when command
prompt is loaded into the memory.

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

6.1 Compiling the Program:

To compile the MyFirst program, execute the compiler, javac, specifying the name of the

source file on the command line, as shown here:

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

When the program is run, the following output is displayed:

7
CC-121 Object Oriented Programming

7 A Second Short Program:

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.

When the program is run, the following output is displayed:

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.

Data Size Range


Type
byte 1 byte -128 to 127
short 2 bytes -32,768 to 32,767
int 4 bytes -2,147,483,648 to 2,147,483,647
long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Java does not support unsigned data types for primitive types. All numeric types (byte, short,
int, long, float, double) in Java are signed, meaning they can be used to store both positive and
negative values.
Size Precision/Accuracy Range
float
4 bytes 7 decimal digits -45 to 38
double 8 bytes 16 decimal digits –324 to +308 range

char 2 bytes, stores Unicode characters (0 to 65,535)


boolean 1-bit logical value (true/false), stored as 1 byte for memory alignment.

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

public static void main(String args[])

int lightspeed;

long days; // Take it long for expression “days * 24 * 60 * 60”

long seconds;

long distance; // Take it long for the expression “lightspeed * seconds”

lightspeed = 186000;
days * 24 * 60 * 60
days = 1000;
long int int int

seconds = days * 24 * 60 * 60; long

long
distance = lightspeed * seconds;
long
System.out.print("In " + days);

System.out.print(" days light will travel about ");

System.out.println(distance + " miles.");

This program generates the following output:

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:

// Compute the area of a circle.

class Area

public static void main(String args[])

double pi, r, a;

r = 10.8; // radius of circle

pi = 3.1416; // pi, approximately

a = pi * r * r; // compute area

System.out.println("Area of circle is " + a);

This program generates the following output:

char:

Here is a program that demonstrates char variables:

// Demonstrate char data type.

class CharDemo

11
CC-121 Object Oriented Programming

public static void main(String args[])

char ch1, ch2;

ch1 = 88; // code for X

ch2 = 'Y';

System.out.print("ch1 and ch2: ");

System.out.println(ch1 + " " + ch2);

This program displays the following output:

You can add two characters together, or increment the value of a character variable. Consider the
following program:

// char variables behave like integers.

class CharDemo2

public static void main(String args[])

char ch1;

ch1 = 'X';

System.out.println("ch1 contains " + ch1);

ch1++; // increment ch1

12
CC-121 Object Oriented Programming

System.out.println("ch1 is now " + ch1);

The output generated by this program is shown here:

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.

Here is a program that demonstrates the boolean type:

// Demonstrate boolean values.

class BoolTest

public static void main(String args[])

boolean b;

b = false;

System.out.println("b is " + b);

b = true;

System.out.println("b is " + b);

// a boolean value can control the if statement

if(b) System.out.println("This is executed.");

13
CC-121 Object Oriented Programming

b = false;

if(b) System.out.println("This is not executed.");

// outcome of a relational operator is a boolean value

System.out.println("10 > 9 is " + (10 > 9));

The output generated by this program is shown here:

9 A Closer Look at Literals

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:

Any whole value number is an integer literal.

May be positive or negative

e.g. 2,-2,30.

 Works on Decimal Number System (DNS) (Base 10) (0,1,2,3,4,5,6,7,8)


Normal decimal numbers cannot have a leading zero.

 Works on Octal Number System (Base 8) (0,1,2,3,4,5,6,7)


int a= 024; // Octal int literal

14
CC-121 Object Oriented Programming

Octal values are denoted in Java by a leading zero.

 Works with Hexadecimal Number System (Base 16) (0-9, A-F)


int a = 0x14; // Hexadecimal int literal

Hexadecimal values are denoted in Java by a leading 0x or 0X.

long literal:

long a = 9223372036854775807L; // long literal

A long iteral in Java is suffixed with the letter L.


We can also specify integer literals using binary. To do so, prefix the value with 0b or 0B. For example,
this specifies the decimal value 10 using a binary 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:

 Floating-point numbers represent decimal values with a fractional component.


 They can be expressed in either standard or scientific notation.
float literal:

float a = 2.5f or 2.5F; // float literal

Standard notation consists of a whole number component followed by a decimal point followed by a fractional
component.

float a = 6.022E23f; // float exponential literal

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:

double a = 2.5d or 2.5D or 2.5; // 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.

12.2 = (1 x 161 + 2 x 160 + 2 x 16-1) x 22 


2x = 0.125

= (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.

For octal For hexadecimal


For octal notation, use the backslash followed by the For hexadecimal, you enter a backslash-u ( \u),
three-digit number then exactly four hexadecimal digits.

' \141' ' \u0061'


141 = 1 x 82 + 4 x 81 + 1 x 80 0061 = 0 x 163 + 0 x 162 x 6 x 161 + 1 x 160
= 64+32+1 = 0 + 0 + 96 + 1
= 97 -> letter ‘a’ = 97 -> letter ‘a’

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\""

9.1 Java Literals Summary:

Type of Literal Description Examples

Integer Literals Whole numbers that can be positive, int a = 2;


negative, or zero. int b = -30;

Decimal System Normal whole numbers (cannot have a int x = 123;


(Base 10) leading zero).

Octal System Numbers starting with a leading 0. int x = 024;


(Base 8)
Hexadecimal Numbers starting with 0x or 0X. int x = 0x14;
(Base 16)
Binary Literals Numbers prefixed with 0b or 0B. int x = 0b1010;

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

Escape Sequence Effect with Escape Sequence


\ddd System.out.println("Octal character \\101: " + '\101');
Octal character (ddd)

\uxxxx System.out.println("Hexadecimal Unicode \\u0041: " + '\u0041');


Hexadecimal Unicode character
(xxxx)
\' System.out.println("Single quote: \'Hello\'");
Single quote

\" System.out.println("Double quote: \"Hello\"");


Double quote

\r System.out.println("Carriage return: ");


Carriage return System.out.println("First Line\r1st Line");

\n System.out.println("New line: ");


New line (also known as line System.out.println("First Line\nSecond Line");

feed)

\\ System.out.println("C:\\nfc\\tc\\xyz.java");
Backslash

\f System.out.println("Form feed (\\f): First Line\fSecond Line");


Form feed

\t System.out.println("Tab (\\t): First Column\tSecond Column");


Tab

\b System.out.println("Backspace (\\b): Text\b\b");


Backspace

19
CC-121 Object Oriented Programming

10.1 Type Conversion and Casting

Conversion of one datatype into another datatype is called type casting.

Typecasting

Implicit Explicit
(Widening) (Narrowing)

10.2 Java’s Automatic Conversions:


When one type of data is assigned to another type of variable, an automatic type conversion

will take place if the following two conditions are met:

 The two types are compatible.


Widening Conversion
 The destination type is larger than the source type.

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

Here is a simple program demonstrating widening type casting:

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 program generates the following output:

 char and boolean are not compatible with each other.


 Java also performs an automatic type conversion when storing a literal integer constant into
variables of type byte, short, long, or char.

int a = 88;  char ch1 = 88; 


char ch = a; // automatically converts into char and print X

10.3 Casting Incompatible Types (Narrowing Type Conversion):


If we want to assign a value of a larger data type to a smaller data type, we perform explicit type
casting or narrowing.

 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;

// …

b = (byte) a; 257 % 256 - > 1

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

public static void main(String args[])

byte b;

int i = 257;

double d = 323.142;

System.out.println("\nConversion of int to byte.");

b = (byte) i;

System.out.println("i and b " + i + " " + b);

System.out.println("\nConversion of double to int.");

i = (int) d;

System.out.println("d and i " + d + " " + i);

System.out.println("\nConversion of double to byte.");

b = (byte) d;

System.out.println("d and b " + d + " " + b);

24
CC-121 Object Oriented Programming

This program generates the following output:

10.4 Automatic Type Promotion in Expressions:


byte, short, and char are automatically converted into int.

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

a*b is performed using integers—not bytes.

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);

which yields the correct value of 100.

10.5 The Type Promotion Rules:

They are as follows:

 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

public static void main(String args[])

byte b = 42;

char c = 'a';

short s = 1024;

int i = 50000;

float f = 5.67f;

double d = .1234;

double result = (f * b) + (i / c) - (d * s);

System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));

System.out.println("result = " + result);

Let’s look closely at the type promotions that occur in this line from the program:

double result = (f * b) + (i / c) - (d * s);


short
float byte int char double

float int double

float

double

27
CC-121 Object Oriented Programming

11 Expression:
An expression is the combination of operator(s) and operand(s).

11.1 Steps for Building an Expression:


1. Choose right operator
2. Select/check correct precedence order according to requirement of expression.
3. Check correct association according to requirement of expression evaluation.
4. Check type casting of each operand after every operator evaluation.
For example:

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).

The below diagram depicts the different types of operators in Java:

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

Ternary Binary Unary


Operator Operator Operator

Binary Operator: The operator having 2 operands is called binary operator.


+
For example: a+b
-
a–b * These all are binary operator

%
Unary Operator: The operator having one operand is called unary operator.

+ unary plus

- unary minus
Unary
For example: -2 , -a , 2 – (- 1)
Binary

Ternary Operator: Operator having three operands is called ternary operator.

For example: ? : (Conditional operator)

max = (a>b) ? a : b;

29
CC-121 Object Oriented Programming

11.5 Arithmetic operators:


Operator Meaning
-,+ Unary Minus and Unary Plus ( -a , +4)
+ Add

Applicable on - Subtract
all numeric
Data Type. * Multiply
/ Divide
% Remainder (Modulus Operator)

11.6 Implicit Type Casting During Arithmetic operation:

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.

11.6.1 What is the implicit/automatic conversion rule of the compiler?

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.

8 bytes with 4 bytes with


8 bytes 4 bytes 2 bytes 1 byte
precision and precision and
range range

double float long int short byte


Higher order Lower order
Data Type Data Type

 Now first of all we will discuss about addition.

int type literal 2+4 int type literal

It will give us 6 which is int type literal.

30
CC-121 Object Oriented Programming

double type literal 2.0 + 4 int type literal

int type literal is automatically converts into double


type literal, because double is a higher order data
type, the end result is 6.0 which is double type
literal

 Now we will discuss about division


When both operands are of int, the result of division is int.

int type literal 1/2 int type literal

It will give us 0 which is int type literal

 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

It will give us 0.5 which is double type literal

31
CC-121 Object Oriented Programming

11.7 Summary of Integer and Real Type Conversions during division:


A few practical examples shown in the following table:

Operation Result Operation Result


5/2 2 2/5 0
5.0 / 2 2.5 2.0 / 5 0.4
5 / 2.0 2.5 2 / 5.0 0.4
5.0 / 2.0 2.5 2.0 / 5.0 0.4

11.8 Implicit/Automatic conversion During assignment statement:

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

11.9 Explicit Type Casting:


Programmer required to explicitly cast a value to its targeted data type when:

 data types are compatible to each other; and


 converts higher order data type into the lower order data type.
The syntax of the cast operator is:

(type) expression;

Targeted datatype name Expression may be in the form of variable or Literals or


expression

int k = (int) 2.5; double type literal

11.10 Remainder Operator (Modulus Operator):


 The modulus operator, %, returns the remainder of a division operation. It can be applied to
floating-point types as well as integer types.
 Specially used for digit separation.
3%2 3.5 % 2

Valid operand Valid operand

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

Now reverse this number.

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

public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

int a, fd, sd, res;

System.out.print("Enter a 2-digit number: ");

a = scanner.nextInt();

fd = a % 10;

sd = a / 10;

res = fd * 10 + sd*1;

System.out.println("a = " + a + " and res = " + res);

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

12 Precedence Table (Determine operator evaluation sequence)

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.

12.1 Rules of Operator Precedence:

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:

1. Operators in expressions contained within pairs of parentheses are evaluated first.


Parentheses are said to be at the “highest level of precedence.” In cases of nested, or
embedded, parentheses, such as
((a+b)+c)

the operators in the innermost pair of parentheses are applied first.

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.

4. The assignment operator (=) is evaluated at the end.

 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:

Without parentheses With parentheses

Step 1 3 + 4 * 2 (multiplication first) Step 1 (3 + 4) * 2 (parentheses first)


4 * 2 is 8 (3+4) is 7

Step 2 3 + 8 (addition) Step 2 7 * 2 (multiplication)

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 1 2 + 3 / 4 * 2 % 7 (division first)


3 / 4 is 0
Implicit Type casting rule.

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:

Variable = Variable / Literal / Expression;

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

13.1 Hands on Activity:

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.

13.2 Compound Assignment Statement:

The assignment statement can also be used to assign one value to many variables. This type of
assignment statement is called compound assignment statement.

For example, to assign an integer value 10 to variable a, and b. It is written as:

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.

a = b = 10; a = b = 10 = d = 4; a = b = c = 2.5 = d; LValue not an expression


2 1  4 3 2 1  

39
CC-121 Object Oriented Programming

13.3 Assignment Statement and Compound Assignment Expression:


+= -= *= /= %=
Compiler work more efficiently
in that operator
These have same precedence level and their associativity is R-To-L.

Simple Assignment Statement Compund Assignment Expression


a = a + 9; a + = 9;
a = a - 9; a - = 9;
a = a * 9; a * = 9;
a = a / 9; a / = 9;
a = a % 9; a % = 9;

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

But if we write this expression in this way.

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

Write java program for the following:

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

Precedence Table (Revisited):

High Operator Associativity


() L-To-R
(type) - Unary Minus + Unary Plus R-To-L
* / % L-To-R
+ - L-To-R
Low = *= /= %= -% +% R-To-L

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

14 Increment and Decrement Operator:

 Increment or decrement operator is a unary operator.


 Increment or decrement operator is applicable on variable type operand.
 Increment or decrement operator can never be applicable on constants and expressions.
Thus, the following are invalid use of increment operator:

2 ++
2 = 2+1  Invalid, LValue can never be
literal.

(2*a)++ Invalid

14.1 Increment Operator:


The increment operator is represented by a double plus (++) sign. It is used to add 1 to the value of a
variable. This operator can be used before or after the variable name called the prefix (++a) or
postfix(a++)

++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.

b = ++a *4; b = a++ *3;


2
1 3a = a+1; 1 a*3
2 3a*4 2b= 6
3 2
3 b= 12 3 a = a+1

Assume if int a = 2;

2 2
-4 b = a % a -- - a++ *a; b = -4

a value first incremented by 1 and


0 4 then decremented by 1 so,

-4 a= 2

Effect in System.out.println();
{

int a = 2;

System.out.println("The value is: " + a + " and " + a++);

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

The decrement operator is showing the similar behaviour as an increment operator.

44
CC-121 Object Oriented Programming

Precedence table (Revisited):

High Operator Associativity


() L-To-R
(type) ++ -- prefix - Unary Minus + Unary Plus R-To-L
* / % L-To-R
+ - L-To-R
= *= /= %= -% +% R-To-L
Low postfix ++ -- R-To-L

15 Relational Operators:
Relational operators are used to make conditions. There are six types of relational operators:

< Less than


> Greater than
<= Less than or Equal to
>= Greater than or Equal to
== Equal to
!= Not Equal to

 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.).

 In relational operators, both operands can be literals.


Literals
9<8
0
 Both operands can be variables.

Variables
a<b

 One operand can be variable and other can be literal.

a<9

45
CC-121 Object Oriented Programming

 It is also possible for an operand in a relational operator to be an expression.


a * b < ++b

Let’s assume: int a = 3, b =4;

The steps would be:

 ++b increments b from 4 to 5.


 The expression now looks like 3 * 5 < 5.
 Perform the multiplication: 3 * 5 = 15.
 Compare 15 < 5, which evaluates to false
True condition: False condition:
System.out.println(5 < 10); // true System.out.println(10 < 5); // false
System.out.println(10 * 5 > 5 * 5); // true System.out.println(5 * 5 > 10 * 5); // false
System.out.println(5 + 4 <= 8 + 2); // true System.out.println(8 + 2 < 5 + 4); // false
System.out.println(10 >= 9); // true System.out.println(9 >= 10); // false
System.out.println(10 == 10); // true System.out.println(9 == 10); // false
System.out.println(5 != 10); // true System.out.println(5 != 5); // false

To build/make the Reverse condition?

For example, if temp > 30,

What will be its reverse condition? temp < = 30

 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)

> (greater than) <= (less than or equal to)

<= (less than or equal to) > (greater than)

>= (greater than or equal to) < (less than)

== (equal to) != (not equal to)

!= (not equal to) == (equal to)

46
CC-121 Object Oriented Programming

Precedence Table (Revisited):

High Operator Associativity


() L-To-R
(type) ++ -- prefix - Unary Minus + Unary Plus R-To-L
* / % L-To-R
+ - L-To-R
< > <= >= L-To-R
== != L-To-R
= *= /= %= -% +% R-To-L
Low postfix ++ -- R-To-L

16 Boolean Logical Operators:


The Boolean logical operators shown here operate only on boolean operands. All of the
binary logical operators combine two boolean values to form a resultant boolean value.

Operator Result
& Logical AND
| Logical OR
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT

16.1 Short-circuit Operators:


A short circuit operator is also called as boolean logical operator, but it is much more efficient and
fast as compared to conventional logical operator.

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;

boolean result1= a<10 & b>20; // result = true

boolean result2= a<5 & b> 20; //result = false

47
CC-121 Object Oriented Programming

Short-circuit AND: Short-circuit OR


In case of short circuit AND operator, only left In case of short circuit OR operator, only left
operand is evaluated first and if the output of operand is evaluated first and if the output of the
the operand is false, final output is false. operand is true, final output is true.

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:

if (denom! = 0 && num / denom > 10)

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.

Precedence Table (Revisited):

High Operator Associativity


() L-To-R
(type) ! ++ -- prefix - Unary Minus + Unary Plus R-To-L
* / % L-To-R
+ - L-To-R
< > <= >= L-To-R
== != L-To-R
&& L-To-R
|| L-To-R
= *= /= %= -% +% R-To-L
Low postfix ++ -- R-To-L

48
CC-121 Object Oriented Programming

17 Decision Control Structure


17.1 if statement:

if statement executes the block of statement(s) only when the condition is true.

if statement uses both relational and logical operator.

In C-Language, condition is true for every non-zero numeric value.

17.2 General syntax and the tracing of if statement:

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

Use of Individual if statement for a number judgement whether it is even or odd:

import java.util.Scanner;

class MainMethod
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);

System.out.print("Enter number: ");

int num = scanner.nextInt();

if (num % 2 == 0)
{
System.out.println(num + " is Even");
}

if (num % 2 != 0) Reverse of above condition


{
System.out.println(num + " is Odd");
}
scanner.close();
}
}

Output:

50
CC-121 Object Oriented Programming

17.4 if-else Statement:

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.

The execution of if-else is more efficient than two if conditions.

The source code is more readable form and easy to understand.

17.5 General Syntax of if-else statement:

if(condition)

if condition is false { if condition is true


Statement-1;
}

else

Statement-2;

Statement_outside_if-else;

17.6 Flowchart of if-else statement:

51
CC-121 Object Oriented Programming

17.7 Comparison of if and if-else:


if (num % 2 == 0) if (num % 2 == 0)
{
{
System.out.println(num + " is Even");
} System.out.println(num + " is Even");
}
if (num % 2 != 0)
{ else
System.out.println(num + " is Odd");
{
}
System.out.println(num + " is Odd");
}

17.8 if-else-if statement:

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

17.9 General Syntax of if-else-if statement:

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

17.10 Flowchart of if-else-if statement:

54
CC-121 Object Oriented Programming

17.11 Nested if-structure:

Nested-if structure is very complicated structure.

To eliminate the nested if structure or alternate of if statement enclosed immediately another if


statement. The logical && is often used.

17.12 Flowchart of nested-if structure:

55
CC-121 Object Oriented Programming

Nested if to find out greatest number between Three Numbers:


Assume n1, n2 and n3 are three numbers.

Equivalent to this statement

if (n1 > n2) if (n1>n2)&&(n1>n3)


{ {
if (n1 > n3) System.out.println(n1 + " is the greatest
{ number.");
System.out.println(n1 + " is the }
greatest number.");
}
}

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.

In C based language there are three types of loops.

Loops

for loop while loop do-while loop

18.1 for loop:

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.

18.2 General Syntax of for loop:


for(initialization; condition; expression)
{
Loop_body

18.3 Tracing of for loop:


If condition is false, control exit from here.
1 2

for(initialization; condition; expression)


3
{ 4

Loop_body

58
CC-121 Object Oriented Programming

Example 1

+1 +1 +1 +1

Start point 1 2 3 4 5 End point


Less than To Greater than
< or <=
The value moving from Less than to
Greater than, so operator for
condition is < or <=
If condition is false
Control starts from here
for(i=1; i<=5; i=i+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 >=

The value moving from Greater


than to Less than, so operator for
condition is > or >= If condition is false
100>=92 (T)
98>=92 (T)
for(sp=100; sp>=92;sp=sp-2) 96>=92 (T)
94>=92 (T)
{ 92>=92 (T)
90>=92 (F)

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

Less than To Greater than


The value moving from Less than to
Greater than, so operator for 1>=9 (T)
condition is < or <= If condition is false 3>=9 (T)
5>=9 (T)
for(a= 1 ; a<=9; a=a+2) 7>=9 (T)
9>=9(T)
{ 11>=9(F)

System.out.print("\t" +a);
}
Exit from

Example 4

Start point 1 + 2 + 3 + 4 + 5 End point


Less than To Greater than
The value moving from Less than
to Greater than, so operator for
condition is < or <= int i, sum=0;
for(i=1; i<=5;i=i+1)
{
1 = 0+ 1
3= 1+ 2 sum=sum+i;
6 = 3+3 }
10= 6+4 System.out.print(sum);
15 =10+5 }

60
CC-121 Object Oriented Programming

Example 5

Start point 1 2 3 4 5 End point


Less than To Greater than
The value moving
from Less than to
Greater than, so int i, product=1;
operator for
condition is < or <= for(i=1; i<=5; i=i+1)
{

1 = 1* 1
product=product*i;
2= 1* 2
}
System.out.println(product);
6 = 2*3
}
24= 6 * 4
120 =24*5

Example 6

Start point 1/1 + 1/2 + 1/3 + 1/4 End point


Less than To Greater than
The value moving from int L:
Less than to Greater
than, so operator for double sum=0.0;
condition is < or <=
for(L=1 ; L<=4; L=L+1)
{
sum=sum+1.0/L;
}
System.out.println(sum);
}

61
CC-121 Object Oriented Programming

Comparison:

while loop do-while loop


For loop
General Syntax General Syntax General Syntax

for(initialization; condition; exp) while(condition) do


{ { {
Statement; Statement; Statement;
} } } (Condition);

Flow chart Flowchart Flowchart

 Pre-Test Condition  Pre-Test Condition  Post-Test Condition


Loop Executed when Loop Executed when Loop Executed once without
condition is true condition is true checking the condition

1 2 3 4 5 1 2 3 4 5 1 2 3 4 5

for(i=1;i<=5;i++) i=1; i=1;


{ while(i<=5) do
System.out.print("\t" +i); { {
} System.out.print("\t"
+i); System.out.println(“\t”+i);
i++; i++;
} } while(i<=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

19 Nested for Loop


A loop within a loop is called nested loop.
Example 1:
Input: Output:

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

20 Object Oriented Model:


 Object oriented design is related to real world. In real world everything (living or non-living) is
classify in different classes according to their common attributes and behaviours.
 So big problem is decomposed into different classes and objects.
 In object oriented model class is a basic unit of decomposition.
 Every problem is decomposed according to common attributes and behaviours.

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

21.1 Maintainable Design


In object oriented design the data is decentralized. Every class has its own data members. Due to this
the object oriented design and program is easily more maintainable.

21.2 General Syntax of class:

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

How to create Rectangle class with states and behaviors

Step 1: Step 2:

Create class Add States/instance


New datatype
Rectangle is created variables
class Rectangle
in the form of class class Rectangle
{
{
double width;
} Instance variables
double height; Features or attributes
}

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

Output of the following program:

23 Class Diagram | Unified Modeling Language (UML)


23.1 UML Class Notation
class notation is a graphical representation used to depict classes and their relationships in object-
oriented modeling.

1. Class Name:

The name of the class is typically written in the top compartment of the class box and is centered.

Figure 1The UML class diagram

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.

Figure 2 A class and its attributes

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.

Figure 4 class method

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:

 integer type variables with zero.


 real type variables with 0.0.
 boolean type variables with false.
 char type variables with \0 character.
 any other class type variable with null reference.

74
CC-121 Object Oriented Programming

/***Limitation: No Constructor is available in your Own Class. Then default constructor is


called by JRE and Initialize the data members in default way. ***/

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

/***Create Constructor***/ In the presence of constructor in your own class No default


constructor is called by JRE. The available constructor of our own class is called by JRE.

class A
{
int x;
double y;

Constructor name is similar as class name.


A()
{
x=10;
y=5.6;
}

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

Output of the following program:

/***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

} With parameterized constructor, every object is created


with customized values as happened in real world.
}

77
CC-121 Object Oriented Programming

Output of the following program:

/***Limitation: Every object of class A created with same number of Parameters


Solution: Constructor Overloading ***/

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

You might also like