0% found this document useful (0 votes)
8 views13 pages

OOP in Java Unit3

Java programming unit 3

Uploaded by

free98072fire
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
8 views13 pages

OOP in Java Unit3

Java programming unit 3

Uploaded by

free98072fire
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 13

By: Manoj Sapkota, Nepal Polytechnic Institute

Unit-1: Fundamental Programming Structures

Whitespace: These are the spaces that are used to separate tokens in the
source code such as spaces, tabs and newlines. Proper use of whitespace
improves the readability of the code.

Examples of whitespace:
• Space: Used to separate keywords, variables, operators etc.
int a = 5; //spaces between keyword ‘int’, variable ‘a’, operator ‘=’ and
literal ‘5’.
• Tab: Used for indentation and make the code more readable.
• Newlines: Used to separate statements and make the code readable.

Separators: These are the symbols that are used to separate different parts of
the code and define the structure. Some of the commonly used separators are
as follows:
• Parentheses ( )
• Braces { }
• Brackets [ ]
• Semicolon ;
• Comma ,
• Period .

Comments: These the statements that are not executed by the compiler and
are used to provide information about the lines of code. They make the
program easier to read and understand. They are widely used for documenting
code.

There are two types of comments:


(a) single-line comments: These are represented by double slash (//). Any
text after the ‘//’ till the end of the line will not be executed.
For example:
// This is a single line comment. It will print Hello.
System.out.println(“Given above is a single line comment”);

1
By: Manoj Sapkota, Nepal Polytechnic Institute

(b) multi-line comments: These comments start with /* and ends with */.
Any text between /* and */ will be ignored by the compiler. Multiple lines
of comments can be placed inside them.
For example:
/* This is a multiple line comment.
It will print Hello World. */
System.out.println(“Hello World.”);

Identifiers: These are the names that are used to identify variables, methods,
classes, packages, and other entities in the code. They must follow specific
rules:
• An identifier must start with a letter (A-Z or a-z), currency character ($),
or an underscore (_).
• After the first character, identifiers can contain letters, digits (0-9),
currency characters, and underscores.
• Identifiers are case-sensitive.
• Identifiers cannot be Java keywords.

Examples of valid identifiers:


int myVariable;
int num2;
int my_Name;

Examples of invalid identifiers:


int 5age; //cannot start with a digit
String class; //cannot be a keyword
float total-num; //hyphens are not allowed

Keywords: These are the reserved words that have a predefined meaning in the
language syntax. Their meaning cannot be changed and cannot be used as
identifiers.

Examples of keywords: int, double, if, else, while, for, switch, public, private,
protected, return, void, static, final, class, interface, extends, implements etc.

2
By: Manoj Sapkota, Nepal Polytechnic Institute

Literals: These are the data that are used for representing fixed values. These
are the constant values that are assigned to the variables.

Examples: int a =5;


float b= 2.5;
char c= ‘M’;
Here, 5, 2.5 and ‘M’ are literals.

Variable: A variable is a storage area (location in memory) to hold data. The


value stored in a variable can be changed during program execution. Each
variable is given a unique name to indicate the storage area.

Example: int num=5;


Here, ‘num’ is a variable of ‘int’ data type and we have assigned value 5
to it.

Constant: A constant is an entity whose value cannot be changed once it has


been initialized. Constants are declared using the final keyword. They are often
used to define values that should remain constant throughout the program,
such as mathematical constants, fixed conversion rates etc.

Example: final double PI = 31.4 // constant double


final int days = 7; // constant integer

Once a constant is declared, its value cannot be changed.

Data types: It is a classification that specifies the type of data that can be
stored in variables. All the variables must be declared with their data types
before they can be used.

Example: int num;


Here, the data type of the variable ‘num’ is ‘int’. That means, only integer
type of data can be stored in that variable.

Categories of Data types: There are two categories of data types. They are:
(a) Primitive data types
(b) Non-primitive data types

3
By: Manoj Sapkota, Nepal Polytechnic Institute

(a)Primitive data types: These are the basic data types provided by Java. They
represent only single values and are stored directly in memory.

1. byte type:
• Range: -128 to 127 (8-bit signed integer)
• It is used instead of ‘int’ to save memory, if it is certain that the value
of a variable falls within its range.
• Default value: 0
• Example: byte marks =70;

2. short type:
• Range: -32768 to 32767 (16-bit signed integer)
• It is used instead of other types such as ‘int’ or ‘long’, if it is certain
that the value of a variable falls within its range.
• Default value: 0
• Example: short speed = 150;

3. int type:
• Range: -231 to 231-1 (32-bit signed integer)
• It is generally used to store integers (whole numbers).
• Default value: 0
• Example: int balance = 150000;

4
By: Manoj Sapkota, Nepal Polytechnic Institute

4. long type:
• Range: -263 to 263-1 (64-bit signed integer)
• It is generally used to store integers (whole numbers) of long size.
• Default value: 0
• Example: long phone = 9855078422;

5. float type:
• It is used to store floating-point numbers.
• It is a single-precision 32-bit floating-point.
• Default value: 0.0 (0.0f)
• Example: float kg = 2.5;

6. double type:
• It is used to store floating-point numbers with high precision.
• It is a double-precision 64-bit floating-point.
• Default value: 0.0 (0.0d)
• Example: double price = 2.25;

7. char type:
• It is a 16-bit unicode character.
• Default value: ‘\u0000’
• It is used to store a single character, such as ‘A’ or ‘1’.
• Example: char c = ‘A’;

8. boolean type:
• It has two possible values, either true or false.
• Default value: false
• It is generally used for true/false conditions.
• Example: boolean flag = true;

(b) Non-primitive data types: These are also known as reference types. These
are types that are not predefined in the Java language. They are created by
programmers. Non-primitive data types can store multiple values or complex
objects and include arrays, classes, interfaces etc.

Examples: classes and objects, arrays, interfaces etc.

5
By: Manoj Sapkota, Nepal Polytechnic Institute

Data type conversion: It is the process of converting one data type into
another. There are mainly two types of data type conversion in Java. They are:
1. Automatic (Implicit) type conversion
2. Manual (Explicit) type conversion

1. Automatic (Implicit) type conversion: It is also known as widening


conversion. This is the type of conversion that automatically takes place when
a value of a smaller data type is assigned to a larger data type. This conversion
is safe and does not lose data.

The automatic data type conversion takes place from left side to right side
types as shown in figure above.

Example: int a= 10;


float b = a; // automatic conversion from integer to long type

2. Manual (Explicit) type conversion: It is also known as narrowing conversion.


This is the type of conversion that has to be done manually when a value of a
larger data type is assigned to a smaller data type. This conversion leads to a
data loss or precision loss.

Example: int num=100;


char ch= (char) num; // Explicit type conversion

Operators: These are the special symbols that perform specific operations on
operands and then provide a certain result. They allow to perform arithmetic
and logical operations, compare values, manipulate bits etc.

Examples: int sum = a + b; /// Here, ‘=’ and ‘+’ are operators
boolean r = (a>b); /// Here, ‘>’ is an operator

6
By: Manoj Sapkota, Nepal Polytechnic Institute

Types of operators:
1. Arithmetic operators: These operators are used to perform basic
arithmetic operators. These operators are: +, - , *, / , %
Examples:
int sum= a+b;
int result= a*b;

2. Relational operators: These operators are used to compare two values.


These operators are: >, <, < =, > =, ==, !=
Examples:
boolean a = (a>b);
boolean b = (a == b);

3. Logical operators: These operators are used to combine multiple Boolean


expressions and perform logical operations. These operators are: &&, ||
and !
Examples:
boolean x = a && b; // Logical AND
boolean y= a && b; //Logical OR
boolean z= !a; // Logical NOT

4. Assignment operators: These operators are used to assign values to


variables. These operators are: =, +=, -=, *=, /=, %=
Examples:
a = 5;
a += 2; // Equivalent to a = a + 2

5. Bitwise operators: These operators are used to operate on the bits of


integer data types. These operators are: &, |, ^
Examples:
int x= a & b;
int y = a | b;

6. Conditional operators: It is also known as ternary operator. It is a


shorthand for the if-else statement. Operator: ? :
Example: int result = (condition)? a : b;
(If the condition is true, a will be stored in result otherwise b will
be stored.)

7
By: Manoj Sapkota, Nepal Polytechnic Institute

7. Instanceof operator: It is used to test whether an object is an instance of


a specific class or subclass.
Example:
String s = "Hello";
boolean result = s instanceof String; // result is true

Strings: These are the objects that represent sequences of characters. In Java,
the String class is used to create and manipulate strings.

Declaration and Initialization of strings: Strings in Java can be created in two


ways:
1. Using string literals: Strings can be created by using string literals,
which are enclosed in double quotes:
Example: String str1 = "Hello, World!";

2. Using the new Keyword: Strings can be created by using the new
keyword.
Example: String str2 = new String("Hello, Java!");

Few of the common string operations are as follows:


• Length of a string: The length of the string can be known by using the
method length( ).
Example: String str = “Nepal”;
int len = str.length( ) // 5 is stored in len

• String concatenation: Strings can be concatenated by using the ‘+’


operator.
Example: String str1 = “Hello ”;
String str2= “World”;
String s= str1+ str2; // s becomes “Hello World”

Control Structures: These are the statements that control the flow of
execution in a program. They allow the program to make decisions, repeat
actions, and control the order in which statements are executed. The main
types of control structures in Java are:
1. Decision-Making Structures
2. Looping Structures
3. Branching Structures

8
By: Manoj Sapkota, Nepal Polytechnic Institute

1. Decision-Making Structures: These are the structures that executes


statements by making decisions. These structures are of following types:
a) if statement
b) if-else statement
c) else-if statement (else-if ladder)
d) switch statement

a) if statement: This statement executes a block of code if its condition


evaluates to true.
Example: int a = 10;
if (a > 5) {
System.out.println("a is greater than 5");
}

b) if-else statement: This statement provides an alternative block of code to


execute if the condition is false. It executes first block if the condition is true
otherwise it executes the second block.
Example: int a = 10;
if (a > 15)
{
System.out.println("a is greater than 15");
}
else
{
System.out.println("a is not greater than 15");
}

c) else-if statement (else-if ladder): This statement allows multiple conditions to


be checked in sequence.
Example: int a = 10;
if (a > = 15) {
System.out.println("a is greater than or equal to 15");
} else if (a > 5) {
System.out.println("a is greater than 5 and less than 15");
} else {
System.out.println("a is less than or equal to 5");
}

9
By: Manoj Sapkota, Nepal Polytechnic Institute

d) switch Statement: This statement allows a variable to be tested for equality


against a list of values.
Example: int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
break;
}

2. Looping Structures/(loop): These are the statements that repeat a block of


code until the specified condition is false. Java supports mainly three types of
loops:
a) for loop
b) while loop
c) do-while loop

a) for loop: It is used for iterating a part of the program several times.
Example: for (int i = 1; i < =5; i++) {
System.out.print(" " + i);
}
Output: 1 2 3 4 5

b) while Loop: It repeatedly executes a block of statement until the condition is


false.
Example: int i = 1;
while (i < 5) {
System.out.print(" " + i);
i++;
}

10
By: Manoj Sapkota, Nepal Polytechnic Institute

Output: 1 2 3 4 5
c) do-while Loop: The do-while loop is similar to the while loop, but it checks
the condition after executing the statements. It executes the code at least once
even if the condition is false.
Example: int i = 1;
do {
System.out.print(" " + i);
i++;
} while (i < 5);
Output: 1 2 3 4 5

3. Branching Structures: These are the statements that are used to alter the
control and jump from one part of code to another. These are as follows:
a) break statement
b) continue statement

a) break Statement: It is used to exit from a loop or a switch statement.


Example:
for (int i = 1; i <=5; i++) {
if (i == 3) {
break;
}
System.out.print(" " + i);
}
Output: 1 2

b) continue Statement: It skips the current iteration of a loop and proceeds


with the next iteration.
Example:
for (int i = 1; i <=5; i++) {
if (i == 3) {
continue;
}
System.out.print(" " + i);
}
Output: 1 2 4 5

11
By: Manoj Sapkota, Nepal Polytechnic Institute

c) return Statement: It exits from the current method and may return a value.
Example:
public int add(int a, int b) {
return a + b;
}

Arrays: Arrays are objects that store multiple values of the same type. They
group and manage a collection of related data items.

An array is a fixed-size data structure, meaning its size is specified when it is


created and cannot be changed later. Each element in an array is accessed by
its index, with indexing starting at 0.

Declaring and Creating an Array:


Example of declaration of an Array: int[ ] array;

Example of creating an array: array = new int[5];

Declaration and creation of array can be done in one statement as follows:


int[ ] array = new int[5];

Initializing an Array: An array can be initialized at the time of declaration as


follows:
int[ ] array = {1, 3, 5, 7, 9};

Alternatively, it can also be initialized as follows:


int[ ] array = new int[5];

array[0] = 1;
array[1] = 3;
array[2] = 5;
array[3] = 7;
array[4] = 9;

12
By: Manoj Sapkota, Nepal Polytechnic Institute

Accessing Array Elements: Array elements can be accessed and modified by


using their index as follows:
int a = array[0]; // Accessing the first element
array[1] = 10; // Modifying the second element

Example program: Write a Java program to find the greatest number among 5
input numbers using array.
Solution:

Output: Enter 5 numbers: 3 1 5 9 7


Large= 9

13

You might also like