Module 1
Module 1
NOTES
COMPILED BY:
Mrs. SWATHI R, Assistant Professor
2023-2024
MODULE 1
AN OVERVIEW OF JAVA
Object-Oriented Programming:
Object-oriented programming (OOP) is a computer programming model that organizes software design
around data, or objects, rather than functions and logic. An object can be defined as a data field that has
unique attributes and behavior.
Two Paradigms
Process-oriented/Procedural-oriented model:
This approach characterizes a program as a series of linear steps.
The process-oriented model can be thought of as code acting on data.
Produral languages such as C employ this model to considerable success
Object-oriented programming:
Object-oriented programming organizes a program around its data (that is objects) and a set of
well-defined interfaces to that data.
Object-oriented program can be characterized as data controlling access to code.
All object-oriented programming languages provide mechanisms that help you implement the object-
oriented model. They are abstraction, encapsulation, inheritance, and polymorphism
Encapsulation
Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps
both safe from outside interference and misuse. One way to think about
Encapsulation is as a protective wrapper that prevents the code and data from
being arbitrarily accessed by other code defined outside the wrapper.
Access to the code and data inside the wrapper is tightly controlled through a well-defined
interface.
Inheritance
i) Inheritance is the process by which one object acquires the properties of another object.
ii) It supports the concept of hierarchical classification.
iii) For example, a Golden Retriever is part of the classification dog, which in turn is part of
the mammal class, which is under the larger class animal.
Animal
Mammal
Golden retriever
iv) In the above example Animal Class is a Super class and Mammal and Golden retriever
classes are derived classes.
Polymorphism
i) Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface
to be used for a general class of actions.
ii) More generally, the concept of polymorphism is often expressed by the phrase “one
interface, multiple methods.” This means that it is possible to design a generic interface to a
group of related activities.
iii) An excellent real time example of polymorphism is your Smartphone. The smartphone can
act as phone, camera, music player and what not, taking different forms and hence
polymorphism.
Let’s start by compiling and running the short sample program as shown here.
/*
*/
class Example {
The javac compiler creates a file called Example.class that contains the byte code version of the
program.
Java bytecode is the intermediate representation of the program that contains instructions
the Java Virtual Machine will execute.
javac is not code that can be directly executed.
To actually run the program, you must use the Java application launcher, called java.
To do so, pass the class name Example as a command-line argument, as shown here:
C:\>java Example
/*
*/
class Example {
This line uses the keyword class to declare that a new class is being defined.
The entire class definition, including all of its member will be between the opening curly
brace ({) and the closing curly brace (}).
iii) The next line in the program is the single-line comment, shown here:
This line begins the main( ) method. As the comment preceding it suggests, this is the
line at which the program will begin executing. All Java applications begin execution by calling
main( ). The keyword static allows main( ) to be called without
having to instantiate a particular instance of the class. This is necessary since main( ) is called
by the Java Virtual Machine before any objects are made. The keyword void simply tells the
compiler that main( ) does not return a value. String args[ ] declares a parameter named args,
which is an array of instances of the class String.
v) The next line of code is shown here. Notice that it occurs inside main( ).
/*
*/
class Example2 {
num = num * 2;
System.out.println(num);
When you run this program, you will see the following output:
type var-name;
Here, type specifies the type of variable being declared, and var-name is the name of the
variable.
1. Selection statements
2. Iterative statements
3. Jump statements
Selection statements:
if statement in java
Example:
class IfDemo {
public static void main(String args[])
{
int i = 10;
if (i < 15){
System.out.println("Outside if-block");
// both statements will be printed
}
}
Example:
class IfDemo {
if (i < 15){
}
}
Writing an if statement inside another if-statement is called nested if statement. The general syntax
of the nested if-statement is as follows.
Syntax:
Writing an if-statement inside else of an if statement is called if-else-if statement. The general
syntax of the an if-else-if statement is as follows.
if(condition_1){
condition_1 true-block;
...
}
else if(condition_2){
condition_2 true-block;
condition_1 false-block too;
...
}
Using the switch statement, one can select only one option from more number of options very
easily. In the switch statement, we provide a value that is to be compared with a value associated
with each option. Whenever the given value matches the value associated with an option, the
execution starts from that option. In the switch statement, every option is defined as a case.
The switch statement has the following syntax and execution flow diagram.
import java.util.Scanner;
switch( value )
{
case 0: System.out.println("ZERO") ; break ;
case 1: System.out.println("ONE") ; break ;
case 2: System.out.println("TWO") ; break ;
The while statement is used to execute a single statement or block of statements repeatedly as
long as the given condition is TRUE. The while statement is also known as Entry control
looping statement. The syntax and execution flow of while statement is as follows.
int num = 1;
Output:
10
The do-while statement is used to execute a single statement or block of statements repeatedly as
long as given the condition is TRUE. The do-while statement is also known as the Exit control
looping statement. The do-while statement has the following syntax.
Java Program
public class DoWhileTest {
int num = 1;
do {
System.out.println(num);
num++;
}while(num <= 10);
Output:
10
Syntax:
The initialization portion of the loop sets a loop control variable to an initial value. The
condition is a Boolean expression that tests the loop control variable. If the outcome of that test
is true, the for loop continues to iterate. If it is false, the loop terminates. The iteration
expression determines how the loop control variable is changed each time the loop iterates.
/*
*/
int x;
This is x: 0
This is x: 1
This is x: 2
This is x: 3
This is x: 4
This is x: 5
This is x: 6
This is x: 7
This is x: 8
This is x: 9
In this example, x is the loop control variable. It is initialized to zero in the initialization portion
of the for. At the start of each iteration (including the first one), the conditional test x < 10 is
performed. If the outcome of this test is true, the println( ) statement is executed, and then the
iteration portion of the loop is executed. This process continues until the conditional test is
false.The increment operator is ++. The increment operator increases its operand by one. By use
of the increment operator, the preceding statement can be written like this:
x++;
Thus, the for in the preceding program will usually be written like this:
The for-each statement has the following syntax and execution flow diagram.
for(int i : arrayList) {
System.out.println("i = " + i);
}
Output:
Java allows two or more statements to be grouped into blocks of code, also called code blocks.
This is done by enclosing the statements between opening and closing curly braces. Once a
block of code has been created, it becomes a logical unit that can be used any place that a single
statement can. For example, a block can be a target for Java’s if and for statements.
x = y;
y = 0;
Let’s look at another example. The following program uses a block of code as the target of a for
loop.
/*
*/
class BlockTest {
int x, y;
y = 20;
y = y - 2;
This is x: 0
This is y: 20
This is x: 1
This is y: 18
This is y: 16
This is x: 3
This is y: 14
This is x: 4
This is y: 12
This is x: 5
This is y: 10
This is x: 6
This is y: 8
This is x: 7
This is y: 6
This is x: 8
This is y: 4
This is x: 9
This is y: 2
In this case, the target of the for loop is a block of code and not just a single statement.Thus,
each time the loop iterates, the three statements inside the block will be executed.
Lexical Issues
Whitespace
Java is a free-form language. This means that you do not need to follow any special indentation
rules. In Java whitespace is a space, tab, or newline.
Identifiers
AvgTemp
count
a4
$test
this_is_ok
2count
high-temp
Not/ok
Literals
A constant value in Java is created by using a literal representation of it. For example, here are
some literals:
"This is a test"-string
Comments:
Separators
There are 50 keywords currently defined in the Java language .These keywords are
combined with the syntax of the operators and separators, form the foundation of the Java
language. These keywords cannot be used as names for a variable, class, or method.
The two of Java’s built-in methods: println( ) and print( ) and these methods are members of
the System class, which is a class predefined by Java that is automatically included in your
programs. In the larger view, the Java environment relies on several built-in class libraries that
Data Types
1) byte
2) short
3) int
4) long
5) char
6) float
7) double
8) boolean.
The primitive types are also commonly referred to as simple types, and both terms will be
used in this book. These can be put in four groups:
In Integer Fl floating-point Characters Boolean
byte float char boolean
short
double
long
Integers
Java defines four integer types: byte, short, int, and long. All of these are signed, positive and
negative values. Java does not support unsigned, positive-only integers.
Long 64 –
9,223,372,036,854,775,808
to
9,223,372,036,854,775,807
Int 32 –2,147,483,648 to
Example program:
class Light {
int lightspeed;
long days;
long seconds;
long distance;
lightspeed = 186000;
Floating-point numbers, also known as real numbers, are used when evaluating expressions that
require fractional precision. There are two types:
Double 64 64 4.9e–324 to
1.8e+308
Example program:
class Area {
double pi, r, a;
a = pi * r * r; // compute area
Characters
class CharDemo {
ch2 = 'Y';
Output:
Boolean
Java has a primitive type, called boolean, for logical values. It can have only one of two
possible values, true or false.
class BoolTest {
boolean b;
b = false;
b = true;
b = false;
Output:
b is false
b is true
This is executed.
10 > 9 is true
Integer Literals:
Integers are probably the most commonly used type in the typical program. Any whole number
value is an integer literal.
Floating-Point Literals:
Floating-point numbers represent decimal values with a fractional component. They can be
expressed in either standard or scientific notation. Standard notation consists of a whole number
component followed by a decimal point followed by a fractional component.
Boolean literals are simple. There are only two logical values that a boolean value can have,
true and false. The values of true and false do not convert into any numerical representation.
The true literal in Java does not equal 1, nor does the false literal equal 0. In Java, they can only
be assigned to variables declared as boolean, or used in expressions with Boolean operators.
Character Literals
Characters in Java are indices into the Unicode character set. They are 16-bit values that can
be converted into integers and manipulated with the integer operators, such as the addition
String Literals
String literals in Java are specified like they are in most other languages—by enclosing
a sequence of characters between a pair of double quotes. Examples of string literals are
“Hello World”
“two\nlines”
“\”This is in quotes\”“
\’ Single quote
\” Double quote
\\ Backslash
\r Carriage return
\n New line
\t Tab
\b Backspace
Variables
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables have a
scope, which defines their visibility, and a lifetime.
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a variable
declaration is shown here:
To declare more than one variable of the specified type, use a comma separated list.
Dynamic Initialization
Although the preceding examples have used only constants as initializers, Java allows variables
to be initialized dynamically, using any expression valid at the time the variable is declared.
Example program:
// c is dynamically initialized
defined by a class
defined by a method.
class Scope {
x = 10;
x = y * 2;
In Java, type casting is a method or process that converts a data type into another data type in both
ways manually and automatically. The automatic conversion is done by the compiler and manual
conversion performed by the programmer.
Converting a lower data type into a higher one is called widening type casting. It is also known
as implicit conversion or casting down. It is done automatically. It is safe because there is no
chance to lose data. It takes place when:
byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other. Let's see
an example.
WideningTypeCastingExample.java
Output
In the above example, we have taken a variable x and converted it into a long type. After that, the
long type is converted into the float type.
Converting a higher data type into a lower one is called narrowing type casting. It is also known
as explicit conversion or casting up. It is done manually by the programmer. If we do not perform
casting then the compiler reports a compile-time error.
double -> float -> long -> int -> short -> byte
In the following example, we have performed the narrowing type casting two times. First, we
have converted the double type into long data type after that long data type is converted into int
type.
NarrowingTypeCastingExample.java
double d = 166.66;
long l = (long)d;
int i = (int)l;
Output
Arrays
An array is a group of like-typed variables that are referred to by a common name. Array
element is accessed by its index. Arrays offer a convenient means of grouping related
information.
One-Dimensional Arrays
A one-dimensional array is, essentially, a list of like-typed variables. To create an array, you
first must create an array variable of the desired type. The general form of a one-dimensional
array declaration is
type var-name[ ];
or
Example:
int a[];
or
int[] a;
Example:
a=new int[10];
Example program:
Here is an example that uses a one-dimensional array. It finds the average of a set
of numbers.
class Average {
double result = 0;
int i;
Multidimensional Arrays
Output:
1 2 3
2 4 5
4 4 5
output:
01234
56789
10 11 12 13 14
15 16 17 18 19
When you allocate memory for multi-dimensional array, you need to specify the memory for the
first dimension. Remaining dimensions separately
Ex : int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
Initializing two dimensional array
Example :
// Initialize a two-dimensional array.
class Matrix {
public static void main(String args[]) {
double m[][] = {
{ 0*0, 1*0, 2*0, 3*0 },
{ 0*1, 1*1, 2*1, 3*1 },
{ 0*2, 1*2, 2*2, 3*2 },
{ 0*3, 1*3, 2*3, 3*3 }
};
int i, j;
for(i=0; i<4; i++) {
for(j=0; j<4; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
}
}
When you run this program, you will get the following output:
0.0 0.0 0.0 0.0
0.0 1.0 2.0 3.0
type[ ] var-name;
Example:
The String type is used to declare string variables. You can also declare arrays of strings.
Aquoted string constant can be assigned to a String variable. A variable of type String can
be assigned to another variable of type String. You can use an object of type String as an
argument to println( ).
Example:
System.out.println(str);
Here, str is an object of type String. It is assigned the string “this is a test”. This string is