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

Java Unit 2

The document discusses various Java fundamentals including variables, data types, operators, and object-oriented programming concepts. It defines variables as containers that hold values, and describes local, instance, and static variables. It also defines primitive and non-primitive data types. Key object-oriented concepts like classes, objects, inheritance, polymorphism, abstraction, and encapsulation are summarized.

Uploaded by

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

Java Unit 2

The document discusses various Java fundamentals including variables, data types, operators, and object-oriented programming concepts. It defines variables as containers that hold values, and describes local, instance, and static variables. It also defines primitive and non-primitive data types. Key object-oriented concepts like classes, objects, inheritance, polymorphism, abstraction, and encapsulation are summarized.

Uploaded by

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

Java Fundamentals - I

Java Variables

 A variable is a container which holds the value while the Java


program is executed. A variable is assigned with a data type.
 Variable is a name of memory location. There are three types of
variables in java: local, instance and static.
 There are two types of data types in Java: primitive and non-
primitive.
Local Variable

 A variable declared inside the body of the method is called local


variable. You can use this variable only within that method and
the other methods in the class aren't even aware that the variable
exists.
 A local variable cannot be defined with "static" keyword.
Instance Variable

 A variable declared inside the class but outside the body of the
method, is called instance variable. It is not declared as static.
 It is called instance variable because its value is instance specific
and is not shared among instances.
Static Variable

 A variable which is declared as static is called static variable. It


cannot be local. You can create a single copy of static variable
and share among all the instances of the class.
 Memory allocation for static variable happens only once when
the class is loaded in the memory.
Java Variables

Example to understand the types of variables in java


class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
}//end of class
Data Types in Java

Data types specify the different sizes and values that can be stored
in the variable. There are two types of data types in Java:
 Primitive data types: The primitive data types include Boolean,
char, byte, short, int, long, float and double.
 Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.
Data Types in Java

Datatypes

Primitive Non-primitive

Boolean Numeric String Array etc

boolean Character Integral

Floating
char Integer
point

Byte Short Int Long Float double


Data Types in Java
Data Type Default Value Default size
boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
Operators in Java

Operator in Java is a symbol which is used to perform operations. For example: +, -,


*, / etc. There are many types of operators in Java which are given below:
 Unary Operator,
 Arithmetic Operator,
 Shift Operator,
 Relational Operator,
 Bitwise Operator,
 Logical Operator,
 Ternary Operator and
 Assignment Operator.
Operator Type Category Precedence
Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%


additive +-
Shift shift << >> >>>
Relational comparison < > <= >= instanceof

equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<=
>>= >>>=
Keywords

abstract continue for new switch


assert*** default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum**** instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp** volatile
const* float native super while
OOPs CONCEPTS

Object means a real-world entity such as a pen, chair, table,


computer, watch, etc.
Object-Oriented Programming is a methodology or
paradigm to design a program using classes and objects. It
simplifies software development and maintenance by providing
some concepts:
OOPs CONCEPTS

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
OBJECTS

An Object can be defined as an instance of a class. An object contains an address


and takes up some space in memory. Objects can communicate without knowing the
details of each other's data or code. The only necessary thing is the type of message
accepted and the type of response returned by the objects.
SYNTAX:
class-name obj-name = new class-name();
Eg:
Fruit f = new Fruit();
The new keyword is used to allocate memory at runtime. All objects get memory in
Heap memory area.
CLASS

A class is a collection of objects. It is a logical entity. A class can


also be defined as a blueprint from which you can create an individual
object. Class doesn't consume any space.
Syntax:
class <class-name>
Eg:
class Fruit
Inheritance

When one object acquires all the properties and behaviors of a


parent object (or) to inherit the new subclass(child class) from the
existing superclass (parent class), it is known as inheritance.
It provides code reusability. It is used to achieve runtime
polymorphism.
Polymorphism

If one task is performed in different ways, it is known as


polymorphism. For example: to convince the customer differently, to
draw something, for example, shape, triangle, rectangle, etc.
In Java, we use method overloading and method overriding to
achieve polymorphism.
Another example can be to speak something; for example, a cat
speaks meow, dog barks woof, etc.
Abstraction

To hiding internal details and showing functionality is known as


abstraction. For example phone call, we don't know the internal
processing.
In Java, we use abstract class and interface to achieve abstraction.
Encapsulation

The binding (or wrapping up of data) code and data together into
a single unit are known as encapsulation. For example, a capsule, it
is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully
encapsulated class because all the data members are private here.
OOPs CONCEPTS

Apart from these concepts, there are some other terms which are
used in Object-Oriented design:
 Coupling
 Cohesion
 Association
 Aggregation
 Composition
Coupling

Coupling refers to the knowledge or information or dependency of another


class. It arises when classes are aware of each other.
If a class has the details or information of another class, there is strong coupling.
In Java, we use private, protected, and public modifiers to display the visibility level of
a class, method, and field. The user can use interfaces for the weaker coupling because
there is no concrete implementation.
.
Cohesion

Cohesion refers to the level of a component which performs a single well-defined


task. A single well-defined task is done by a highly cohesive method. The weakly
cohesive method will split the task into separate parts.
The java.io package is a highly cohesive package because it has I/O related classes
and interface. However, the java.util package is a weakly cohesive package because it
has unrelated classes and interfaces.
Association

Association represents the relationship between the objects. Here, one object can be
associated with one object or many objects. There can be four types of association between the
objects:
 One to One
 One to Many
 Many to One, and
 Many to Many
Let's understand the relationship with real-time examples. For example, One country can have
one prime minister (one to one), and a prime minister can have many ministers (one to many).
Also, many MP's can have one prime minister (many to one), and many ministers can have
many departments (many to many).
Association can be undirectional or bidirectional
Aggregation

Aggregation is a way to achieve Association. Aggregation represents the


relationship where one object contains other objects as a part of its state. It represents
the weak relationship between objects. It is also termed as a has-a relationship in Java.
Like, inheritance represents the is-a relationship. It is another way to reuse objects.
Composition

The composition is also a way to achieve Association. The composition represents


the relationship where one object contains other objects as a part of its state. There is a
strong relationship between the containing object and the dependent object.
It is the state where containing objects do not have an independent existence. If
you delete the parent object, all the child objects will be deleted automatically.
Outlines

Control Statements

Selection

Iteration

Jump

27
Selection Statements

 Selection Statements are also called Decision Making Statements.

Selection

Selection Statements

Switch Statement
28
if Statements
if Statements

Simple if

if else

if- else- if Ladder

Nested if
29
Simple if

Syntax :

if (condition)
{
statement1;
}

Purpose: The statements will be evaluated if the value of the condition is true.

30
Simple if

Flow Chart: Start

True False
Condition

Statements

End
31
Example

32
if else
Syntax :
if (condition)
{
statement1;
}
else
{
statement2;
}

Purpose: The statement 1 is evaluated if the value of the condition is true otherwise
statement 2 is true.

33
if else
Flow Chart: Start

True False
Condition

Statement 1 Statement 2

End

34
Example

35
If-else-if Ladder
Syntax :

if(condition)
statements;
else if(condition)
statements;
else if(condition)
statements;
...
...
else
statements;

36
Examples
import java.util.Scanner;
class Day else if (day == 3)
{ {
public static void main(String args[]) System.out.println("\n Wednesday");
{ }
Scanner s = new Scanner(System.in); else if (day == 4)
System.out.println("Enet day between 0 to 6 Day = "); {
int day = s.nextInt(); System.out.println("\n Thursday");
if (day == 0) }
{ else if (day == 5)
System.out.println("\n Sunday"); {
} System.out.println("\n Friday");
else if (day == 1) }
{ else
System.out.println("\n Monday"); {
} System.out.println("\n Saturday");
else if (day == 2) }
{ }
System.out.println("\n Tuesday"); }
}
37
Nested if
• A nested if is an if statement that is the target of another if or else.
• Nested ifs are very common in programming.

Syntax :

if(condition)
{
if(condition)
statements....
else
statements....
}
else
{
if(condition)
statements....
else
statements....
}
38
Example

39
switch
Syntax :

switch (expression)
{
case value 1 :
statement 1 ; break;
case value 2 :
statement 2 ; break;
...
...
case value N :
statement N ; break;
default :
statements ; break;
}

Purpose: The statements N will be evaluated if the value of the logical expression is true.
40
switch
Start
Flow Chart:
Variable or Expression

Case A Statements
Case A
break;
True
False

Case B Case B Statements


break;
True
False

… Case C Statements
True break;
False

default Default Statements

End
41
Example

42
Iteration Statements
Iterations/ Loops
Each loop has four types of
statements :
while
 Initialization
 Condition checking
 Execution
 Increment / Decrement do while

for

43
while

Syntax:
m=1
initialization while(m<=20)
while(final value) {
{ System.out.println(m);
statements; m=m+1;
increment/decrement; }
}

Purpose: To evaluate the statements from initial value to final value with given
increment/decrement.

44
Example
 print values from 1 to 10

class while1 Output :


{ 1
public static void main(String args[]) 2
{ 3
int i=1; 4
while(i<=10) 5
{ 6
System.out.println("\n" + i); 7
i++; 8
} 9
} 10
}

45
do while

Syntax:
initialization m=1
do do
{ {
statements; System.out.println(m);
increment/decrement; m=m+1;
} }
while(final value); while(m==20);

Purpose: To evaluate the statements from initial value to final value with given
increment/decrement.

46
Example
class dowhile1
{
public static void main(String args[])
{
int i = 1;
int sum = 0;
do
{
sum = sum + i;
i++;
}while (i<=10);
System.out.println("\n\n\tThe sum of 1 to 10 is .. " + sum);
}
}

Output :
The sum of 1 to 10 is .. 55 22
for

Syntax:

for(initialization;final value;increment/decrement) for(m=1;m<=20;m=m+1)


{ {
statements; System.out.println(m);
} }

Purpose: To evaluate the statements from initial value to final value with given
increment/decrement.

48
Example
class for1
{
public static void main(String args[])
{
int i;
for (i=0;i<5;i++)
{
System.out.println("\nExample of for loop ");
}
}
Output :
Example of for loop
Example of for loop
Example of for loop
Example of for loop
Example of for loop
49
Jump Statements
Jump

break

continue

return
50
The break statement

 This statement is used to jump out of a loop.


 Break statement was previously used in switch – case statements.
 On encountering a break statement within a loop, the execution continues with the next
statement outside the loop.
 The remaining statements which are after the break and within the loop are skipped.
 Break statement can also be used with the label of a statement.
 A statement can be labeled as follows.

statementName : SomeJavaStatement

 When we use break statement along with label as,

break statementName;

51
Example
class break1 Output :
{ 1
public static void main(String args[]) 2
{ 3
int i = 1; 4
while (i<=10)
{
System.out.println("\n" + i);
i++;
if (i==5)
{
break;
}
}
}
}
52
continue Statement

 This statement is used only within looping statements.

 When the continue statement is encountered, the next iteration starts.

 The remaining statements in the loop are skipped. The execution starts from the

top of loop again.

53
Example
class continue1 Output :
{ 1
public static void main(String args[]) 3
{ 5
for (int i=1; i<1=0; i++) 7
{ 9
if (i%2 == 0)
continue;

System.out.println("\n" + i);
}
}
}

54
The return Statement

 The last control statement is return. The return statement is used to


explicitly return from a method.
 That is, it causes program control to transfer back to the caller of the
method.
 The return statement immediately terminates the method in which it is
executed.

55
Example
class Return1
{
public static void main(String args[])
{
boolean t = true; Output :
System.out.println("Before the return."); Before the return.
if(t)
return; // return to caller
System.out.println("This won't execute.");
}
}

56

You might also like