Unit - I Introduction To Oop and Java
Unit - I Introduction To Oop and Java
Overview of OOP:
E.g.: C++, Python, C#, Java, Beta, IDL Script, COBOL, etc.
| Data |
|------|
|Methods|
Eg: Real-Time
Car – collection of properties.
Steering, Clutch, Brake, Window, Mirrors, Seat, etc.
Eg2:
Student → Class
Anitha, Anu → Object
Department – Class
CSE, IT, CIVIL – Object
Syntax:
class name_of_class
{
private:
variable declaration; // variable
function declaration;
public:
variable declaration; // methods
function declaration; // read, write, play
};
Object:
- Object is the instance of a class.
- Object is used to invoke the members of the class (properties/tasks to be performed).
- Object has states and behaviours.
Example: car → key
- States: colour, name, model
- Behaviors: key
class_name object_name = new class_name;
(or) class_name
object_name;
object_name = new class_name();
Encapsulation:
The wrapping up of data and methods into a single unit (Class) is known as encapsulation.
Concept:
Encapsulation leads to the concept of data hiding, which means data is prevented from external access.
Example: Consider the capsule. (Method + Variable inside Class)
Abstraction:
The process of stating the essential things without including the background details is known as abstraction.
Eg:
- pow() → Header file
- Accelerator and Brake
For Example: - Consider an ATM Machine; All are performing operations on the ATM machine like cash
withdrawal, money transfer, retrieve mini- statement…etc. but we can't know internal details about ATM.
Abstraction provides advantage of code reuse.
Abstraction enables program open for extension.
In java, abstract classes and interfaces are used to achieve Abstraction.
Inheritance:
Inheritance is the process of creating a new class from an existing class.The idea behind inheritance in Java is
that we can create new classes that are built upon existing classes. When we inherit from an existing class, we
can reuse methods and fields of the parent class, and we can add new methods and fields also. Inheritance
represents the IS-A relationship, also known as the parent-child relationship. For example:- In a child and
parent relationship, all the properties of a father are inherited by his son.
A → Base class / Father class
B → Derived class / Child class
Syntax of Java Inheritance
Example:
Employee.getName(name);
Where,
Employee – object name
getName – method name (message) name - information
Polymorphism:
- Polymorphism means it can take more than one form. Polymorphism is a concept by which we can perform a sing
action in different ways. An object can take more than one form.
● The word "poly" means many, and "morphs" means forms. So, polymorphism
means many forms.
● An operation may exhibit different behaviours in different instances. The
behaviour depends on the data types used in the operation.
● For Example:- Suppose if you are in a classroom that time you behave like a
student, when you are in the market that time you behave like a customer, when
you are at your home that time you behave like a son or daughter. Here, one
person presents in different-different behaviours.
Eg:
class Shape {
draw(); // one method (draw) with different properties
}
Subclasses:
- Circle → draw()
- Square → draw()
- Rectangle → draw()
Dynamic Binding:
- Binding means linking of a procedure call to the code to be executed.
- When the linking is done at runtime.
- Object type is determined at runtime.
Comparison Table: Inheritance vs Polymorphism:
1. The derived class can derive the properties and Polymorphism is the ability for an
methods of the base class. object to use different forms.
2. Types: single, multilevel, multiple, hybrid, Types: Run time, Compile time
hierarchical inheritance. Overloading Types:
1. Function overloading
2. Operator overloading
2. Depends upon the object data type. Depends upon the independent object
1. A single class can be any no. of objects. Many objects can be created from one
class.
3. Class cannot be initialised with some Assign some property value to the
property value. objects.
Benefits of OOP:
1. Inheritance → Redundant code eliminated.
2. Modules → Communicate with each other (task).
3. Data hiding → Unauthorised access.
4. Multiple objects.
5. Message passing technique → Communicate to external.
6. Partitioning the code → Understanding.
Simple:-
✳ Java is very easy to learn.
✳ Syntax is based on C++. So easy to learn.
✳ Java has removed complicated features such as pointers.
✳ Automatic Garbage collection is available in java.
Object Oriented:-
✳ Java supports object-oriented concepts such as classes, objects, Abstraction, Encapsulation, inheritance
and polymorphism.
✳ OO means we organise our SLW as a combination of different types of object. (data and behavior)
C++ ( can be without class) Java – No programs without classes and objects
{
clrscr();
cout<<”\n Hello!”; getch();
}
Platform Independent :
✳ Java is a software-based platform-independent. (byte code)
✳ Java compiler converts source file into byte code.
✳ Bytecode is a platform-independent code because it can be run on multiple platforms such as Windows,
Linux, mac etc.
(Write Once and Run Anywhere).
✳ Two Components :
1) Runtime Environment.
2) API (Application Programming Interfaces).
Secured :
(Java is secured because java programs run inside JVM.)
Robust : (strong)
✳ Java uses strong mly management.
✳ Java supports exception handling and types of checking mechanism.
E.g.: my effective allocation
int a[10] ➝ allocate 11
java int a[5] ➝ only 1 - 5
✳ Type checking :
int a;
a = 10 + 5.5 ;
Multithreaded :-
✳ A thread is like a separate programs.
✳ Multithread contains multiple programs and executing concurrently
Advantages :
1) Doesn’t occupy mly for each thread.
2) Share a common memory area.
3) Multithread are important for web applications, multimedia etc..,
Distributed :
✳ Java is distributed because it enables users to create distributed applications in java.
✳ RMI ➝ Remote Method Invocation and EJB (Enterprise Java Beans) are used for creating distributed
applications.
Dynamic :
✳ Java is a dynamic language.
(classes on demand)
✳ Supports dynamic loading of classes.
✳ Supports functions from its native languages (C, C++)
3) Overview of Java
The Java programming language was originally developed by Sun Microsystems which was initiated by
James Gosling and released in 1995 as a core component of Sun Microsystems' Java platform (Java 1.0
[J2SE]).
BASIC JAVA TERMINOLOGIES:
1. BYTECODE:
Byte code is an intermediate code generated from the source code by java compiler and it is
platform independent.
2. JAVA DEVELOPMENT KIT (JDK):
JRE is used to provide runtime environment for JVM. It contains set of libraries
+other files that JVM uses at runtime.
4. JAVA VIRTUAL MACHINE (JVM):
JVM is an interpreter that converts a program in Java bytecode (intermediate language) into native machine code
and executes it. JVM needs to be implemented for each platform because it will differ from platform to platform.
Structure of Java :
A Java source file is a plain text file containing Java source .java code and having extension. The .java
extension means that the file is a Java source file. A Java source code file contains source code for a
class, interface, enumeration, or annotation type. There are some rules associated to Java source
files.Java program may contain many classes of which only one class defines the main method.A Java
program may contain one or more sections.
Documentation Section:
1. Provides the information about the source program.
Import Section:
Every Java Standalone program requires a main method as its starting point. A Simple Java
Program will contain only the main method class. It creates objects of various classes and uses
those objects for performing various operations.When the end of main is reached the program
terminates and the control transferred back to the Operating system.
Syntax for writing main:
public static void main(String arg[])
where,
public – It is an access specifier to control the visibility of class members. main() must be
declared as public, since it must be called by code outside of its class when the
program is started.
static – this keyword allows the main() method to be called without having to instantiate the
instance of the class.
void – this keyword tells the compiler that main() does not return any value.
The smallest individual units in a program are known as tokens. A Java program is a collection of
tokens, comments, and white spaces.
Types of Tokens:
● Reserved Keywords
● Identifiers
● Literal
● Operators
● Separators
Reserved Keywords:
50 reserved keywords are defined in Java. Written in lowercase.
Examples:
abstract, boolean, break, byte, case, catch, finally, char, class, continue, default, do, double, else,
extends, false, final, float, for, if, import, long, native, private, public, ...
Identifiers or Variables:
Example:
int c;
private float a, b;
The declaration represents:
Rules:
● Literals are variables that store a sequence of characters for representing constant values.
Example: int cost = 10;
1) Integer Literal:
Example:
double d = 123.456;
3) Character Literal:
1. Single quote: A single character within the single quote
Example:
char ch = 'a', 'b';
5) Boolean Literal:
Only two values are allowed: true or false
Example:
boolean b = true;
Operators:
● Operators are the symbols used in the expression for evaluating them.
Example:
int a = 10, b = 5;
int sum = a + b; // '+' is the operator, 'a' and 'b' are operands
Here, the + operator tells the program to add the values of a and b.
Separators:
● () : Parenthesis
● {} : Curly Brackets
● [] : Square Brackets
Data types in Java are of different sizes and values that can be stored in a variable.
Categories:
1.Primitive Data Types (int, char, short, byte, long, float, boolean, double)
Primitive data are only single values and have no special capabilities. Primitive data types are those
whose variables allow us to store only one value and never allow storing multiple values of the same
type. This is a data type whose variable can hold a maximum of one value at a time.
4 categories:
1. Integers
2. Floating point numbers
3. Characters
4. Boolean
i.Integers:
iii.Character:
● It is a set of character used to represent identifiers, literals, keyword, expression and statements.
● char is a keyword.
● Numerals: 0 to 9
● Alphabets: a to z and A to Z
Boolean:
● Because the reference type won't store the variable value directly in mly.
Categories:
1. Strings
2. Array
3. Class
Strings:
Array:
● Array is a collection of elements of similar data type stored in contiguous memory allocation.
Syntax:
datatype[] arrayname;
(or)
datatype arrayname[];
Eg: int a[];
char ch[];
Variables:
A variable is a name that holds a value while the Java program is executed.
A variable is assigned a datatype. A variable is a name of a memory location.
Variables in Java
● A variable is a named piece of memory used for storing data in a Java program.
● A variable may take different values at different times during the execution of the program,
unlike constant.The variable's type determines what values it can hold and what operations can
be performed on it.
Syntax to Declare Variables
Note: totalHeight is a corrected version of total height (whitespace not allowed in variable names).
1. A variable name must begin with a letter and must be a sequence of letters or digits.
Initializing Variables
int months;
months = 1;
class FindRemainder {
Output:
Remainder is 1
● rem is initialized dynamically using the modulo operation on num and den.
Types of variables:
Local variables Instance variables are declared Class variables also known as static
aredeclared in methods, in a class, but outside a method, variables are declared with the static
constructors, or blocks. a constructor or any block. keyword in a class, but outside a method,
constructor or a block.
There would only be one copy of each class
variable per class, regardless of how many
objects are created from it.
Instance variables are created
Local variables are created Static variables are created when the
when an object is created with the
when the method, program starts and destroyed when the
use of the keyword 'new' and
constructor or block is program stops.
destroyed when the object is
entered and the variable
destroyed.
will be destroyed once it
exits the method,
constructor or block.
Access modifiers cannot be Access modifiers can be used for Access modifiers can be used for class
used for local variables. instance variables. variables.
ObjectReference.VariableNa
me.
Syntax:
datatype[] arrayname;
or
datatype arrayname[];
Eg:
int[] a;
or
int a[];
Advantages of Array:
1. Cost Optimization → Multiple values can be stored under a common name.
Disadvantages of Array:
Types of Array:
Syntax:
datatype[] arrayname;
or
datatype arrayname[];
Eg:int[] a;
Instantiation of an Array:
● To allocate memory for array elements, we must mention the array size.
Syntax:
Eg:
Diagram:
Index: 0 1 2 3 4
Element: □ □ □ ■ □ → Element at index 3
Array length is 5
Initialize Array:
Syntax:
datatype[] arrayname = new datatype[] {list of values};
or
datatype[] arrayname = {list of values};
Example:
Output:
20
30
40
10
Sorted Array:
10
20
30
40
Two-Dimensional Array:
Syntax:
datatype[][] arrayname;
or
datatype arrayname[][];
Eg: int[][] a;
or
int a[][];
Instantiation of an Array:
● To allocate memory for array elements, we must mention the array size.
Syntax:
Initialize Array:
Syntax:
Eg:
sql
CopyEdit
Table:
Column 1 | Column 2 | Column 3 | Column 4
Row 1 → a[0][0] | a[0][1] | a[0][2] | a[0][3]
Row 2 → a[1][0] | a[1][1] | a[1][2] | a[1][3]
Row 3 → a[2][0] | a[2][1] | a[2][2] | a[2][3]
Program: Matrix Addition
class MatrixAddition {
public static void main(String args[]) {
int a[][] = {{1, 3, 4}, {2, 4, 3}, {3, 4, 5}};
int b[][] = {{1, 3, 4}, {2, 4, 3}, {1, 2, 4}};
int c[][] = new int[3][3];
Output:
CopyEdit
268
486
469
Operators:
An operator in Java is a symbol that is used to perform operations. Operators are used to manipulate
primitive data types. Java operators can be classified as unary, binary, or ternary—meaning they take
one, two, or three arguments, respectively.
1.Arithmetic Operator:
/ Divides B by A B/A 2
Program:
class AdArithmetic {
public static void main(String args[]) {
int a = 20, b = 15;
System.out.println("Addition \t" + (a + b));
System.out.println("Subtraction \t" + (a - b));
System.out.println("Multiplication \t" + (a * b));
System.out.println("Division \t" + (a / b));
System.out.println("Modulus \t" + (a % b));
}
}
Output:
mathematica
CopyEdit
Addition 35
Subtraction 5
Multiplication 300
Division 1
Modulus 5
2.Relational Operators
Relational operators in Java are used to compare 2 or more objects. Java provides sixrelational
operators: Assume variable A holds 10 and variable B holds 20, then:
== Checks if the values of two operands are equal. If yes, then the (A == B) is not true.
condition becomes true.
!= Checks if the values of two operands are not equal. If they are (A != B) is true.
not equal, then the condition becomes true.
> Checks if the value of the left operand is greater than the value of (A > B) is not true.
the right operand. If yes, then the condition becomes true.
< Checks if the value of the left operand is less than the value of (A < B) is true.
the right operand. If yes, then the condition becomes true.
Example:
public RelationalOperatorsDemo( )
System.out.println("x < y : "+(x < y)); System.out.println("x >= y : "+(x >= y)); System.out.println("x
<= y : "+(x <= y)); System.out.println("x == y : "+(x == y)); System.out.println("x != y : "+(x != y));
new RelationalOperatorsDemo();
}
Output:
$java RelationalOperatorsDemo
3.Bitwise Operators
Java provides Bit wise operators to manipulate the contents of variables at the bit level. The result of
applying bitwise operators between two corresponding bits in the :operandsis shown in the Table below.
1 1 0 1 1 0
1 0 0 0 1 1
0 1 1 0 1 1
0 0 1 0 0 0
EXAMPLE:
int b = 13; /* 13 = 0000 1101 */int c = 0; c = a & b; /* 12 = 0000 1100 */ System.out.println("a
& b = " + c );
System.out.println("a << 2 = " + c ); c = a >> 2; /* 215 = 1111 */ System.out.println("a >> 2 = " + c
); c = a >>> 2; /* 215 = 0000 1111 */
}
}
Output:
$java Test
a & b = 12 a | b = 61 a ^ b = 49
~a = -61
a << 2 = 240
a >> 2 = 15
a >>> 2 = 15
4. Logical Operators
Logical operators return a true or false value based on the state of the Variables. Given that x and y
represent boolean expressions, the boolean logical operators are defined in the Table below.
x&y x|y
x y !x x^y
x && y x || y
true true false true true False
true false false false true
true
Example:
public LogicalOperatorsDemo()
System.out.println("x & y : " + (x & y)); System.out.println("x && y : " + (x && y));
System.out.println("x | y : " + (x | y)); System.out.println("x || y: " + (x || y)); System.out.println("x ^ y :
" + (x ^ y));
}
public static void main(String args[])
new LogicalOperatorsDemo();
Output:
$java LogicalOperatorsDemo
x || y: true x ^ y : true
!x : false
syntax:<variable> = <expression>
If the value already exists in the variable, it is overwritten by the assignment operator (=).
Example:
class OperatorExample {
int a = 10;
int b = 20;
a += 4; // a = a + 4 → a = 10 + 4 → 14
b -= 4; // b = b - 4 → b = 20 - 4 → 16
System.out.println(a); // 14
System.out.println(b); // 16
OUTPUT
14
16
6. Ternary Operator in Java (?:)
The ternary operator is a conditional operator that evaluates a boolean expression and returns one of
two values depending on whether the expression is true or false.
It is called ternary because it takes three operands:
Syntax
Flow
class TernaryExample {
Output:
Minimum value: 10
7.Java Unary Operator
The Java unary operators require only one operand. Unary operators are used to perform various
operations
i.e.:
o Incrementing/decrementing a value by one
o Negating an expression
o Inverting the value of a boolean
int x = 10;
System.out.println(++x); // 12
System.out.println(--x); // 10
OUTPUT:
10
12
12
10
CONTROL-FLOW STATEMENTS
Java Control statements control the order of execution in a java program, based on data values
and conditional logic.
1.Selection Statements
We use control statements when we want to change the default sequential order of execution
There are two types of decision making statements in Java. They are:
· if statements
· if-else statements
· nested if statements
· switch statements
1.If Statement:
Syntax:
if(<conditional expression>)
If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed.If not the first set of code after the end of the if statement (after the closingcurly brace) will be
executed.
Flowchart:
Example:
Output:
2.if-else Statement:
The if/else statement is an extension of the if statement. If the statements in the if statement fails, the
statements in the else block are executed.
Syntax:
The if-else statement has the following syntax:
if(<conditional expression>)
{
< Statement Action1>
}
else
{
< Statement Action2>
}
Example:
else {
Output:
3. Nested if Statement:
Nested if-else statements, is that using one if or else if statement inside another if or else ifstatement(s).
Syntax:
if(condition1)
if(condition2)
{
else
else
{
//Executes this block if condition is false
}
Example-nested-if statement:
class NestedIfDemo
if (i < 15)
{
System.out.println("i is smaller than 15");
else
else
Output:
i is smaller than 15
An if statement can be followed by an optional else if...else statement, which is veryuseful to test
various conditions using single if...else if statement.
Syntax:
if(Boolean_expression 1){
}else {
//Executes when the none of the above condition is true.
}
Example:
Output:
Value of X is 30
5.switch Statement:
• The switch case statement, also called a case statement is a multi-way branch with several
choices. A switch is easier to implement than a series of if/else statements.
• A switch statement allows a variable to be tested for equality against a list of values. Eachvalue
is called a case, and the variable being switched on is checked for each case.
• 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 labeled
cases. Each label must equate to an integer constant and each must be unique.
• When the switch statement executes, it compares the value of the controlling expression to the
values of each case label.
• The program will select the value of the case label that equals the value of the
controllingexpression and branch down that path to the end of the code block.
• If none of the case label values match, then none of the codes within the switch statementcode
block will be executed.
• Java includes a default label to use in cases where there are no matches. We can have a nested
switch within a case block of an outer switch.
Syntax:
switch (<expression>)
{
case label1:
<statement2>
case labeln:
<statementn> default:
<statement>}
Example:
status = 1;
} else if (b > c) {
status = 2;
} else {
status = 3;
switch (status) {
case 1:
break;
case 2:
break;
case 3:
default:
System.out.println("Cannot be determined");
}}}
Output:
c is the greatest
The while statement is a looping control statement that executes a blockof code while a condition
is true. It is entry controlled loop.You can either have a single statement or a block of code within
the while loop.The loop will never be executed if the testing expression evaluates to false.The
loop condition must be a boolean expression.
Syntax:
The syntax of the while loop is
while (<loop condition>)
{
<statements>
}
Example:
System.out.println(count++);
}
}
}
Output
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
2.do-while Loop Statement
do while loop checks the condition after executing the statements atleast once.
Therefore it is called as Exit Controlled Loop.
· The do-while loop is similar to the while loop, except that the test is performed at
the endof the loop instead of at the beginning.
· This ensures that the loop will be executed at least once. A do-while loop begins
with the keyword do, followed by the statements that make up the body of the loop.
Syntax:
do
{
<loop body>
}while (<loop condition>);
Example:
public class DoWhileLoopDemo {
public static void main(String[] args)
{
int count = 1;
System.out.println("Printing Numbers from
1 to 10"); do {
System.out.println(count++);
} while (count <= 10);
}
}
Output:
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
3.For Loops
The for loop is a looping construct which can execute a set of instructions a
specifiednumber of times. It‘s a counter controlled loop. A for statement consumes the
initialization, condition and increment/decrement in one line. It is the entry controlled
loop.
Syntax:
for (<initialization>; <loop condition>; <increment expression>)
{
<loop body>
}
● The first part of a for statement is a starting initialization, which executes once
before the loop begins. The <initialization> section can also be a
comma-separatedlist of expression statements.
● The second part of a for statement is a test expression. As long as the
expression istrue, the loop will continue. If this expression is evaluated as false
the first time, theloop will never be executed.
● The third part of the for statement is the body of the loop. These are the
instructionsthat are repeated each time the program executes the loop.
● The final part of the for statement is an increment expression that automatically
executes after each repetition of the loop body. Typically, this statement
changes the value of the counter, which is then tested to see if the loop should
continue.
Exmple:
public class ForLoopDemo {
public static void main(String[] args)
{
System.out.println("Printing Numbers from 1 to 10");
{
System.out.println(count);
}}}
Output:
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
The break keyword is used to stop the entire loop. The break keyword must beused inside any loop or a
switch statement.The break keyword will stop the execution of the innermost loop and start
executingthenext line of code after the block.
Syntax:
The syntax of a break is a single statement inside any loop:
break:
Example:
Output:
10
20
2. Using continue Statement:
The continue keyword can be used in any of the loop control structures. It causes theloop to immediately
jump to the next iteration of the loop.The Java continue statement is used to continue loop. It continues
the current flow of the program and skips the remaining code at specified condition. In case of inner
loop, it continues only inner loop.
Syntax:
The syntax of a continue is a single statement inside any loop:
continue;
Example:
public class Test {
public static void main(String args[]) {int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
if( x == 30 )
{
continue;
}
System.out.print( x ); System.out.print("\n");
}}}
Output:
10
20
40
50
A class is a collection of similar objects and it contains data and methods that operate on that
data. In other words ― Class is a blueprint or template for a set of objects that share a
common structure and a common behavior.
DEFINING A CLASS:
The keyword class is used to define a class.
Rules to be followed:
class box {
{
System.out.println( \n Volume is : );
Systme.out.println(width*height*depth);
}
Objects
● An object is an instance of a class.
Object Declaration:
ClassName objectName;
Object Instantiation:
Example:
Or:
object_name.variable_name;
object_name.method_name(parameter_list);
Example:
class box
{
double width; double height;
double depth; void volume()
{
System.out.print("\n Box Volume is : ");
System.out.println(width*height*depth+" cu.cms");
}}
Constructors
Definition:
A constructor is a special type of method that is used to initialise the object. The constructor is
invoked at the time of object creation. Once defined, the constructor is automatically called
immediately after the object is created, before the new operator completes.
Where:
If a constructor is not defined, the Java compiler builds a default constructor for that class.
1. The constructor name must be the same as the class name.
Syntax:
class ClassName {
ConstructorName() {
// initialization code
}
}
Example – Object Creation
class Student {
String name;
int sno;
Student() {
name = "ABC";
sno = 123;
Types of Constructors
1) Default Constructor
Student() {
name = "ABC";
sno = 123;
}
public static void main(String[] args) {
Student st = new Student();
System.out.println(st.name); // ABC
System.out.println(st.sno); // 123
}
}
2) Parameterised Constructor
Example:
class Student {
String name;
int sno;
Student(String n, int no) {
name = n;
sno = no;
}
public static void main(String[] args) {
Student s2 = new Student("Riya", 456);
System.out.println(s2.name); // Riya
System.out.println(s2.sno); // 456
}
}
Constructor Overloading
When a class contains more than one constructor with different parameter lists, it is called
constructor overloading.
Syntax:
class ClassName {
ClassName() { ... }
ClassName(parameter1, parameter2) { ... }
}
Example:
class Student {
String name;
int sno;
Student() {
name = "Anvi";
sno = 555;
}
Student(String n, int no) {
name = n;
sno = no;
}
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student("Eva", 253);
System.out.println(s1.name); // Anvi
System.out.println(s1.sno); // 555
System.out.println(s2.name); // Eva
System.out.println(s2.sno); // 253
}
}
Invoked only once when object is created Can be called multiple times
“this” KEYWORD:
Definition:
In java, this is a reference variable that refers to the current object.
6. this keyword can also be used to return the current class instance.
Instance Variable Hiding:
It is illegal in Java to declare two local variables with the same name inside the same or
enclosing scopes. We can also have local variables, which overlap with the names of the class's instance
variables. However, when a local variable has the same name as an instance variable, the local
variable hides the instance variable .
We can use the “this” keyword to resolve any namespace collisions that might occur between
instance variables and local variables.
Example:
class Student
{
int rollno; String name; float fee;
{
this.rollno=rollno;
this.name=name; this.fee=fee;
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis2
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f); Student
s2=new Student(112,"sumit",6000f); s1.display();
s2.display();
}
}
Output:
ankit 5000
METHODS
DEFINITION :
A Java method is a collection of statements that are grouped to operate.
Syntax: Method:
modifier Return –type method_name(parameter_list) throws exception_list
{
// method body
}
The syntax shown above includes:
· modifier: It defines the access type of the method, and it is optional to use.
· returnType: Method may return a value.
· Method_name: This is the method name. The method signature consists of the method
name and the parameter list.
· Parameter List: The list of parameters includes the type, order, and number of
parameters of a method. These are optional; the method may contain zero parameters.
· Method body: The method body defines what the method does with statements.
Example:
This method takes two parameters num1 and num2 and returns the maximum between the two:
/** the snippet returns the minimum between two numbers
*/ public static int minFunction(int n1, int n2)
int min;
int findMin(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
METHOD CALLING (Example for Method that takes parameters and returning value):
● For using a method, it should be called.
● A parameter is a variable defined by a method that receives a value when the method is called.
1. When a program invokes a method, program control gets transferred to the called
method.
2. The called method then returns control to the caller in two conditions:
Example:
Following is the example to demonstrate how to define a method and how to call it:
public class MinNumber
{
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
Pass by Value
○ Scalar variables: int, long, short, float, byte, double, char, boolean → are always passed
to methods by value.
Note:
class Swapper {
int a, b; // parameters
// Constructor to initialize variables
Swapper(int x, int y) {
a = x;
b = y;
}
void swap(int x, int y) {
int temp; // Local copy x, y gets swapped
temp = x; // Original object a, b unchanged
x = y;
y = temp;
}
}
class Main {
public static void main(String[] args) {
// main method content here
System.out.println("Before Swapping : a = " + obj.a + " b = " + obj.b);
obj.swap(obj.a, obj.b); // call the method by passing values obj
System.out.println("Before Swapping : a = " + obj.a + " b = " + obj.b);
}
Program:
class Swapper
{
int a;
int b;
Swapper(int x, int y) // Initialize variables
{
a = x;
b = y;
}
void swap(Swapper ref)
{
int temp;
temp = ref.a;
ref.a = ref.b;
ref.b = temp;
}
}
class PassByRef
{
public static void main(String[] args)
{
Swapper obj = new Swapper(10, 20); // Create object
System.out.println("Before Swapping : a = " + obj.a + " b = " + obj.b);
Access Specifiers
Access specifiers or access modifiers in Java specify data members, methods, constructors, or classes.
1. private
2. public
3. protected
Private data fields and methods are accessible only inside the class where they are declared (same class
members).
It supports encapsulation and abstraction.
Example:
class PrivateEx {
private int x; // private data
public int y; // public data
Default specifier allows access to classes, methods, or fields within the same package but not from
outside the package.
Example
class DefaultEx {
int y = 10; // default data
}
public class Main {
public static void main(String[] args) {
DefaultEx obj = new DefaultEx();
System.out.println(obj.y); // default data y is accessible outside the class but within the same
package
}
}
O/P: 10
Example:
class Base {
protected void show() {
System.out.println("In Base");
}
}
public class Main extends Base {
public static void main(String[] args) {
Main obj = new Main();
obj.show(); // calling protected method
}
}
O/P: In Base
● Methods, classes, and fields declared as public are accessible by any class in the same or
different package.
Example:
class PublicEx {
public int no = 10;
}
public class Main {
public static void main(String[] args) {
PublicEx obj = new PublicEx();
System.out.println(obj.no);
}
}
O/P: 10
Static Members:
Static Members are data members (variables) or methods that belong to a static or non-static
class rather than to the objects of the class. Hence it is not necessary to create object of that class
to invoke static members.
The static can be:
1. variable (also known as class variable)
2. method (also known as class method)
3. block
4. nested class
Static Variable:
When a member variable is declared with the static keyword, then it is called static variable and it
can be accessed before any objects of its class are created, and without reference to any object.
Syntax
[access_spefier] static data_type instance_variable;
When a static variable is loaded in memory (static pool) it creates only a single copy of the static
variable and is shared among all the objects of the class. A static variable can be accessed outside
of its class directly by the class name and doesn‘t need any object.
Syntax : <class-name>.<variable-name>
Static block is used to initialize the static data member like constructors helps toinitialize instance
members and it gets executed exactly once, when the class is first loaded.It is executed before main
method at the time of class loading in JVM.
Syntex:
class classname
{
static
{
// block of statements
}
}
Example:
class StaticProg {
static int a = 10;
static void fun(int b) {
System.out.println("b = " + b);
System.out.println("a = " + a);
}
}
class AnotherClass {
public static void main(String[] args) {
System.out.println("a = " + StaticProg.a);
StaticProg.fun(20);
}
O/P:
a = 10
b = 20
a = 10
JavaDoc Comments:
● Javadoc is a convenient tool.
● HTML files give the convenience of hyperlinks from one document to another.
/**
This is a <b>doc</b> comment.
*/
Types:
Javadoc comments
→ Class level comments
→ Member-level comments
Note:
Javadoc comments start with /** and end with */.
TYPES OF COMMENTS:
1.Class Comments
The class comment must be placed after any import statements, directly before the classdefinition.
Example:
import java.io.*;
/** class comments should be written here */Public class sample
{
….
}
2.Method Comments
The method comments must be placed immediately before the method that it describes.
Tags used:
@return This tag describes the return value from a @return description
method with the exception void methods
and constructors.
@throw s This tag describes the method that throws @throws class description
an exception.
Example:
/** adding two numbers
@param a & b are two numbers to be added @return the result of addition
**/
public double add(int a,int b)
{
int c=a+b; return c;
}
3. Field Comments
Field comments are used to document public fields—generally, that means static constants.
For example:
/**
* Account number
*/
4.General Comments
@author This tag makes an ―author entry. You can have multiple @author name
@author tags, one for each author.
@see This tag adds a hyperlink in the ―see also section. It @see reference
can be used with both classes and methods. Here,
reference can be one of the following:
package.class#feature label
Example:
COMMENT EXTRACTION
Here, docDirectory is the name of the directory where you want the HTML files to go. Follow these
steps:
1. Change to the directory that contains the source files you want to document.
2. To create the document API, you need to use the javadoc tool followed by java file name.There is no
need to compile the Java file.
Here, docDirectory is the name of the directory where you want the HTML files to go.
1. Change to the directory that contains the source files you want to document.
Example:
// Comment tags
/**
*
* @version 1.0
* @since 2017-02-18
*/
/**
*/
/**
*/
OUTPUT:
Building tree for all the packages and classes... Generating FindAvgDocument\FindAvg.html...
FindAvg.java:32: error: invalid use of @return
* @return Nothing.
Generating FindAvgDocument\constant-values.html... Building index for all the packages and classes...