0% found this document useful (0 votes)
10 views176 pages

Unit I

Uploaded by

Ms Delphy P
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views176 pages

Unit I

Uploaded by

Ms Delphy P
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 176

CS3391-OBJECT ORIENTED PROGRAMMING

UNIT I INTRODUCTION TO OOP AND JAVA


Overview of OOP – Object-oriented programming paradigms – Features of Object
Oriented Programming – Java Buzzwords – Overview of Java – Data Types,
Variables and Arrays – Operators – Control Statements – Programming Structures
in Java – Defining classes in Java – Constructors Methods -Access specifiers –
Static members- Java Doc comments.
TEXT BOOKS:
1. Herbert Schildt, “Java: The Complete Reference”, 11 th Edition, McGraw Hill
Education, New Delhi, 2019
2. Herbert Schildt, “Introducing JavaFX 8 Programming”, 1 st Edition, McGraw
Hill Education, New Delhi, 2015
Overview of OOP -Basic concepts of object-oriented
programming paradigm
OBJECT ORIENTED PROGRAMMING (OOP):

• Object-oriented programming Systems (OOPs) is a programming paradigm based on the

concept of ―objects that contain

• Data and methods, instead of just functions and procedures.

• Purpose Of Oops-increase the flexibility and maintainability of programs. (code optimization

& no redundant code)

• Object-oriented programming brings together data and its behavior (methods) into a single

entity (object).

• Simula is the first object-oriented programming language.

• Many of the most widely used programming languages (such as C++, Java, Python etc.)
Features of object-oriented programming
• The basic concepts of OOP are as follows:

 Object
 Classes
 Encapsulation
 Inheritance
 Polymorphism
 Abstraction
 Dynamic binding
 Message Passing
CLASS
• Class is a collection of objects of similar
datatypes.
• For Example: quincy, sanjay,srimathi are
members(objects) of the class(II CSE B).
• Syntax: Class class_name
{………
}

• Example: Class II _CSE_B


{………..
}
OBJECT
• Object is the basic run time entity
• It is the instances of class
• It is a combination of data and its methods(functions)
• Example: Student
• Syntax for creating objects:

• The object of a class can be created by using the new keyword

• Example:

class_name object_name = new class_name();

Student s=new Student();


INHERITANCE
• Inheritance is a process by which object of one class acquires
the properties of objects of another class.
• New classes are created from the existing classes.
• The new class created is called “derived class” or “child
class” and the existing class is known as the “base class” or
“parent class”.
• The derived class now is said to be inherited from the base
class.
• Old class- Base Class(Super Class)
• New class-Derived Class(Sub Class)
POLYMORPHISM
• Polymorphism, A Greek Term, means the ability to do more
than one form.
• The word "poly" means many and "morphs" means forms. So
polymorphism means many forms.
• Another Example:

 If you are in classroom-student


 If you are in market-customer
 If you are in home that time-son,daughter,parent
Abstraction
• Abstraction refers to the act of representing essential features
without including the background details or explanations.
• i.e., Abstraction means hiding lower-level details and exposing
only the essential and relevant details to the users.

• 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
Encapsulation
• Wrapping of data and method together into a single unit is
known as Encapsulation.
Dynamic Binding
• Dynamic binding in C++ is a practice of connecting the
function calls with the function definitions at run time.
Message passing
• An object–oriented program comprises a set
of objects that communicate with each other.
• Message passing involves specifying the name of the object, the
name of the method (message) and the information to be sent.
• Example:
Employee.getName(name);
• Where,
• Employee – object name
• getName – method name
• (message) name - information
Java Buzzwords
• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed
• Dynamic
 Simple:
• Java is Easy to write and more readable and eye
catching.
• Most of the concepts are drew from C++ thus making
Java learning simpler.

 Secure:
• Java provides a secure means of creating Internet
applications and to access web applications.
• Java enables the construction of secured, virus-free.
 Object Oriented:
• Java programming is pure object-oriented programming
language. Like C++, Java provides most of the object
oriented features.

 Robust:
• Java encourages error-free programming by being
strictly typed and performing run-time checks.
 Platform Independent:
• Unlike C, C++, when Java program is compiled, it is not
compiled into platform-specific machine code, rather it is
converted into platform independent code called bytecode.
• The Java bytecodes are not specific to any processor. They
can be executed in any computer without any error.
• Because of the bytecode, Java is called as Platform
Independent.
Portable:
• Java bytecode can be distributed over the
web and interpreted by Java Virtual Machine
(JVM)
• Java programs can run on any platform
(Linux, Window, Mac)
• Java programs can be transferred over world
wide web.
Architecture Neutral:
• Java is not tied to a specific machine or operating system
architecture.
• Machine Independent i.e. Java is independent of hardware.
• Bytecode instructions are designed to be both easy to
interpret on any machine and easily translated into native
machine code.
 Dynamic and Extensible:
• Java is a more dynamic language than C or C++. It
was developed to adapt to an evolving environment.
• Java programs carry with them substantial amounts
of run-time information that are used to verify and
resolve accesses to objects at run time.
 Interpreted:
• Java supports cross-platform code through the use of Java
bytecode.
• The Java interpreter can execute Java Bytecodes directly on any
machine to which the interpreter has been ported.

 High Performance:
• Bytecodes are highly optimized.
• JVM can execute the bytecodes much faster.
• With the use of Just-In-Time (JIT) compiler, it enables high
performance.
 Multithreaded:
• Java provides integrated support for multithreaded programming.
• Using multithreading capability, we can write programs that can
do many tasks simultaneously.
• The benefits of multithreading are better responsiveness and real-
time behavior.

 Distributed:
• Java is designed for the distributed environment for the Internet
because it handles TCP/IP protocols.
• Java programs can be transmit and run over internet.
Overview of java
• Java is a object-oriented programming language was
originally developed by Sun Microsystems which was
initiated by James Gosling and released in early 1990 .
• James Gosling, often called as the father of Java
• In initial stage java was called as 'Oak. ‘
• Laterly it renamed as “java” in 1995.
BASIC JAVA TERMINALOGIES
 Bytecode-intermediate code is generated from the source code by Java
compiler and it is platform-independent.
 Java development kit (JDK)-offers a collection of tools and libraries
necessary for developing Java-based software applications.
 Java virtual machine(JVM)-provide a means for a Java program to run in
any environment.
 Java runtime environment-(JRE) provides runtime environment for JVM.
It contains set of libraries + and other files that JVM uses at runtime
 Jit (just in time) compiler: It is used to improve the performance and hence
reduces the amount of time needed for compilation.
JAVA SOURCE FILE - STRUCTURE – COMPILATION
 The java source file:
• A Java source file is a plain text file containing Java source
code and having .java extension.
 Java Program Structure:
• Java program may contain many classes of which only one
class defines the main method.
//save as Simple.java.
package mypack;
Import java.io.*;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
Main Method Class :
• Every Java Standalone program requires a main method as its
starting point.
• A Simple Java Program will contain only the main method class.
 Syntax for writing main:

public static void main(String arg[])


Compiling and running a java program in command prompt
 Step 1:
• Set the path of the compiler as follows (type this in command prompt):
• Set path=”C:\ProgramFiles\Java\jdk1.6.0_20\bin”;
 Step 2:
• To create a Java program, ensure that the name of the class in the file is
the same as the name of the file.
 Step 3:
• Save the file with the extension .java (Example: HelloWorld.java)
 Step 4: To compile the java program use the command javac as follows:
javac HelloWorld.java
 Step 5:
• To run java program use the command java as follows:
java HelloWorld
Example 1: A First Java Program:
public class HelloWorld
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}
Save: HelloWorld.java
Compile: javac HelloWorld.java
Run: java HelloWorld
Output: Hello World
A Java Program for getting input from user: Scanner object

import java.util.Scanner; // Import the Scanner class

class userinput
{
public static void main(String[] args)
{
int x, y, sum;
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Type a number:");
x = myObj.nextInt(); // Read user input

System.out.println("Type another number:"); OUTPUT:


y = myObj.nextInt(); // Read user input Type a number:10
sum = x + y; Type another number:5
System.out.println("Sum is: " + sum); // Output user input Sum is: 15

}
}
Using BufferReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args)
throws IOException
{
// Enter data using BufferReader
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// Reading data using readLine
String name = reader.readLine();
// Printing the read line
System.out.println(name); OUTPUT:
} CSE
} CSE
JAVA – DATA TYPES
• Data type is used to allocate sufficient
memory space for the data.
• Data types specify the different sizes and
values that can be stored in the variable.
• Every variable in java must be declared with a
data type.
Data types in Java are of two types:

 Primitive data types (Intrinsic or built-in types ) :-


The primitive data types include boolean, char, byte,
short, int, long, float and double.
 Non-primitive data types (Derived or Reference
Types): The non-primitive data types include
Classes, Interfaces, Strings and Arrays.
Primitive Types:

• Primitive data types are those whose


variables allow us to store only one value and
never allow storing multiple values of same
type.
• This is a data type whose variable can hold
maximum one value at a time.
There are eight primitive types in Java:
 Integer Types:
1. int
2. short
3. long
4. byte
 Floating-point Types:
5. float
6. double
 Others:
7. char
8. Boolean
Integer Types:
• The integer types are form numbers without
fractional parts.
• Negative values are allowed. Java provides
the four integer types shown below:
Floating-point Types:

• The floating-point types denote numbers with


fractional parts.
Derived Types (Reference Types):

• Derived data types are those whose variables allow us to


store multiple values of same type.
• But they never allow storing multiple values of different
types.
Example
int a[] = {10,20,30}; // valid
int b[] = {100, 'A', "ABC"}; // invalid
Char:
• Char data type is used to store any character.
• Example: char letterA ='A'

Boolean:
• boolean data type represents one bit of information.
• There are only two possible values: true and false.
• This data type is used for simple flags that track true/false conditions.
• Default value is false.
• Example: boolean one = true
Variables
• Variables are containers(memory) for storing data values.
Declaring (Creating) Variables:
Syntax:

Data _type variable_name=value;

• Where type is one of Java's types (such as int or String)


• Variable_name is the name of the variable (such as x or name).
• The equal sign is used to assign values to the variable.
Example
• Create a variable called name of data type String and assign it the value
"John“

public class Main


{
public static void main(String[] args) {
String name = "John";
System.out.println(name); output:
} John
}
• Example
Create a variable called myNum of data_type int and assign
it the value 15

public class Main


{
public static void main(String[] args)
{
int myNum = 15;
System.out.println(myNum); output:
} 15
}
• Declare a variable without assigning the value, and assign
the value later.

public class Main {


public static void main(String[] args) {
int myNum;
myNum = 15;
System.out.println(myNum);
} output:
} 15
• Change the valueof myNum from 15 to 20:

public class Main {


public static void main(String[] args) {
int myNum = 15;
myNum = 20; // myNum is now 20
System.out.println(myNum);
}
}
Output:

20
Final Variables
• Use the final keyword (if we declare the variable as "final" or "constant", which
means unchangeable and read-only):
public class Main {
public static void main(String[] args)
{
final int myNum = 15;
myNum = 20; // will generate an error
System.out.println(myNum);
}

} output:
• Main.java:4: error: cannot assign a value to final variable myNum
myNum = 20;
^
1 error
class area
{
int length=20;
int breadth=30;
void calc()
{
int areas=length*breadth;
System.out.println(“The area is"+ areas);
}
public static void main(String args[])
{
area a=new area();
a.calc();
}
}
Output:
Java Arrays
• An array is a collection of similar type of elements which
has contiguous memory location.
• Arrays are used to store multiple values in a single variable,
instead of declaring separate variables for each value.
• Array in Java is index-based, the first element of the array is
stored at the 0th index, 2nd element is stored on 1st index
and so on.
• To declare an array, define the variable type with square
brackets:
String cars[];
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

• To create an array of integers,

int mynum[]={10,20,30,40};
• Advantage of Array:
• • Code Optimization: It makes the code
optimized; we can retrieve or sort the data
easily.
• • Random access: We can get any data
located at any index position.
• Disadvantage of Array:
• Size Limit: We can store only fixed size of
elements in the array. It doesn't grow its size
at runtime.
Change an Array Element

• To change the value of a specific element,


refer to the index number:
• Example
Cars[0]=“Kia_Carrons”;

• String[] cars = {“Toyota", "BMW", "Ford",


“Innova"};
public class Main
{
public static void main(String[] args)
{
String[] cars = {“Toyota", "BMW", "Ford", “Innova"};
cars[0] = “Kia_Carrons";
System.out.println(cars[0]);
output:
} Kia_Carrons
}
Array Length
• To find out how many elements an array has, use
the length property
public class Main
{
public static void main(String[] args)
{
String[] cars = {“Toyota", "BMW", "Ford", “innova"};
System.out.println(cars.length);
}
}

Output:
4
Types of Array:
There are two types of array.
1. One-Dimensional Arrays
2. Multidimensional Arrays
One-Dimensional Array:

• A one-dimensional array is an array in which


the elements are stored in one variable name
by using only one subscript.
• Example:
• String[] cars = {“Toyota",
"BMW", "Ford", “Innova"};
public class Main
{
public static void main(String[] args)
{
String[] cars = {“Toyota", "BMW", "Ford", “Innova"};
cars[0] = “Kia_Carrons";
System.out.println(cars[0]);
output:
} Kia_Carrons
}
Multidimensional Arrays

• A multidimensional array is an array of arrays.


• Multidimensional arrays are useful when you
want to store data as a tabular form, like a
table with rows and columns.
• To create a two-dimensional array, add each
array within its own set of curly braces:
• Example
int [ ] [ ] myNumbers={ {1,2,3,4}, {5,6,7} };

• myNumbers is now an array with two arrays


as its elements.
Example
public class Main
{
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
System.out.println(myNumbers[1][2]);
}
}
Output:
7
Java Operators
• Operators are used to manipulate primitive
data types.
• Operators are used to perform operations on
variables and values.
• Java operators can be classified as unary,
binary, or ternary—meaning taking one, two,
or three arguments, respectively.
Java Unary Operator
• The Java unary operators require only one
operand.
• Unary operators are used to perform various
operations .
• i.e.:
 incrementing/decrementing a value by one
class OperatorExample
{
public static void main(String args[])
{
int x=10;
System.out.println(x++); //10(11)
System.out.println(++x); //12
System.out.println(x--); //12(11)
System.out.println(--x); //10
}
}
Different categories of operator:

1. Assignment operator

2. Arithmetic operator

3. Relational operator

4. Logical operator

5. Bitwise operator

6. Conditional operator
Java Assignment Operator
• The java assignment operator statement has
the following syntax:
<variable> = <expression>
Java Assignment Operator Example
class assignmentop{
public static void main(String args[])
{
int a=10;
int b=20;
a+=4; //a=a+4 (a=10+4)
b-=4; //b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}
}
Java Arithmetic Operators
• Java arithmetic operators are used to perform
addition, subtraction, multiplication, and
division.
• They act as basic mathematical operations.
Java Arithmetic Operator Example:
class arithmeticop
{
public static void main(String args[])
{
System.out.println(10*10/5+3-1*4/2);
}
}
Relational Operators
• Relational operators in Java are used to
compare 2 or more objects.
• Java provides six relational operators: Assume
variable A holds 10 and variable B holds 20,
then:
public class RelationalOperatorsDemo {
public RelationalOperatorsDemo()
{

int x = 10, y = 5;
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));
System.out.println("x != y : "+(x != y));}
public static void main(String args[])
{
RelationalOperatorsDemo d1=new RelationalOperatorsDemo();
}
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.
public class LogicalOperatorsDemo
{
void LogicalOperatorsDemo()
{
boolean x = true;
boolean y = false;
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));
System.out.println("!x : " + (!x));
}
public static void main(String args[])
{
LogicalOperatorsDemo d1=new LogicalOperatorsDemo();
d1.LogicalOperatorsDemo();
}
Bitwise Operators
• Java provides Bit wise operators to
manipulate the contents of variables at the
bit level.
Conditional Operators
• The Conditional operator is the only ternary (operator takes
three arguments) operator in Java.
• The operator evaluates the first argument and, if true,
evaluates the second argument.
• If the first argument evaluates to false, then the third
argument is evaluated.
• The conditional operator is the expression equivalent of the
if-else statement.
public class TernaryOperatorsDemo {
public TernaryOperatorsDemo()
{ int x = 10, y = 12, z = 0;
z = x > y ? x : y;
System.out.println("z : " + z);
}
public static void main(String args[])
{
TernaryOperatorsDemo d1=new TernaryOperatorsDemo();
}
}
CONTROL-FLOW STATEMENTS
• Java Control statements control the order of
execution in a java program, based on data values
and conditional logic.

• There are three main categories of control flow


statements;
• Selection statements: if, if-else and switch.
• Loop statements: while, do-while and for.
• Transfer statements: break, continue, return, try-
catch-finally and assert.
Selection statements (Decision Making Statement)

• There are two types of decision making


statements in Java. They are:
• if statements
• if-else statements
• nested if statements
• switch statements
if Statement:
• An if statement consists of a Boolean
expression followed by one or more
statements.
• Block of statement is executed when the
condition is true otherwise no statement will
be executed.
Syntax:

if(<conditional expression>)
{
< Statement Action>
}
public class IfStatementDemo {

public static void main(String[] args)


{
int a = 10, b = 20;
if (a > b)
System.out.println("a > b");
if (a < b)
System.out.println("b > a");
}
}

Output:
$java IfStatementDemo
b>a
if-else Statement:
• The if/else statement is an extension of the if statement.
• 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:
public class IfElseStatementDemo {

public static void main(String[] args)


{
int a = 10, b = 20;
if (a > b) {
System.out.println("a > b");
}
else {
System.out.println("b > a"); Output: b > a
}
}
}
Nested if Statement:
• Nested if-else statements, is that using one if
or else if statement inside another if or else if
statement(s).
Syntax:
if(condition1)
{
if(condition2)
{
//Executes this block if condition is True
}
else
{
//Executes this block if condition is false
}
}
else
{
//Executes this block if condition is false
Example-nested-if statement:

class NestedIfDemo
{
public static void main(String args[])
{
int i = 10;
if (i ==10)
{
if (i < 15)
{
System.out.println("i is smaller than 15");
}
else
{
}
}
else
{
System.out.println("i is greater than 15");
}
}
}
Output:
i is smaller than 15
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.
• Each value is called a case, and the variable being switched
on is checked for each case.
Syntax:
switch (<expression>)
{
case label1: <statement1>
case label2: <statement2>

case labeln: <statementn>
default: <statement>
}
public class SwitchExample {
public static void main(String[] args) {
int number=20;
switch(number){
case 10: System.out.println("10");break;
case 20: System.out.println("20");break;
case 30: System.out.println("30");break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Looping Statements (Iteration Statements)

• While Statement :
• The while statement is a looping control
statement that executes a block of code while
a condition is true.
• It is entry controlled loop.
Example:
public class WhileLoopDemo {
public static void main(String[] args) { int count = 1;
System.out.println("Printing Numbers from 1 to 10");
while (count <= 10) {
System.out.println(count++); } } }
Output
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
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 end of the loop instead of at the
beginning.
• 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);
• }
• }
For Loops
• The for loop is a looping construct which can
execute a set of instructions a specified number 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.
Example
public class ForLoopDemo {
public static void main(String[] args)
{
System.out.println("Printing Numbers from 1 to 10");
for (int count = 1; count <= 10; count++)
{
System.out.println(count);
}
}
}
Transfer Statements / Loop Control Statements/ Jump
Statements)

• 1. break statement
• 2. continue statement
Using break Statement:

• The break keyword is used to stop the entire loop.


• The break keyword must be used inside any loop or
a switch statement.
• The break keyword will stop the execution of the
innermost loop and start executing the next line of
code after the block.
Using continue Statement:

• The continue keyword can be used in any of


the loop control structures.
• It causes the loop to immediately jump to
the next iteration of the loop.
Defining Classes in java
• In object-oriented programming, a class is a basic
building block.
• It can be defined as template that describes the
data and behaviour associated with the class
instantiation.
• A class can also be called a logical template to
create the objects that share common properties
and methods.
• For example, an Employee class may contain
all the employee details in the form of
variables and methods.
• If the class is instantiated i.e. if an object of
the class is created (say e1), we can access all
the methods or properties of the class.
• Java provides a reserved keyword class to
define a class.
• The keyword must be followed by the class
name.
• Inside the class, we declare methods and
variables.
• In general, class declaration includes the
following in the order as it appears:
• Modifiers: A class can be public or has default access.
• Class keyword: The class keyword is used to create a class.
• Class name: The name must begin with an initial letter
(capitalized by convention).
• Superclass (if any): The name of the class's parent
(superclass), if any, preceded by the keyword extends. A class
can only extend (subclass) one parent.
• Body: The class body surrounded by braces, { }.
Example 1
Constructor
• Constructor is a special type of method that
is used to initialize the object.
• Constructor is invoked at the time of object
creation.
• At the time of calling constructor, memory for
the object is allocated in the memory.
• Every time an object is created using the
new() keyword, at least one constructor is
called.
• if there is no constructor available in the
class. It calls a default constructor
• In such case, Java compiler provides a default
constructor by default.
Rules for creating Java constructor

• There are three rules defined for the


constructor.
 The Constructor name must be the same as
its class name
 A Constructor must have no return type
 A Java constructor cannot be static, final,
Types of Java constructors

• There are two types of constructors in Java:


 Default constructor (no-arg constructor)
 Parameterized constructor
Java Default Constructor
Java Parameterized Constructor

• A constructor which has a specific number of


parameters is called a parameterized
constructor.
Constructor Overloading in Java

• Constructor overloading in Java is a technique of having

more than one constructor with different parameter lists.

• They are arranged in a way that each constructor performs

a different task.
METHODS
• A Java method is a collection of statements
that are grouped together to perform an
operation.
• 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, it is the type,
order, and number of parameters of a method. These
are optional, method may contain zero parameters.
•  Method body: The method body defines what the
method does with statements.
class method
{
void display() //Method declaration
{
System.out.print(“this is 2nd cse B”);
}
public static void main(String args[])//main function
{
method m1=new method();
m1.display();
}
Output:
nd
ACCESS SPECIFIERS
• Access specifiers are used to specify the
visibility and accessibility of a class
constructors, member variables and methods.
• One of four different access modifiers:
1. Public
2. Private
3. Protected
4. Default (package)
Packages
1. Public (anything declared as public can be accessed from anywhere):

• A variable or method declared/defined with


the public modifier can be accessed
anywhere in the program through its class
objects, through its subclass objects and
through the objects of classes of other
packages also.
2. Private (anything declared as private can’t be seen outside of the class):

• The instance variable or instance methods


declared/initialized as private can be accessed
only by its class.
• Even its subclass is not able to access the
private members.
3. Protected (anything declared as protected can be accessed by classes in the same package and subclasses in the other
packages):

• The protected access specifier makes the instance variables


and instance methods visible to all the classes, subclasses of
that package and subclasses of other packages.
4. Default (can be accessed only by the classes in the same package):

• The default access modifier is friendly.


• This is similar to public modifier except only
the classes belonging to a particular package
knows the variables and methods.
Static Members
• The static keyword in Java is mainly used for
memory management.
• The static keyword in Java is used to share
the same variable or method of a given
class.
• The users can apply static keywords with
variables, methods, blocks, and nested
classes
import java.io.*;
class staticdemo
{
int a=10,b=20,c=30; //non static variable
static int count; //static variable
static void SMdemo() //static method
{
count=100;
}
static // static block creation
{
System.out.println("java program for static");
}
static class innerclass //static class creation
{
static int count2=200;
}
staticdemo() //constructor creation
{
count=count+1;
}
}
class Test1
{
public static void main(String args[])
{
staticdemo.SMdemo(); //static method calling
staticdemo st1=new staticdemo();
staticdemo st2=new staticdemo();
System.out.println("non-static variable"+st1.a); // non-static variable calling

System.out.println("object count" +staticdemo.count); //static variable calling


System.out.println("Static class called"+staticdemo.innerclass.count2); // static class calling

}
}
JavaDoc Comments
• Javadoc is a tool which comes with JDK and it is used for
generating Java code documentation in HTML format
from Java source code which has required
documentation in a predefined format.
Format:
• A Javadoc comment precedes similar to a multi-line comment except that
it begins with a forward slash followed by two asterisks (/**) and ends
with a */
• Each /** . . . */ documentation comment contains free-form text
followed by tags.
• A tag starts with an @, such as @author or @param.
• The first sentence of the free-form text should be a summary statement.
• The javadoc utility automatically generates summary pages that extract
these sentences.
• In the free-form text, you can use HTML modifiers such as <h1>...</h1>
for heading, <p>...</p> .

You might also like