M-1 Notes
M-1 Notes
MODULE I
Contents
An Overview of Java:
Object-Oriented Programming (Two Paradigms, Abstraction, The Three OOP
Principles),Using Blocks of Code,
Lexical Issues (Whitespace, Identifiers, Literals, Comments, Separators, The
Java Keywords
Data Types, Variables, and Arrays:
The Primitive Types (Integers, Floating-Point Types, Characters, Booleans),
Variables.
Type Conversion and Casting.
Automatic Type Promotion in Expressions.
Arrays, Introducing Type Inference with Local Variables.
Operators:
Control Statements:
1
MODULE I
Two Paradigms:
Encapsulation:
Encapsulation is the mechanism that binds together code and data it manipulates,
and keeps both safe from outside interference and misuse.
In Java the basis of encapsulation is the class. A class defines the state and
behaviour(data & code) that will be shared by set of objects.
Each object contains the structure and behaviour defined by the class. The data
defined by the class are called instance variables(member variables), the code that
operates on that data are called methods(member functions).
Inheritance:
Inheritance is the process by which one object acquires the properties of another
object. This is important as it supports the concept of hierarchical classification.
By the use of inheritance, a class has to define only those qualities that make it
unique. The general qualities can be derived from the parent class or base class.
Ex: A child inheriting properties from parents.
2
MODULE I
Polymorphism
Polymorphism (meaning many forms) is a feature that allows one interface to be
used for a general class of actions. The specific action determined by the exact nature
of the situation. This concept is often expressed as ― one interface, multiple
methods‖.
Ex: The operator + can be used for addition of 2 numbers and also concatenation of
2 strings. System.out.println(2+4); output is 6 as answer.
System.out.println(“Hello ” + “Gautham”); output is Hello Gautham
Class
A class is a blueprint or prototype from which objects are created.
Abstraction:
Data abstraction refers to providing only essential information to the outside world
and hiding their background details i.e., to represent the needed information in program
without presenting the details.
Ex: a database system hides certain details of how data is stored and created and
maintained
3
MODULE I
Description:
4
MODULE I
Integer Literal
Float/Double Literal
Character Literal
Boolean Literal
String Literal
Comments - Comments can be used to explain Java code, and to make it more
readable. It can also be used to prevent execution when testing alternative
code.
Single-line comments - start with two forward slashes (//). Any text
between // and the end of the line is ignored by Java (will not be
executed).
5
MODULE I
Keywords - Java keywords are also known as reserved words. Keywords are
particular words that act as a key to a code. These are predefined words by
Java so they cannot be used as a variable or object name or class name. There
are 51 Java keywords. We have listed a few for reference.
Abstract assert Boolean break byte case
Catch char class Enum continue default
Do double else for exports extends
Final finally instance of int goto if
implements import new open interface long
Module static provides public opens package
Private throw throws super requires return
Short uses void to switch transitive
This try native volatile while with
6
MODULE I
JAVA Class Libraries - The Java Class Library (JCL) is a set of dynamically loadable
libraries that Java Virtual Machine (JVM) languages can call at run time. Because the Java
Platform is not dependent on a specific operating system, applications cannot rely on any of
the platform-native libraries.
Primitive data types - include byte, short, int, long, float, double, Boolean, and char
Non-primitive data types - such as String, Arrays, and Classes (you will learn more
about these in a later chapter)
7
MODULE I
public class
public class DynamicInitialization
DynamicInitialization {{
public static
public static void
void main(String[]
main(String[] args)
args) {{
double a=3;
double a=3;
double b=4;
double b=4;
double cc == Math.sqrt(a*a
double Math.sqrt(a*a ++ b*b);
b*b);
// The above variable c will
// The above variable c will be be initialized
initialized during
during the
the run timerun time
}
}
}
}
Types of Variables and its Scope
1. Instance Variables - A variable that is declared inside a class, but is declared outside
any methods and blocks is known as an instance variable.
8
MODULE I
Type Conversion & Casting - Type casting is when you assign a value of one primitive data
type to another type. In Java, there are two types of casting,
9
MODULE I
Arrays : An array is a group of like-typed variables that are referred to by a common name.
Arrays of any type can be created and many have one or more dimensions. A specific
10
MODULE I
element of the array can be accessed by its index. Arrays offer a convenient means of
grouping related information.
System.out.println(cars[0]);
// Outputs Volvo
Operators
Java provides a rich operator environment. Most of the operators can be divided into 4
groups: Arithmetic, bitwise, relational, and logical.
Operator Result
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
+= Assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
-- Decrement
11
MODULE I
Bitwise Operators – Java defines several bitwise operators that can be applied to the integer
types: long, int, short, char, and byte. They are summarized in the below table.
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment
12
MODULE I
Relational Operators – Java defines several bitwise operators that can be applied to the
integer types: long, int, short, char, and byte. They are summarized in the below table.
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
<= Less than or equal to
>= Greater than or equal to
Assignment Operators –We have been using the assignment operator from the beginning. It
is the time to have a formal look at it. The assignment operator is the single equal sign ‘=’ .
The? Operators - Java includes a special ternary(three-way) operator that can replace
certain types of if – then – else statements. This operator is ‘?’.The general form of this is
Expression 1 ? Expression 2 ? Expression 3
Demonstration of ? operator
public class DemonstrationOfQuestionMarkOperator {
}
Output: The absolute value of 10is10
The absolute value of -10is10
13
MODULE I
Control Statements
Java’s program control statements can be put into the following categories: selection,
iteration, and jump.
Selection statements allow your program to choose different paths of execution based
upon the outcome of an expression or the state of a variable.
Iteration statements enable program execution to repeat one or more statements (that is,
iteration statements form loops).
The if statement
The if statement executes a block of code only if the specified expression is true.
If the value is false, then the if block is skipped and execution continues with the rest of
the program.
You can either have a single statement or a block of code within an if statement.
<statements>
Demonstration of if
14
MODULE I
Syntax:
if (condition){
statement1; }
else {
statement2;}
Demonstration of if – else
15
MODULE I
Nested ifs
A nested if is an if statement that is the target of another if or else.
When you nest ifs, the main thing to remember is that an else statement always refers to the
nearest if statement that is within the same block as the else and that is not already associated
with an else.
Demonstration of Nested if
public class NestedIF {
16
MODULE I
long salary=7400000000l;
if (salary >=70000)
{
System.out.println("Tax Third Slab");
}
else if(salary >=60000)
{
System.out.println("Tax Second Slab");
}
else
{
System.out.println("Tax no Slab");
}
The switch statement
}
17
MODULE I
The switch case statement is a multi-way branch with several choices. A switch is
easier to implement than a series of if/else statements. Structure of Switch:
The switch statement begins with a keyword, followed by an expression that equates
to a no long integral value.
Following the controlling expression is a code block that contains zero or more
labelled cases.
Each label must equate to an integer constant and each must be unique.
Syntax:
switch (Expression)
case value 1:
{ Statements; break; }
case value 2:
{Statements; break; }
……
default: { Statements; }
}
18
MODULE I
19
MODULE I
Demonstration of while
}
}
}
while(i<=10);
Department of Artificial Intelligence & Data Science , DBIT Bangalore.
}
}
20
MODULE I
21
MODULE I
Statements;
package xxxx;
import java.util.ArrayList;
public class
Demonstration ForEachLoop
of for each loop {
public static void main(String[] args) {
ArrayList<String> list=new ArrayList<String>();
list.add("vimal");
list.add("sonoo");
list.add("ratan");
//traversing the list of elements using for-each loop
for(String s:list)
{System.out.println("First Element of Array is "+ s);
}
Difference between for loop and for each loop
The for loop is a control structure for The foreach loop is a control structure for
specifying iteration that allows code to be traversing items in an array or a collection.
repeatedly executed.
A for loop can be used to retrieve a The foreach loop cannot be used to retrieve
particular set of elements. a particular set of elements.
The for loop is harder to read and write than The for each loop is easier to read and write
the for-each loop. than the for loop.
The for loop is used as a general-purpose The foreach loop is used for arrays and
loop. collections.
Jump Statements – break ,continue and return
Java supports three jump statements: break, continue, and return. These statements
transfer control to another part of your program. The break statements
22
MODULE I
break
The break statement transfers control out of the enclosing loop (for, while, do
or switch statement).
You use a break statement when you want to jump immediately to the
statement following the enclosing control structure.
You can also provide a loop with a label, and then use the label in your break
statement.
The label name is optional, and is usually only used when you wish to
terminate the outermost loop in a series of nested loops.
Syntax:
break;
Demonstration of break
//Demonstrating break statement - while printing 1
to 10 break it when we reach the number 8.
public class Break_COntinue {
public static void main(String[] args) {
for (i=1; i<=10; i++){
if (i==8)
{
break;
}
System.out.println(i);
}
}}
Continue
A continue statement stops the iteration of a loop (while, do or for) and causes execution
to resume at the top of the nearest enclosing loop.
You use a continue statement when you do not want to execute the remaining
statements in the loop, but you do not want to exit the loop itself.
You can also provide a loop with a label and then use the label in your continue
statement.
The label name is optional, and is usually only used when you wish to return to the
outermost loop in a series of nested loops.
Syntax:
23
MODULE I
continue;
Demonstration of continue
Syntax:
The return statement has two forms: One that returns a value
return Val;
return;
24
MODULE I
Functionality Break statements are mainly used to The continue statement mainly
terminate the enclosing loop such as skips the rest of the loop
while, do-while, for, or switch wherever the continue is
statements wherever a break is declared. declared and executes the next
iteration.
Executional The break statement resumes the control The continue statement resumes
flow of the program to the end of the loop and the control of the program to the
makes execution flow outside that loop. next iteration of that loop
enclosing 'continue' and made
execution flow inside the loop
again.
Usage As mentioned, break is used for the On the other hand, continue
termination of the enclosing loop. causes early execution of the
next iteration of the enclosing
loop.
Compatibility The break statement can be used and We can't use the continue
compatible with 'switch', and 'label'. statement with 'switch', and
'label' as it is not compatible
with them.
25