Module 1 OOPS

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 101

Module-1

• Features of OOP
• Data types, variables, Array, Operators, String functions, Control statements
• Objects and Classes in Java – Defining Classes – Methods - Access Specifiers –
Static Members – Constructors,this Keyword-Encapsulation.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Introduction

Machine Code:
• Representing instruction and data using binary digit is called
Machine Language or Machine Code. Computers can understand only
machine codes.
Assembler: It converts assembly language program into machine code.
Compiler: It converts all lines into machine code and gives to
microprocessor.
Interpreter: It converts line by line and only one line at a time.
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Platform independent

• The platform can be defined as a distinct combination of hardware, operating


system, and software that provides an environment to run programs.

• If a Code which is written in any programming language, get executed on any


platform. Such program or language is called platform independent.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


History of Java
• In 1990, Sun Microsystems Inc. (US) has conceived a project(Green Project) to
develop software for consumer electronic devices that could be controlled by
a remote.
• In 1991, Mike Sheradin -business development; Patrick Naughton -graphics
system; and James Gosling-to identify the proper programming language for
the project.
• Gosling thought C and C++ could be used to develop the project. But they
were system dependent languages and hence could not be used on various
processors.
• So he started developing a new language, which was completely system
independent.
• This language was initially called Oak. Since this name was registered by some
other company, later it was changed to Java.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE 4


History of Java
Why the name Java?
• James Gosling and his team members were consuming a lot of coffee while developing this
language.
• They felt that they were able to develop a better language because of the good quality
coffee they consumed.
• So the coffee has it's own role in developing this language and good quality coffee was
exported to the entire world from a place called ‘Java island’.
• Hence they fixed the name of the place for the language as Java and the symbol for Java
language is a coffee cup and saucer.
• Sun formally announced Java at SunWorld conference in 1995
• On January 23rd 1996, JDK 1.0 version was released.
• Latest Version: Java SE 19 (20th September 2022)

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Simple Program
import java.lang.*;
public class Ex1 {
public static void main(String[] args) {
System.out.println("VIT-AP University");
}}
Compilation: javac Ex1.java
Execution: java Ex1
O/P: VIT-AP University

JDK(Java Development Kit):


• Java Runtime Environment (JRE)
• A compiler (javac)
• An archiver (jar) and many more.
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Java Program Execution Process

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Bytecode

• Bytecode is a highly optimized set of instructions designed to be executed by


Java Virtual Machine (JVM).
• Java people coined a group of instructions to express any operation.
• These instructions are called byte code instructions because the size of each
instruction is 1 byte (=8 bits) exactly.
• Byte code is platform independent
• It helps in achieving platform-independence and security.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Java Virtual Machine (JVM)

• Java Virtual Machine (JVM) is the heart of entire Java program execution
process.
• It is responsible for taking the . class file and converting each byte code
instruction into the machine language instruction that can be executed by
the microprocessor
• Class loader loads the . class file into memory.
• Bytecode verifier verifies whether all byte code instructions are proper or
not.
• If it fids any instruction suspicious, the execution is rejected immediately.
• If the byte instructions are proper, then class loader allocates necessary
memory to execute the program
• JVM is platform dependent
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Java Virtual Machine (JVM)

Interpreter
• The interpreter reads and converts the bytecode instructions line by line
JIT(Just-In-Time) Compiler
• The Execution Engine first uses the interpreter to execute the byte code, but
when it finds some repeated code, it uses the JIT compiler.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Data types
A Data Type represents the type of data stored into a variable or memory.

1. Integer Data Types


2. Float Data Types
3. Character Data Types
4. Boolean Data Types
5. String Data Type

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Data types
Integer Data Types
• These data types represent numbers without decimal point like 10, -20, 9600, 0 etc

Data Types Memory Size Min & Max Values


byte 1 byte -128 to +127
short 2 byte -32768 to +32767
int 4 byte -2147483648 to +2147483647
-9223372036854775808 to

long 8 byte +9223372036854775807

Ex:
• byte rno = 101;
• long sal = 340000000l;
• int x=20;

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE 12


Data types
Float Data Type
• These data types represent numbers with decimal point like 10.0, -20.12, 96.00, 0.01 etc.
Data Types Memory Size Min & Max
Values
float 4 byte -1.4e-47 to +1.4e48
double 8 byte -4.9e-324 to +1.8e308

Ex: float PI = 3.142f;


double dist=1.987654321;

Character Data Type


These
•Data data types represent
Types Memory a single
Size character
Min & like a, 1,*, %, “, -, „, @ etc.
MaxA,Values
Char 2 byte 0 to 65535

• Ex: char ch = “X”;


Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE 13
Data types
Boolean Data Type:
• This data type represents two values, either true or false or binary values like 1 or 0.
Ex: boolean response = true;
boolean request = false;
String Data Type:
• A String represents group of characters like
“Devansh”, “23bce9255”, “Vit-ap” etc.
Ex: String name = “Vit-AP”;
• A string is a data type as well as a class

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Variables
• Variables are containers for storing data values.
• Variable is a name of memory location.
Syntax:
datatype variable_name;
Ex: int a; //Declaration
float b=1.5f; //Initialization
int a=5,b=6,c=7;

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Data types & Variables
class Datatype
{
public static void main(String[] args) {
int a=20;
float b=20.5f;
char c='A';
double d=3.4;
boolean e=true;
long l=9502734525l;
System.out.println(a+"\t"+b+"\t"+c+"\t"+d+"\t"+e+"\t"+l);
}
} 20 20.5 A 3.4 true 9502734525

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Operators

• An operator is a symbol that can perform an operation on operands(variables)


 If an operator acts on a single variable (Operand) then it is called as Unary
operator.
 If an operator acts on a two variables (Operands) then it is called as Binary
operator.
 If an operator acts on a three variables (Operands) then it is called as ternary
operator.

1. Arithmetic Operators
2. Increment & Decrement Operators
3. Relational Operators
4. Logical Operators
5. Assignment Operators
6. Conditional Operators
7. Bitwise
Dr. Venkata Operators
Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Operators
Arithmetic Operators:
• These operators performs basic arithmetic operations etc.
Operator Operators Meaning Usage
+ Addition a+b
- Subtraction a–b
* Multiplication a*b
/ Division a/b
% Modulus (remainder of a%b
Div.)

Ex: int a=2, b=5;


• a%b=2;
• a/b=0
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Operators
Increment and Decrement Operators:
• The increment operator increases its operand by one. The decrement operator decreases its
operand by one.
Ex: x++,++x or x--,--x
• In the prefix form(++x,--x), the operand is incremented or decremented before the
value is obtained for use in the expression.
• In postfix form(x++,x--), the previous value is obtained for use in the expression,
and then the operand is modified.
Example:
x = 42; y = ++x;
y=?, x=?
• x = 42; y = x++;
Y=?,x=?
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Operators
Relational Operators
• These operators are used to compare two operands.
• The outcome of these operations is a boolean value.
Operators Meaning
> Greater than
>= Greater than or equals to
< Less than
<= Less than or equals to
== Equals to
!= Not Equals to

Example:
int a = 4; int b = 1;
boolean c = a < b;
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Operators
Logical Operators:
• These operators are used to construct compound conditions. A compound condition is
a combination of more than one simple condition
Operators Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Example:
class HelloWorld {
public static void main(String[] args) {
int a = 5,b=6,c=4;
System.out.println(a < b && a<c);
System.out.println(a<b || a<c); }}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Operators
Ternary Operator or Conditional Operator(?:)
Syntax:
variable = expression1? Expression2:expression3;
• First, expression1 is evaluated. If it is true, then expression2 value is stored into the variable. If
expression1 is false, then expression3 value is stored into the variable
Ex:
int a=5,b=6,c;
c=a>b?a:b;
Assignment Operator (-)
This operator is used to store some value into a variable.
int x=5;
int y=x;

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Operators
Bitwise Operators:
• These operators act upon the individual bits (0 & 1) of their operands.

1. Bitwise AND (&)


2. Bitwise OR (|)
3. Bitwise XOR (^)
4. Bitwise Complements (~)
5. Bitwise Left shift (<<)
6. Bitwise Right shift (>>)

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Operators
int x=10; int y=11;
X: 0000 1010
Y: 0000 1011
X&Y : 0000 1010
result is 10
X: 0000 1010
Y: 0000 1011
X|Y : 0000 1011
result is 11
X: 0000 1010
Y: 0000 1011
X^Y : 0000 0001
result is 1
a = 0011
~a = 1100
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Operators
Bitwise Left Shift Operator «
• This operator shifts the bits of the number towards left a
specified number of positions.
• If we write x«n, the meaning is to shift the bits of x towards
left n positions.
X<<n=x*2n

X=10;
X<<2=10x22
=10x4= 40
Bitwise Right Shift Operator (»)
• This operator shifts the bits of the number towards right a
specified number of positions.
• If we write x»n, the meaning is to shift the bits of x towards
right n positions
X>>n=x/ 2n
X>>2=10/22
=10/4=2
X>>2=?
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Operators

class ope {
public static void main(String[] args)
{
int x=9,y=15,z=5;
System.out.println(x+y); //24
System.out.println(x++); //9
System.out.println(x<y); //true
System.out.println(x<y && x<z); //false
System.out.println(x<y?x:y); //10
System.out.println(x & y); //10
System.out.println(x>>2); //2
}
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Program to find the maximum of two numbers

public class MaxOfTwoNumbers {


public static void main(String[] args) {
int num1 = 5;
int num2 = 7;
int max = num1 > num2 ? num1 : num2;
System.out.println("Maximum of " + num1 + " and " + num2
+ " is: "
+ max);
}
}

Maximum of 5 and 7 is: 7

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Java Program to Convert Celsius into
Fahrenheit
fahrenheit=(celsius*1.8)+32

class celsiustofahrenheit {
public static void main(String[] args)
{
double celsius = 33.0, fahrenheit;

fahrenheit = (celsius * 1.8) + 32;


System.out.println( "Fahrenheit:"+ fahrenheit);
}
}

Fahrenheit:91.4

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Java User Input
• The Scanner class is used to get user input, and it is found in the java.util package.

• To use the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class

Scanner in = new Scanner(System.in);

• The Java Scanner class provides nextXXX() methods to return the type of value such
as nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(),
nextBoolean(), etc.
• To get a single character from the scanner, you can call next().charAt(0) method
which returns a single character

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Java User Input
import java.util.Scanner;
System.out.println("Name: " +
public class ScannerDemo1 { name);
public static void main(String[] System.out.println("Gender: " +
args) gender);
{ System.out.println("Age: " +
Scanner sc = new age);
Scanner(System.in);
System.out.println("MobileNumber:"+ mobileNo);
// String input System.out.println("CGPA: " +
cgpa);
O/P:
String name = sc.nextLine();
} Devansh
// Character input } M
char gender = 07
sc.next().charAt(0); 9502734525
9.8
int age = sc.nextInt(); Name: Devansh
long mobileNo = Gender: M
sc.nextLong();
Age: 7
double cgpa =
sc.nextDouble();
Mobile Number: 9502734525
CGPA: 9.8
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Java program to convert dollars to rupees

import java.util.Scanner;

public class DollarToRupeeConverter {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter amount in dollars: ");


int dollars = scanner.nextInt();

double rupees = dollars * 80.29;


System.out.println("Rupees="+rupees);

}
}
Enter amount in dollars: 5
Rupee=401.45000000000005

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


CONTROL STATEMENTS
• Control statements are the statements which alter the flow of execution and provide
better control to the programmer on the flow of execution
• Java provides three types of control flow statements.
1.Decision Making statements
1. if statements
2. switch statement
2.Loop statements
1. do while loop
2. while loop
3. for loop
4. for-each loop
3.Jump statements
1. break statement
2. continue statement
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Decision-Making / Conditional statements

if statements:
1.Simple if statement
2.if-else statement
3.if-else-if ladder

Simple if statement
Syntax:
if(condition) {
statement 1; //executes when condition is true
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Decision-Making / Conditional statements

if-else statement:
This statement is used to perform a task depending on whether a given condition is true
or false. Example: Movie Ticket automation
Syntax: class Ticket{
if(condition) { public static void main(String args[])
{
statement 1; //executes when condition is true int age=2;
} if(age<4)
{
else{
System.out.println(“Ticket Not Required”);
statement 2; //executes when condition is false }
} else
{
System.out.println(“ Ticket Required”);
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Decision-Making / Conditional statements
Example: Check eligibility to cast vote
import java.util.*;
class Vote{
public static void main(String args[])
{
System.out.println("Enter Age");
Scanner sc = new Scanner(System.in);
int age=sc.nextInt();
if(age<18)
{
System.out.println("Not eligible to Vote");
}
else
{
System.out.println("Eligible to Vote");
}
}}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Decision-Making / Conditional statements

if-else-if ladder:
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 3; //executes when all the conditions are false
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Decision-Making / Conditional statements

Problem:
Raju's parents are celebrating their marriage anniversary. They have arranged a small party
tonight. They have planned to serve 'Coke' and 'Badam Milk' to the guests. But they would
like to serve 'Badam Milk' to teenagers and 'Coke' to adults. Please help them in finding
teenagers and adults based on age. Write a Java program to find out the adults and teenagers
based on their age. Teenagers are those whose age is between 13 and 19 (both inclusive).

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Decision-Making / Conditional statements
import java.util.*;
public class Party
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter Age: ");
int age=s.nextInt();

if((age>=13) && (age<=19))


System.out.println("Serve Badam Milk");
else if(age>19)
System.out.println("Serve Coke");
else
System.out.println("Not allowed to Party");
}
Dr. Venkata}Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Decision-Making / Conditional statements

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Decision-Making / Conditional statements
switch :
• When there are several options and we have to choose only one option from the available
ones, we can use switch statement.
• Depending on the selected option, a particular task can be performed.

switch (expression) {
case value1: statement sequence;
break;
case value2: statement sequence;
break;
. . .
case valueN: statement sequence ;
break;
default: default statement sequence;
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Decision-Making / Conditional statements
Problem:
There is a telecommunication company called “PoweredAir” who have approached you to build their Interactive
Voice Response (IVR) system. You should write a Java program and be able to provide the following menu
(given below):
• Note: User should provide an input for each menu display.
• Welcome to Powered Air Service. What would you like to do?
1. Know my balance
2. Know my validity date
3. Know number of free calls available
4. Exit

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Decision-Making / Conditional statements
import java.util.*;
class IVR
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("1. Know my balance\n 2. Know my validity
date\n 3. Know number of free calls available\n 4. Exit");
System.out.println(" Enter your choice");
int i=sc.nextInt();
switch(i)
{
case 1: System.out.println("Your balance is:Rs. 200");
break;
case 2: System.out.println("Your validity is :Jan 2024");
break;
case 3:System.out.println("Number of free calls are:500");
break;
case 4:break;
}} }

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Looping statements
while Loop:
• The Java while loop is used to iterate a part of the program repeatedly until the specified
condition is true.
• As soon as the condition becomes false, the loop automatically stops.

Syntax:

while (condition){
//code to be executed
Increment / decrement statement
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Looping statements

import java.util.*;
class Sum
{
public static void main(String args[])
{
int i=1, sum=0,n;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
while(i<=n)
{
sum=sum+i;
i++;
}
System.out.println(“Sum is=”+sum);
}
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Looping statements
do-while Loop:
• Unlike while loop and for loop, the do-while import java.util.*;
check the condition at the end of loop body. class Sum
• The Java do-while loop is executed at least {
once because condition is checked after public static void main(String args[])
{
loop body.
Int i=1, sum=0,n;
Scanner sc=new Scanner(System.in);
Syntax: int n=sc.nextInt();
do{
do{ sum=sum+i;
// i++;
code to be executed / loop body } while(i<=n);
}while (condition);
System.out.println(“Sum is=”+sum);
}
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Looping statements

for loop:
• The Java for loop is used to iterate a part of the program several times.
• If the number of iteration is fixed, it is recommended to use for loop.

Syntax:
for(initialization; condition; increment/decrement){
//statement or code to be executed
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Looping statements

class Pattern {
public static void main(String args[]) 1
{ 12
int i, j,n=5;
// outer loop to handle number of rows
123
for (i = 1; i <= n; i++) { 1234
// inner loop to handle number of 12345
columns
for (j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Looping statements

for-each loop:
• The for-each loop is used to traverse array or public class ForEach {
collection in Java public static void main(String[] args) {
//Declaring an array
Syntax: int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(data_type variable : array_name
){ for(int i:arr){
System.out.println(i);
//code to be executed
}
} }
}
O/P: 12,23,44,56,78

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Jump statements

break: public class BreakExample {


• The Java break statement is used to jump public static void main(String[] args) {
out of a loop or switch statement. for(int i=1;i<=6;i++){
• When a break statement is encountered if(i==3){
inside a loop, the loop is immediately break;
terminated and the program control resumes }
at the next statement following the loop. System.out.println(i);
}
}
}
O/p:

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Jump statements

continue: public class BreakExample {


• The continue statement is used in loop public static void main(String[] args) {
control structure when you need to jump to for(int i=1;i<=6;i++){
the next iteration of the loop immediately. if(i==3){
• The continue statement breaks one iteration continue;
(in the loop), if a specified condition occurs, }
and continues with the next iteration in the System.out.println(i);
loop. }
}
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Arrays in JAVA

• An ordered collection of values


• two distinguishing characters:
• Ordered and fixed length
• Homogeneous. Every value in the array
must be of the same type
• The individual values in an array are called
elements.
• Each element is identified by its position
number in the array, which is called index.
Types of Arrays:
• One/Single dimensional arrays (or lD arrays) o
• Multi dimensional arrays (or 2D, 3D, ... arrays)

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


One Dimensional Array
• A one dimensional array represents a row or a column of
elements.
Declare array:
datatype identifier[] = new datatype[size];
int age[]=new int[3];
Initialize array:
age[0]=12;
age[1]=4;
age[2]=5;
• Arrays can be initialized when they are declared More examples for ID array:
int a[]={10,20,30}; float salary[] = {56.55f, 120f, 45.75f};
char ch [ ] = {' a' , ‘ b' , ,’c' , ’d’ };
• Cycling through array elements
String names [ ] = {"Raju", "Viji", "Gopi"};
for (int i = 0; i < array.length; i++) { String names [ ]= new String[10];
operations involving the ith element
Dr. Venkata }Rami Reddy Ch , Sr. Assistant Professor, SCOPE
One Dimensional Array
import java.util.*;
class Create
{
public static void main(String[] args) {
int a[]=new int[5];
Scanner sc=new Scanner(System.in);
System.out.println("Enter Array elements");
//Reading
for(int i=0;i<5;i++)
{
a[i]=sc.nextInt();
}
System.out.println("Array elements");
for(int i=0;i<5;i++)
{
System.out.println(a[i]);
}
}}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Java program to find a maximum element
import java.util.*;
class Max
{
public static void main(String[] args) {
int a[]=new int[5];
Scanner sc=new Scanner(System.in);
System.out.println("Enter Array elements");
for(int i=0;i<5;i++)
{
a[i]=sc.nextInt();
}
int max=a[0];
for(int i=0;i<5;i++) Enter Array elements
{ 3 5 6 2 24
if(max<a[i]) maximum element is:24
{
max=a[i];
} }
System.out.println("maximum element is:"+max);
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Java program to find the duplicate values of an array of integers.

public class FindDuplicates {


public static void main(String[] args) {
int[] arr= {5,10,6,5,20,10};

System.out.print("Duplicate elements in array: ");


for (int i = 0; i < arr.length; i++)
for (int j = i + 1; j < arr.length; j++)
if (arr[i] == arr[j]) {
System.out.print(arr[j] + " ");
break;

}
}
}

Duplicate elements in array: 5 10

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Java program to sort an array of integers.
import java.util.Scanner;
public class Order
{ System.out.print("Ascending Order:");
public static void main(String[] args) for (int i = 0; i < n ; i++)
{
{
int n=5, temp;
Scanner s = new Scanner(System.in); System.out.print(a[i] + ",");
int a[] = new int[n]; }
System.out.println("Enter all the elements:");
}
for (int i = 0; i < n; i++)
{ }
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Multidimensional Arrays
Two dimensional arrays (2D array):
• A two dimensional array represents
several rows and columns of data.

int a[][] = new int[4][5];

for(int i=0;i<4;i++)
{
for(int i=0;i<5;i++)
{
a[i][j]=value;
}
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Sum of Elements of a matrix

import java.util.*;
class Sum
{
public static void main(String[] args) {
int sum=0;
int a[][]=new int[2][2];
Scanner sc=new Scanner(System.in);
System.out.println("Enter Array elements");

for(int i=0;i<2;i++)
for(int j=0;j<2;j++) O/P:
a[i][j]=sc.nextInt();
Enter Array elements
for(int i=0;i<2;i++) 1
for(int j=0;j<2;j++) 2
sum=sum+a[i][j];
3
System.out.println("Sum Of Elements:"+sum); 4
} Sum Of Elements:10
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Strings
• String represents a group of characters
• In java, a string is an object of String class

String str = “Hello”;


String s2 = new String (“Hay”);

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


String Class Methods

int length ():


• This method returns the length of a string.
String s1=“VITAP”;
Syetm.out.println(s1.length());

char charAt (int i):


• This method-returns the character at the specified location i.
String s1="VITAP";
System.out.println(s1.charAt(3));

boolean equals (String· s):


• This method returns true if two strings are same, otherwise false.

String s1="VIT" ;
String s2="AP";
System.out.println(s1.equals(s2));

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


String Class Methods

char[] toCharArray() : It converts a string into character array


String s1=“VITAP";
String s1="VIT-AP" ;
char[] ch=s1.toCharArray();
System.out.println(ch[5]);

int indexOf(String s):


s1.indexOf(s2) : If s1 contains s2 as a substring, then the first occurrence (position) of s2
in the string s1 will be returned by this method.
String s1= "This is a book";
System.out.println(s1.indexOf("is"));

String trim (): This method removes spaces from the beginning and ending of a string.
String s1=“ OOPS through JAVA ”;
System.out.println(s1.trim());

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


String Class Methods

String substring (int i): This method is useful to extract sub string from a main string.
• It returns a new string consisting of all characters starting from the position 'i' until the
end of the string.
String s1="University";
System.out.println(s1.substring(3));

String substring (int i1, int i2 ): This method returns a new string consisting of all
characters starting from position i1 to i2.
• The character at i2 is excluded;
String s1="University";
System.out.println(s1.substring(3,5));

String toLowerCase(): This method converts all characters of the string into lower case.
String toUpperCase () : This method converts all characters of the string into upper case.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


String Class Methods

split()
• The split() method divides the string at the specified regex and returns an array of
substrings.
Java
String text = "Java is a fun programming language"; is
a
String[] result = text.split(" "); fun
programming
for (String str : result) {
language
System.out.println(str);

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


String Class Methods

replace():
• The replace() method searches a string for a specified character, and returns a new
string where the specified character(s) are replaced.

String myStr = "Hello";


System.out.println(myStr.replace('l', 'p'));

contains()
• The contains() method checks whether a string contains a sequence of characters.
• Returns true if the characters exist and false if not.
String myStr = "Hello";
System.out.println(myStr.contains("Hel")); // true
System.out.println(myStr.contains("Ho")); // false

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Java Program to reverse a string

import java.util.*;
class Reverse
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter A string");
String str=sc.next();
String rev="";
int n=str.length();
for(int i= n-1; i>=0; i--) {
rev=rev+str.charAt(i);
}
System.out.println("After Reverse="+rev);
}}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Java Program to print no of vowels and consonants in a given string

import java.util.*; for(int i=0;i<n;i++)


class VC_count {
{
public static void main(String if(ch[i]=='a'||ch[i]=='e'||ch[i]=='i’||
args[])
{ ch[i]=='o'||ch[i]=='u')
int vc=0,cc=0; {
Scanner sc=new Scanner(System.in); vc++;
System.out.println("Enter A }
string");
String str=sc.nextLine(); else{
int n=str.length(); cc++;
char ch[]=str.toCharArray(); }
}
System.out.println("No of vowels="+vc);
System.out.println("No of
consonants="+cc);
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE }}
Java Program to print no of words and characters in a given string

import java.util.Scanner;
public class WordCharacterCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string: ");
String input = scanner.nextLine();

String[] words = input.split(" ");


int wordCount = words.length; Enter a string:
int charCount = input.length(); OOPs through Java
Word count: 3
Character count: 17
System.out.println("Word count: " + wordCount);
System.out.println("Character count: " + charCount);
}
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
OOPS concepts
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


OOPS concepts
Object:
•An object is any thing that exists physically
•For example, a table, a ball, a car, a dog, a person, etc.,
•Every object has a properties and behavior.

Class:
•Class is a template/blueprint from which you can create an individual object.
•It is a user-defined data type which provides a common structure to all its objects
•A class contains variables and methods

Attributes( properties): Methods(behaviors):


• manufacturer’s name
• Define data items (specify manufacturer’s
• model name
name, model, year, etc.)
• year made
• color • Change a data item (color, engine, etc.)
• number of seats • Display data items
• etc. • Calculate cost
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
OOPS concepts
Inheritance
• When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability
Polymorphism
• If one task is performed in different ways, it is known as polymorphism.
Abstraction
• Hiding internal details and showing functionality is known as abstraction.

Encapsulation
• Binding (or wrapping) code and data together into a single unit are known as
encapsulation.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Object oriented programming approach

• Object oriented programming approach is a programming methodology to design


computer programs using classes and objects.
• VIT-AP(Faculty, Students and Staff)

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Classes & Objects
The General Form of a Class
class classname {
• An object is an instance of a class because every
type instance-variable1; object of a given class contains the structure and
type instance-variable2; behavior defined by the class.
// ... type instance-variableN; • The variables defined within a class are called
type methodname1(parameter-list) instance variables because each object of the class
{ contains its own copy of these variables.
// body of method
}
• Thus, the data for one object is separate and unique
type methodname2(parameter-list) from the data for another object.
{ • The code is contained within methods.
// body of method • Collectively, the methods and variables defined
}
within a class are called members of the class
// ...
type methodnameN(parameter-list) {
// body of method }
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Classes & Objects
Creating Object :
A Simple Class:
Box mybox = new Box(); // create a Box object called mybox
class Box {
• mybox will be an instance of Box.
• The new operator dynamically allocates memory for an object and double width;
returns a reference to it. double height;
• Every Box object will contain its own copies of the instance double depth;
variables width, height, and depth. }

Accessing instance variables:


mybox.width=10;
mybox.height=20;

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Introducing Methods
This is the general form of a method:

type method_name(parameter-list)
{
// body of method
}

• Here, type specifies the type of data returned by the method.


• If the method does not return a value, its return type must be void.
• Methods that have a return type other than void return a value to the calling routine
using the following form of the return statement:
return value;

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Introducing Methods
class Box { public static void main(String args[]) {
double width;
Box mybox1 = new Box();
double height;
Box mybox2 = new Box();
double depth;
double vol;
void setDim(double w, double h, mybox1.setDim(10, 20, 30);
double d) mybox2.setDim(5, 6, 7);
{ vol = mybox1.volume();
width = w; System.out.println("volume of first box is
height = h; " + vol);
depth = d; vol = mybox2.volume();
}
System.out.println("volume of second box is
double volume() {
" + vol);
return width * height * depth;
}
}
}
volume of first box is 6000.0
volume of second box is 210.0

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE 75


Create a class Cricketer with fields name, country and totalruns. Include
readData () method to initialize instance variables and print () method to
display the data. Design a driver class and create two Cricketer objects. Invoke
readData () and print () methods to read and display the cricketer's data.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


class Cricketer { Class Driver_cri
String name,country; {
int totalRuns;
public static void main(String[] args) {
void readData(String n, String c, int t) // Creating objects for two cricketers
{ Cricketer ck1 = new Cricketer();
name = n;
Cricketer ck2 = new Cricketer();
country = c;
totalRuns = t; ck1.readData("Virat Kohli","India", 12000);
} ck2.readData("Steve Smith","Australia",
9000);
void displayInfo() {
System.out.println("Cricketer 1:");
System.out.println("Name: " +
name); ck1.displayInfo();
System.out.println("Country: " +
country);
System.out.println("Cricketer 2:");
System.out.println("Total Runs: "
+ totalRuns); ck2.displayInfo(); Cricketer 1:
System.out.println(); } Name: Virat Kohli
} }
Country: India
} Total Runs: 12000
Cricketer 2:
Name: Steve Smith
Country: Australia
Total Runs: 9000
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Constructors
• A constructor in Java is a special method that is used to default constructor:
initialize instance variables Box()
• The constructor is called when an object of a class is created. {
Statements:
A constructor has the following characteristics:
}
1.The constructor's name and class name should be same
2.constructor does not return any value, not even void also. Parameterized Constructor:
3.constructor may have or may not have parameters. Box(double w, double h, double d)
a. default constructor b. parameterized constructor {
4. A constructor is automatically called and executed at the Statements:
time of creating an object. }
5. A constructor is called and executed only once per object.
Box mybox1 = new Box();
Box mybox1 = new Box(10, 20,
15);
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Constructors

class Box { class BoxDemo3 {


double width;
public static void main(String args[]) {
double height;
double depth; double vol;
Box mybox1 = new Box(10,20,30);
Box(double w, double h, double d) { vol = mybox1.volume();
width = w; System.out.println("volume of first box is " + vol);
height = h;
}
depth = d;
} }
double volume() {
return width * height * depth;
}
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Create a class Student with fields id, name and cgpa. Include a
constructor to initialize instance variables and print () method to
display the data. Design a driver class and create two student objects.
Invoke print () method to display the student’s data.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


class Student {
int id;
String name;
double cgpa; class Driver_stu
{
public static void main(String[] args) {
Student student1 = new Student(1,"rr",5.6);
Student(int i,String n,double c) { Student student2 = new Student(2,"cc",6.6);
id=i;
System.out.println("\nDetails of student 1:");
name=n;
cgpa=c; student1.print();
} System.out.println("\nDetails of student 2:");
student2.print();
void print() {
System.out.println("Student ID: " }
+ id); }
System.out.println("Student Name:
" + name);
System.out.println("Student CGPA:
" + cgpa);
}
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Constructors
•Write a java program that would print the information (name, year of joining, salary, address) of three employees by
creating a class named 'Employee'. The output should be as follows:
Name Year of joining Salary Address
Robert 1994 10000 Delhi
Sam 2000 20000 Hyderabad
John 1999 15000 Chennai

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Constructors
class Employee {
class EmployeeDemo{
String name, address;
public static void main(String args[]) {
int yoj, salary; Employee e1=new
Employee(String name, int yoj, int salary, Employee("Robert",1994,10000,"Delhi");
String address) Employee e2=new
{ Employee("Sam",2000,20000,"Hyderabad");
this.name= name; Employee e3=new
this.yoj=yoj; Employee("John",1999,15000,"Chennai");
this.salary=salary;
this.address=address; System.out.println("Name"+"\t"+"YearofJoining"+"\
t"+"Salary"+"\t"+"Address");
}
e1.display();
void display()
e2.display();
{ e3.display();
System.out.println(name+"\t"+yoj+"\ }}
t"+salary+"\t"+address);
Dr.}}
Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Constructor Overloading
• The constructor overloading can be defined as the concept of having more than one constructor
with different parameters so that every constructor can perform a different task.
class Box {
double width; class BoxDemo3 {
double height; public static void main(String args[]) {
double depth;
double vol;
Box() { Box mybox1 = new Box();
width = 10; height = 10; depth = 10; Box mybox2 = new Box(10,20,30);
}
Box(double w, double h, double d) { vol = mybox1.volume();
width = w; System.out.println("volume of first box is " + vol);
height = h;
depth = d;
} vol = mybox2.volume();
double volume() { System.out.println("volume of second box is " + vol);
return width * height * depth; }}
}}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Constructor Overloading

Create a class named BloodData that includes two fields one is


bloodtype to hold blood type (the four blood types are O, A, B, and AB)
and an Rh factor field to hold Rh factor (the factors are + and –).
Create a default constructor that sets the bloddtype to “O” and
Rhfactor to “+”, and an overloaded constructor that requires values for
both fields. Create a class named TestBloodData that demonstrates
each constructor works correctly.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Constructor Overloading
class BloodData { class TestBloodData {
String bloodType; public static void main(String[] args) {
char rhFactor;
BloodData ob1 = new BloodData();
BloodData() { System.out.println("Default Blood Data:");
this.bloodType = "O"; ob1.print();
this.rhFactor = '+';
} BloodData ob2= new BloodData("AB", '-');
System.out.println("\nCustom Blood Data:");
BloodData(String bloodType, char rhFactor) { ob2.print();
this.bloodType = bloodType; }
this.rhFactor = rhFactor; }
}
void print(){
System.out.println("Blood Type: " +bloodType);
System.out.println("Rh Factor: " +rhFactor);
}
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Constructor Overloading

Create a FitnessTracker class that includes data fields for a fitness activity,
the number of minutes spent participating, and the date. The class includes
methods to get each field. In addition, create a default constructor that
automatically sets the activity to “running,” the minutes to 0, and the date to
January 1 of the current year. Create an additional overloaded constructor
for the FitnessTracker class. This constructor receives parameters for each of
the data fields and assigns them appropriately. Create a class that
demonstrates each method works correctly.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Constructor Overloading
import java.text.SimpleDateFormat;
import java.util.Date; class FitnessTrackerDemo {
class FitnessTracker { public static void main(String[] args)throws Exception
String activity; {
int minutes;
FitnessTracker tk1 = new FitnessTracker();
Date date;
System.out.println("Default Fitness Tracker:");
tk1.print();
public FitnessTracker()throws Exception { FitnessTracker tk2 = new FitnessTracker("swimming", 30, new Date());
this.activity = "running"; System.out.println("Custom Fitness Tracker:");
this.minutes = 0; tk2.print();
this.date = new }
SimpleDateFormat("dd/mm/yyyy") .parse("01/01/2024"); }
}
public FitnessTracker(String activity, int minutes, Date date) {
this.activity = activity;
this.minutes = minutes;
this.date = date;
}
void print(){
System.out.println("Activity: " +activity );
System.out.println("Minutes: " + minutes);
System.out.println("Date: " +date);
}
}Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
this keyword
• this keyword can be used inside any method to refer to the current object
• ‘this’ keyword is used to invoke current class instance variables, methods and
constructors.
• When an object is created to a class, a default reference(this) is also created internally
to the object.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


this keyword
class Test {
int a, b; class driver{
Test() public static void main(String[]
{ args)
this(20, 20); {
this.add(); Test object = new
} Test();
Test(int a, int b) }
{ }
this.a = a;
this.b = b;
}
void add()
{
System.out.println("Addition="+(a+b));
}
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Array of Objects in Java
className arrayName[] = new className[size];
where
• className is the name of class, whose objects we store in the array.
• arrayName is the name of the array using which we will access its elements.
• new keyword that allocates memory based on the size of array.
Ex:
Employee[] e=new Employee[4];
e[0]=new Employee("Robert",101,10000);
e[1]=new Employee("Sam",102,20000);
e[2]=new Employee("John",103,15000);
for(int i=0;i<4;i++)
e[i].display();

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Write a Java program to print the name, Id ,salary and avg
salary of 4 employees in a company.
class Employee { class EmployeeArray{
String name; public static void main(String args[]) {
int id,salary; Employee[] e=new Employee[4];

Employee(String name, int id, int salary) e[0]=new Employee("Robert",101,10000);


{ e[1]=new Employee("Sam",102,20000);
this.name=name; e[2]=new Employee("John",103,15000);
this.id=id; e[3]=new Employee("Dev",104,25000);
this.salary=salary;
} int sum=0;
void print() System.out.println("Name"+"\t"+"ID"+"\t"+"Salary");
{ for(int i=0;i<4;i++){
System.out.println(name+"\t"+id+"\t"+salary); e[i].print();
}} sum=sum+e[i].salary;
Robert 101 10000 }
Sam 102 20000 System.out.println("Average Salary="+sum/4);
John 103 15000 }}
Dev 104 25000
Average Salary=17500
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Write a Java program to print the name, Id and salary of
employee who is getting highest salary in a company of 4
employees.
class EmployeeArray{
class Employee { public static void main(String args[]) {
String name; Employee[] e=new Employee[4];
int id,salary; e[0]=new Employee("Robert",101,10000);
e[1]=new Employee("Sam",102,20000);
Employee(String name, int id, int salary) e[2]=new Employee("John",103,15000);
{ e[3]=new Employee("Dev",104,25000);
int index=0;
this.name=name;
int max=e[0].salary;
this.id=id; for(int i=1;i<4;i++)
this.salary=salary; {
} O/p:
if(max<e[i].salary)
Name ID Salary
void print() {
Dev 104 25000
{ max=e[i].salary;
System.out.println(name+"\t"+id+"\t"+salary); index=i;
}} }}
System.out.println("Name"+"\t"+"ID"+"\t"+"Salary");
e[index].print();
}}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Create a class Student with fields id, name and cgpa. Include a constructor to
initialize instance variables and print () method to display the data. Design a
driver class and store four students data and display the name, ID, and cgpa of
the student with the lowest cgpa within the class

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Create a class Student with fields id, name and cgpa. Include a constructor to initialize
instance variables and print () method to display the data. Design a driver class and store four
students data and display the name, ID, and cgpa of the student with the lowest cgpa within
the class
class Student { class LowestCGPA {
int id; public static void main(String[] args) {
String name; Student[] students = new Student[4];
double cgpa; students[0] = new Student(1, "John", 3.5);
students[1] = new Student(2, "Alice", 3.2);
Student(int id, String name, double cgpa) { students[2] = new Student(3, "Bob", 3.8);
this.id = id; students[3] = new Student(4, "Emily", 3.4);
this.name = name; int index=0;
this.cgpa = cgpa; double min = students[0].cgpa;
} for (int i = 1; i < 4; i++) {
if (students[i].cgpa<min) {
void print() { min=students[i].cgpa;
System.out.println("ID: " + id); index= i;
System.out.println("Name: " + name); }
System.out.println("CGPA: " + cgpa); }
} System.out.println("Student with the lowest CGPA:");
} students[index].print();
}}
Encapsulation

• It is a mechanism of wrapping the data (variables) and methods together as a single


unit and keeps both safe from outside interference and misuse.
• In Java, the basis of encapsulation is the class.

• Encapsulation can be achieved by declaring all the variables in the class as private and
writing public methods(setter & getter) in the class to set and get the values of
variables.
• It is a way to achieve data hiding in Java because other class will not be able to access
the data through the private data members.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Encapsulation
class Encapsulate {
private String name; class TestEncapsulation {
private int age; public static void main(String[] args)
public void setName(String name) {
{ Encapsulate ob= new Encapsulate();
this.name = name;
} ob.setName("Havya");
public String getName() ob.setAge(5);
{
return name;
System.out.println(" Name: " +
}
public void setAge(int age)
ob.getName());
{ System.out.println(" Age: " + ob.getAge()
this.age = age;
} }
public int getAge() }
{
return age;
}
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Static Members

• When a variable is declared as static, then a single copy of the variable is created
and shared among all objects of a class.
• When a member is declared static, it can be accessed without help of an object.
• Both methods and variables can be used as static.
• main( ) is declared as static because it must be called before any objects exist.

Ex: static int a=20;


static void show()

From outside class:


classname.method( ); Methods declared as static have several restrictions:
• They can only call other static methods.
classname.variablename;
• They must only access static data.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Static Members

class Student{
int rollno; class TestStaticMethod{
String name; public static void main(String args[]){
static String college; Student.change();
Student(int r, String n){ Student s1 = new Student(111,"Karan");
rollno = r; Student s2 = new Student(222,"Aryan");
name = n; s1.display();
} s2.display();
static void change(){ }
college = "VIT-AP"; }
}
void display() {
System.out.println(rollno+" "+name+" "+college);} }

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Access Specifiers

• An access specifier specifies how to access-the


members of a class or a Class itself.
private: 'private' members of a-class are not
accessible any where outside the class.
public: 'public' members of a class are accessible
every where outside the class.
protected: 'protected' allow members to be seen
outside current package, but only to classes that
subclass your class directly
default: 'default' members are accessible outside
the class, but within the same directory.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Access Specifiers

class Access{ class AccessDemo {


private int a; public static void main(String args[]) {
public int b; Access ob=new Access();
protected int c; ob.a=10; // error a has private access in Access
int d; ob.b=20;
void add() ob.c=30;
{ ob.d=40;
System.out.println(a+b+c+d); ob.add();
} }
} }

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE

You might also like