You are on page 1of 125

Object oriented Programming Concepts

using java

Course Handout and Assessment Mechanism


1.How to develop a simple java program
 open any editor and type the program
 Set the classpath
 Compile the java program using javac command
 Run the java program
2.Control Statements
 Conditional Control Statements
 If
 If-else
 Nested-if
 switch
 Looping Control statements
 while
 For loop
 Do-while
 JAVA FEATURES

 Oops Concepts

 scope of variable

 object creation and its life cycle

 Wrapper classes

 java operators includes string operations

 function overloding

 function overriding

 Array and its types

 static keyword to methods and variables

 Constructor and its types


 constructor overloading

 access modifiers to constructor

 encapsulation principles to class

 destructor

 types of inheritance

 types of polymorphism

 interface and abstract class

 searching and sorting

 stack and queue using java

 exceptions and its types(checked and unchecked)


 exception handling techniques
 Packages
 user defined package
 predefined package
 importing classes and user defined packages from one to other
 command line arguments
 ArrayList and Vector
 thread and multithreading in java
 java thread model
 thread priority and thread synchronization
 inter thread communication
 Input and Output Stream classes in java
 file input and file out stream classes in java
 Random access file
 BufferedReader class and BufferWriter class
 Swings
 Jlable and ImageIcon
 JTextfield, JButton, Jscrollpane
 ActionListener class
 JDBC
 types of JDBC Drivers
 JDBC connection with database
Simple java program to display HelloWorld
 step-1
 open notepad editor:
type the java source code
public class FirstProgram
{
public static void main(String ar[])
{
System.out.println(“HelloWorld”);
}
}
step-2
save the program in a specific folder with file name is
FirstProgram.java
 Step-:3
Set the classpath:
open the command prompt, go to that specific folder where we can save the java
program and set the class path
Example: set path=C:\Program Files\Java\jdk-17\bin;
Step-4:
compile the program
using javac command
Ex: javac (filename)Demo.java
Step-5
Run the program using java com
Ex: java Demo(filename)
How to set Permanent Path of JDK in Windows
 For setting the permanent path of JDK, you need to follow these steps:
• Right click on MyComputer
• choose properties ->
• Select advanced tab ->
• Click on environment variables button ->
Click on new tab of user variable ->
• type path in variable name text box ->
• copy path of bin folder in variable value text box ->
• Then click on ok -> ok -> ok

JAVA FEATURES
 Simple
 Object-Oriented
 Portable
 Platform independent
 Secured
 Robust
 Architecture neutral
 Interpreted
 High Performance
 Multithreaded
 Distributed
 Dynamic
Platform Independence
 Computer programs are very closely related to specific hardware and operating
system.
 Windows applications cannot run on Mac Operating System. Mac applications
cannot run on the Android Operating system, and so on.
 Java code is not complied into platform specific machines. Java Code can be
executed on multiple platforms like Windows, Linux, Mac/OS etc.
 Java is called Platform Independent because programs written in Java can be
run on multiple platforms without re-writing them individually for a particular
platform, i.e., Write Once Run Anywhere (WORA).
 How Java Provides Platform Independence?
 Source code is very similar to human language, consisting of words and
phrases. It has to be converted into machine language code, which computers
can easily understand and execute.
 The process of converting source code into machine code is called
compilation. Machine Language Code is unique for different platforms.
 Ordinary Compilation Process
 The code is first converted into machine-readable language when the C/C++
program is written and compiled in Windows OS
Step-by-Step Execution of Java Program
 While compiling the java program,Instead of generating the machine(os) based
instructions directly, java compiler generates .class file first.
 Java Virtual Machine or JVM is a special Java Interpreter. Java Virtual Machine takes
.class file as input. It interprets and executes the byte code and provides the output
of the program.
 A compiler translates the entire program at once into machine-readable code. An
Interpreter also converts the program to machine code, but it does so by translating it
instruction-by-instruction or line-by-line.
Java Virtual Machine
 JVM is part of the Java Runtime Environment (JRE) and acts as a
runtime engine to run Java applications.
 JVM is responsible to load the .class file and generates its
machine(platform) based instructions.
Control Statements in java
 Control Statements are the base of any programming
language. Using control statements we implement real
world scenarios in programs.
 There are three types of Control Statements in Java:
1. Decision-Making Statements
2. Loop Statements
3. Jumping Statements

Control statements in Java are one of the fundamental


features of Java which provides a smooth flow of the
program.
Decision-Making Statements
 These are used to execute the statements based on
specified condition
 Decision-making statements in Java are similar to making
a decision in real life, where we have a situation and
based on certain conditions we decide what to do next.
 For example, if it's raining outside then we need to carry
an umbrella. In programming also, we have some
situations when we need a specific code to be executed
only when a condition is satisfied.
 There are four types of decision-making statements in
Java:
1. if Statement

If the condition is true,


then the code is
executed otherwise not.
Syntax:
if(CONDITION){
Statement1;
}
default statement;
2. if-else Statement
In this, if the condition is true
then the code inside the if block is
executed otherwise the else block
is executed.
Syntax:
if(CONDITION){
Statement1;
}
else{
Statement2;
}
default statement;
3. Nested if-else Statement
Nested control statements mean an if-else statement inside other if or else blocks.

It is similar to an if-else statement but they are defined inside another if-else statement.

Syntax:

if(condition1)

if(condition2){

Statement1;

else

stmt2;

else{

stmt3;

}
4. if-else-if Ladder
 In this, the if statement is followed by multiple else-
if blocks. We can create a decision tree by using these
control statements in Java.
 If the specified condition is true, then it execute the
statement. Otherwise execution moves onto else, in
else once again check the condition, if it is true then
execute the statement, otherwise execution moves on
to else.
 If none of the conditions is true, the last else block is
executed(default statement)
Syn:
if(Cond1)
{
Stmt1;
}
else{
if(Cond2)
{
Stmt2;
}
else{
Stmt3;
}
}
5. switch
Statement
 Switch statements are almost similar to the if-else-if ladder
control statements in Java. It is a multi-branch statement. It
is a bit easier than the if-else-if ladder and also more user-
friendly and readable.
 We can use case values instead of conditions.
 Note:
 The expression can be of type String, short, byte, int, char,
 We cannot have any duplicate case values.
 The default statement is optional.
 Usually, the break statement is used inside the switch to
terminate a statement sequence.
 The break statement is optional.
Syntax:
switch(expression)
{
case value1:
Stmt1;
break:
case value2:
Stmt2;
break;
case value3:
Stmt3;
break;
default:
Stmtn;
}
Looping Statements in java
 The java programming language provides a set of
iterative statements that are used to execute a
statement or a block of statements repeatedly as long as
the given condition is true.
 The iterative statements are also known as looping
statements or repetitive statements.
• while statement
• do-while statement
• for statement
• for-each statement
while statement
 The while statement is used to execute a single
statement or block of statements repeatedly as long as
the given condition is TRUE.
 The while statement is also known as Entry control
looping statement.
 Minimum number of execution of a statement in while
is -0.
 It is also called pre-test loop. While entering into the
loop, it checks the condition.
do-while statement in java
 The do-while statement is used to execute a single
statement or block of statements repeatedly as long as
given the condition is TRUE.
 The do-while statement is also known as the Exit
control looping statement.
 Minimum number of execution of a statement in do
while is-1
 It is also called as post –test loop, i.e; while leaving
from the loop it checks the condition.
 Most used loop by users.
for statement in java
 The for statement is used to execute a single statement or a block of
statements repeatedly as long as the given condition is TRUE.
 The Java for loop is the most powerful and versatile of iterative
statements.
 Easy to implement.
 Most commonly used loop.
 In for-statement, the execution begins with
the initialization statement. After the initialization statement, it
executes Condition.
 If the condition is evaluated to true, then the block of statements
executed otherwise it terminates the for-statement.
 After the block of statements execution, the modification statement
gets executed
For statement
 Syntax:
for(initialization; condition; updation)
{
Statement;
}
in for statement initialization section executes into only once.
If we know the no of iterations well in advance then for loop is
the best choice.

specifying curly braces are optional. Without curly braces we can


take only one statement under for loop.
for(int i=0;i<10;i++); // valid statement.
 Ex:
 for(int i=0; i<10;i++)
 {
 System.out.println(“hi”);
 }
 here i variable is a local variable.
 we can declare multiple variables in for loop but should be
same type of variable only.if we can declare different data type
variables, we will get compile time error.
 int i=0,j=0; //valid statement
 int i=0,int j=0; //invalid statements
 int i=0, char c=‘d’; // invalid
 Initialization section allows any valid java statement including
System.out.println() also.
 Ex:
 int i=0;
 for(S.o.p(“hello guys r u listen”); i<3; i++)
 {
 S.o.p(“no sir we are chit chat with friends”);
 }
 o/p;
 hello guys are r u listen
 no sir we are chit chat with friends
 no sir we are chit chat with friends
 no sir we are chit chat with friends.
 i.e; in the initialization we can take any valid java statement including sop
 Conditional statement is optional. if we cant specify the condition then
compiler takes it as true.
 It can take any valid java expression but should be of the Boolean.
We can take any valid java statement including Sop as updating part.
 Ex:
 int i=0;
 for(S.o.p(“hello”); i<3; S.o.p(“hi”))
 {
 i++;
 }
 O/P: hello
 hi
 hi
 hi
 All three parts of for are independent and specifying these parts are optional.
 But if we are not specify all three parts, then we will get infinite loop.
 Ex:
 for( ; ; )
 {
 System.out.println(“hi”);
 }
 o/p: infinite loop
 or
 for( ; ;);
 O/P: infinite loop
Data types in java
 Data types is an identifier, which describes what kind of data
stored in a variable.
 In java, data types are classified into two types and they are
as follows.
• Primitive Data Types
• Non-primitive Data Types
Data Type Default Value Default size
boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
Type casting in java
 Casting is a process of changing one type value to another type. In Java, we
can cast one type of value to another type. It is known as type casting.
In Java, type casting is classified into two types,
•Widening Casting(Implicit)

•Narrowing Casting(Explicitly done)


Java program to perform widening or automatic type conversion
in java.
 Algorithm:

1. Start
2. Create an instance of the Scanner class.
3. Declare a variable.
4. Ask the user to initialize it.
5. Perform the widening or automatic type conversion.
6. Print the value for each data type.
7. Stop.
 import java.util.Scanner;

 public class Main

 {

 public static void main(String[] args)

 {

 //Take input from the user

 // create an object of Scanner class

 Scanner sc = new Scanner(System.in);

 // ask users to enter the number

 System.out.println("Enter the number: ");

 int i=sc.nextInt();

 // widening or automatic type conversion

 long l = i;

 float f = l;

 double d= f;

 System.out.println("After widening or automatic type conversion values are: ");

 System.out.println("Int value "+i);

 System.out.println("Long value "+l);

 System.out.println("Float value "+f);

 System.out.println("Double value "+d);

 }

 }
Java program to perform narrowing or explicite type conversion
in java.
 Algorithm:

1. Start
2. Create an instance of the Scanner class.
3. Declare a variable.
4. Ask the user to initialize it.
5. Perform the narrowing or explicite type conversion.
6. Print the value for each data type.
7. Stop.
 //Type Casting Program in Java

 import java.util.Scanner;

 public class ExpliciteCasting

 {

 public static void main(String[] args)

 {

 //Take input from the user

 // create an object of Scanner class

 Scanner sc = new Scanner(System.in);

 // ask users to enter the number

 System.out.println("Enter the number: ");

 double d=sc.nextDouble();

 // narrowing or explicit type conversion

 float f=(float)d;

 //explicit type casting

 long l = (long)d;

 //explicit type casting

 int i = (int)l;

 System.out.println("After narrowing or explicit type conversion values are: ");

 System.out.println("Double value: "+d);

 //fractional part lost

 System.out.println("Float value: "+f);

 System.out.println("Long value: "+l);

 //fractional part lost

 System.out.println("Int value: "+i);

 }

 }
Garbage collector in java
 Garbage Collection is process of reclaiming the runtime unused
memory automatically. In other words, it is a way to destroy the
unused objects.
 we were using free() function in C language and delete() in C++. But, in
java it is performed automatically. So, java provides better memory
management.
 The garbage collection is a part of the JVM and is an automatic process
done by JVM.
 Garbage Collection can not be forced explicitly. We may request JVM
for garbage collection by calling System.gc() method.
Advantages of Garbage Collection
 Programmer doesn't need to worry about dereferencing an object.
 It is done automatically by JVM.
 Increases memory efficiency and decreases the chances for memory
leak.
How can an object be unreferenced?
1. By nulling the reference
2. By assigning a reference to another
3. By anonymous object etc.
 1.By nulling the reference.
 set null to object reference which makes it able for garbage
collection.
 For example:
 CSE cs= new CSE();
 cs=null; //which is ready for garbage collection.
 2. CSE cs= new CSE();
 CSE cs1= new CSE();
 cs= cs1;
 3. Anonymous object does not have any reference so if it is not in use, it is
ready for the garbage collection.

finalize() method
Sometime an object will need to perform some specific task before it is destroyed such as closing an
open connection or releasing any resources held. To handle such situation finalize() method is used.
The finalize() method is called by garbage collection thread(DAEMON THREAD) before collecting
object.
The gc() method is used to invoke the garbage collector to perform cleanup processing.
public class TestGarbage1{
public void finalize()
{System.out.println("object is garbage collected");
}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
} }
Wrapper classes in Java
 The wrapper class in Java provides the mechanism to convert primitive into
object and object into primitive.
 Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects
and objects into primitives automatically.
 Use of Wrapper classes in Java
 Java is an object-oriented programming language, so we need to deal with
objects many times like in Collections, Serialization, Synchronization, etc.
 Serialization: We need to convert the objects into streams to perform the
serialization. If we have a primitive value, we can convert it in objects through
the wrapper classes.
 Synchronization: Java synchronization works with objects in Multithreading.
 Collection Framework: Java collection framework works with objects only. All
classes of the collection framework (ArrayList, LinkedList, Vector, HashSet,
LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.
 The eight classes of the java.lang package are known as wrapper classes in Java.
The list of eight wrapper classes are given below:
Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double
Autoboxing
 The automatic conversion of primitive data type into its corresponding wrapper
class is known as autoboxing, for example, byte to Byte, char to Character …..etc.
 Since Java 5, we do not need to use the valueOf() method of wrapper classes to
convert the primitive into objects.
//Autoboxing example of int to Integer
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly

Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally


System.out.println(a+" "+i+" "+j);
}
}
unboxing
 The automatic conversion of wrapper type into its corresponding primitive type
is known as unboxing.
 It is the reverse process of autoboxing. Since Java 5, we do not need to use the
intValue() method of wrapper classes to convert the wrapper type into
primitives.

 //Unboxing example of Integer to int


 public class WrapperExample2{
 public static void main(String args[]){
 //Converting Integer to int
 Integer a=new Integer(3);
 int i=a.intValue();//converting Integer to int explicitly
 int j=a;//unboxing, now compiler will write a.intValue() internally
 System.out.println(a+" "+i+" "+j);
 }
 }
Arrays in java
 Normally, an array is a collection of similar type of elements which has
contiguous memory location.
 Java array is an object which contains elements of a similar data type.
Additionally, The elements of an array are stored in a contiguous memory
location.
 An array is a collection of similar data values with a single name. An array can
also be defined as, a special type of variable that holds multiple values of the
same data type at a time.
 In java, arrays are objects and they are created dynamically
using new operator.
 We can store only a fixed set of elements in a Java array.
 Every array in java is organized using index values. The index value of an array
starts with '0' and ends with ‘szise-1'. We use the index value to access
individual elements of an array.
 Advantages
• Code Optimization: It makes the code optimized, we can retrieve or sort
the data efficiently.
• Random access: We can get any data located at an index position.
 Disadvantages
• Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.
• To use the java arrays, we use the following approaches.
1st way
1) array declaration:
2) array instantiation: creating objects.
3) array initialization.
 Example:
 1) int a[];
 2) a=new int[5];
 3] a[0]=10;
 a[1]=20;
 ………..

2nd way:
directly assign the values to an array.
int a[]= {1,2,3,4};
We can display the data from array by three ways.
by using index values.
by using for loop.
by using for each loop.
 Array will be created with some specific blocks with default values first.
 the default value is 0.
 When we assign the values to array then default values are modified.
In java arrays are two types:
 single dimensional
 double dimensional.

 The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of


the array in negative, equal to the array size or greater than the array size while traversing
the array.
 NullPointerException with Arrays
 In java, an array created without size and initialized to null remains null only. It does not
allow us to assign a value. When we try to assign a value it generates
a NullPointerException.
 Example:
 int a[]=null;
 S.O.P(a);// throws exception

 public class ArrayDemo
 {
 public static void main(String arr[])
 {
 int a[]= {1,2,3,4};
 int b[]= new int[3];
 b[0]=15;
 System.out.println(a[0]);
 System.out.println(a[1]);
 System.out.println(a[2]);
 System.out.println(a[3]);
 System.out.println(b[0]);

 for(int i=0; i<b.length; i++)


 {
 System.out.println(b[i]);
 }
 for(int aa:a)
 {
 System.out.println(a[aa]);
 }

 }
 }
String class in java
 In Java, string is basically an object that represents sequence of char values.
An array of characters works same as Java string.
 In java string represented by string class which is located in java.lang package.
 It is probably the most commonly used class in java library.
 string objects are immutable that means once a string object is created it
cannot be changed.
 In Java, CharSequence Interface is used for representing a sequence of
characters. CharSequence interface is implemented by String, StringBuffer and
StringBuilder classes. This three classes can be used for creating strings in java.
 The Java String is immutable which means it cannot be changed. Whenever we change
any string, a new instance is created. For mutable strings, you can use StringBuffer and
StringBuilder classes.
 The java.lang.String class is used to create a string object.
 How to create a string object?
 There are two ways to create String object:
1. By string literal
2. By new keyword

1) String Literal
 Java String literal is created by using double quotes. For Example:
1. String s="welcome";
 Each time you create a string literal, the JVM checks the "string constant pool" first. If
the string already exists in the pool, a reference to the pooled instance is returned. If
the string doesn't exist in the pool, a new string instance is created and placed in the
pool. For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
Each time we create a String literal, the JVM checks the
string pool first. If the string literal already exists in the
pool, a reference to the pool instance is returned. If string
does not exist in the pool, a new string object is created,
and is placed in the pool. String objects are stored in a
special memory area known as string constant pool inside
the heap memory.
 By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variabl
e
String objects are immutable because:

class TestString
{
public static void main(String ar[]){
String s= new String("mahender");
s.concat("nagurla");
System.out.println(s);
}
}
o/p: mahender
 StringBuffer class:
 Java StringBuffer class is used to create mutable (modifiable) String
objects. The StringBuffer class in Java is the same as String class
except it is mutable i.e. it can be changed.
 class StringBufferExample{
 public static void main(String args[]){
 StringBuffer sb=new StringBuffer("Hello ");
 sb.append("Java");//now original string is changed
 System.out.println(sb);//prints Hello Java
 }
 }
 Output:

 Hello Java
charAt() Returns the character at the specified index (position) char

codePointAt() Returns the Unicode of the character at the specified int


index

codePointBefore() Returns the Unicode of the character before the int


specified index

codePointCount() Returns the number of Unicode values found in a string. int

compareTo() Compares two strings lexicographically int

concat() Appends a string to the end of another string String

endsWith() Checks whether a string ends with the specified boolean


character(s)

equals() Compares two strings. Returns true if the strings are boolean
equal, and false if not

split() Splits a string into an array of substrings String[]

startsWith() Checks whether a string starts with specified boolean


characters

subSequence() Returns a new character sequence that is a CharSequence


subsequence of this sequence

substring() Returns a new string which is the substring of String


a specified string

toCharArray() Converts this string to a new character array char[]

toLowerCase() Converts a string to lower case letters String

toString() Returns the value of a String object String

toUpperCase() Converts a string to upper case letters String

trim() Removes whitespace from both ends of a String


string

valueOf() Returns the string representation of the String


 StringBuffer class methods:

 StringBuffer Class append() Method


 concatenates the given argument with this String
 StringBuffer insert() Method
 insert() method inserts the given String with this string at the given position.
 StringBuffer replace() Method
 replace() method replaces the given String from the specified beginIndex and
endIndex.
 StringBuffer delete() Method
 delete() method of the StringBuffer class deletes the String from the specified
beginIndex to endIndex.
StringBuffer reverse() Method
reverse() method of the StringBuilder class reverses the current String.
 String s1=new String(“mahi”);
 String s2=new String(“mahi”);
 Sop(s1==s2); //false
 Sop(s1.equals(s2)); true

 StringBuffer sb2=new StringBuffer(“mahi”);


 StringBuffer sb2=new StringBuffer(“mahi”);
 Sop(sb2==sb2); //false
 Sop(s1.equals(s2)); false
Methods in Java
 Method in Java is similar to a function defined in other programming
languages. Method describes behavior of an object.
 A method is a collection of statements that are grouped together to
perform an operation.
 It provides the reusability of code.
 We write a method once and use it many times. We do not require to
write code again and again.
 Method Signature: Every method has a method signature. It is a part of
the method declaration. It includes the method name and parameter
list.
 Access Specifier: Access specifier or modifier is the access type of the
method. It specifies the visibility of the method. Java
provides four types of access specifier:
 Return Type: Return type is a data type that the method returns. It may
have a primitive data type, object, collection, void, etc. If the method
does not return anything, we use void keyword.
 Method Name: It is a unique name that is used to define the name of a
method. It must be corresponding to the functionality of the method.
 Parameter List: It is the list of parameters separated by a comma and
enclosed in the pair of parentheses. It contains the data type and
variable name.
 Method Body: It is a part of the method declaration. It contains all the
actions to be performed. It is enclosed within the pair of curly braces.
 Types of Method
 There are two types of methods in Java:
1. Predefined Method
2. User-defined Method
3. In Java, predefined methods are the method that is already
defined in the Java class libraries is known as predefined
methods.
4. Some pre-defined methods are length(), equals(), compareTo(),
sqrt(), main()etc.
Java main() method
 The main() is the starting point for JVM to start execution of a Java program.
Without the main() method, JVM will not execute the program.
 main(): It is a default signature which is predefined in the JVM. It is called by
JVM to execute a program line by line and end the execution after
completion of this method.
 String args[]: The main() method also accepts some data from the user. It
accepts a group of strings, which is called a string array.
 Here, agrs[] is the array name, and it is of String type. It means that it can
store a group of string. Remember, this array can also store a group of
numbers but in the form of string only.
 What happens if the main() method is written without
String args[]?
 The program will compile, but not run, because JVM will not recognize the
main() method. Remember JVM always looks for the main() method with a
string type array as a parameter.
 class MainExample
 {
 public static void main()
 {
 System.out.println("hi");
 }
 }
 Execution Process
 First, JVM executes the static block, then it executes static methods.
 Finally, it executes the instance methods.
 JVM executes a static block on the highest priority basis.
 It means JVM first goes to static block even before it looks for the main() method in the
program.
1. class MainDemo
2. {
3. static //static block O/P : Static block Static method
4. {
5. System.out.println("Static block");
6. }
7. public static void main(String args[]) //static method
8. {
9. System.out.println("Static method"); }}
 public static void main(String args[])
 static public void main(String args[])
 static public void main(String...args)
 String...args: It allows the method to accept zero or multiple arguments. There
should be exactly three dots between String and array; otherwise, it gives an
error.
 A program that has no main() method, but compile and runs successfully.
1. abstract class DemoNoMain extends javafx.application.Application
2. {
3. static //static block
4. {
5. System.out.println("Java");
6. System.exit(0);
7. }
8. } O/P: Java
USER DEFINED METHODS IN JAVA
 The method written by the user or programmer is known as a user-
defined method. These methods are modified according to the requirement.
 The major advantage of methods is code re-usability (define the code once, and
use it many times).
 Every method in java must be declared inside a class.

 How to Declare Methods in Java?


 There are a total of six components included in a method
declaration.
 While defining a method, remember that the method name must
be a verb and start with a lowercase letter.
 In the multi-word method name, the first letter of each word
must be in uppercase except the first word.
 Single-word method name: sum(), area()
 Multi-word method name: areaOfCircle(), stringComparision()
 How to call a method/ method calling?
 To call a method in Java, you have to write the method’s name
followed by parentheses () and a semicolon ;
 Ex: objectname. display();
 objectname. show(20);
 Java Program on with arguments and return values
 Public class UserDefinedExample
 {
 public int subNumbers(int x, int y){
 int sub=x-y;
 return sub;
 }
 Public static void main(String ar[])
 {
 int n1=20;
 int n2=30;
 UserDefinedExample obj= new UserDefinedExample(n1,n2);
 Int output= obj.subNumbers(n1,n2);
 System.out.println(“substarction is:” + output);
 }}
Returning Multiple values
 In Java, we can return multiple values from a method by using array.
 We store all the values into an array that want to return and then return back it to the caller
method. We must specify return-type as an array while creating an array.
 class MethodDemo2{
 static int[] total(int a, int b) {
 int[] s = new int[2];
 s[0] = a + b;
 s[1] = a - b;
 return s;
 }
public static void main(String[] args)
 {
 int[] s = total(200, 70);
 System.out.println("Addition = " + s[0]);
 System.out.println("Subtraction = " + s[1]);
 } }
 Methods in Java can also be classified into the following types:
 Static Method
 Instance Method
 Abstract Method
 Factory Method
Instance Method
The method of the class is known as an instance method. It is
a non-static method defined in the class. Before calling or invoking
the instance method, it is necessary to create an object of its class.
 Accessor Method: The method(s) that reads the instance variable(s) is known as
the accessor method. We can easily identify it because the method is prefixed
with the word get
 Mutator Method: The method(s) read the instance variable(s) and also modify
the values. We can easily identify it because the method is prefixed with the
word set
 public class InstanceMethodExample
 {
 int s;
 public int add(int a, int b)
 {
 s = a+b;
 return s;
 }
 public static void main(String [] args)
 {
 InstanceMethodExample obj = new InstanceMethodExample();
 int sum=obj.add(12,13);
 System.out.println(sum);
 }
 }
Java static keyword
 The static keyword in Java is used for memory management mainly. We can apply
static keyword with variables, methods, blocks and nested classes.
 The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class

5. Static variables:
 If you declare any variable as static, it is known as a static variable.
• The static variable can be used to refer to the common property of all objects
(which is not unique for each object), for example, the company name of
employees, college name of students, etc.
• The static variable gets memory only once in the class area at the time of class
loading.
 Advantages of static variable
 It makes your program memory efficient (i.e., it saves memory).
 Understanding the problem without static variable
1. class Student{
2. int rollno;
3. String name;
4. String college=“SRU";
5. }
 Suppose there are 3000 students in my college, now all instance data members
will get memory each time when the object is created.
 All students have its unique rollno and name, so instance data member is good
in such case. Here, "college" refers to the common property of all objects.
 If we make it static, this field will get the memory only once.

When we have a class variable like this, defined using the static keyword, then the
variable is defined only once and is used by all the instances of the class.

 class area SRU

name
 obj1 Rollno
rollno
obj2 name
 rno

name

 heap
 class Employee
 {
 int eid;
 String name;
 static String company = "SRU";
 public void show()
 {
 System.out.println(eid + "-" + name + "-" + company);
 }
 public static void main( String[] args )
 {
 Employee se1 = new Employee();
 se1.eid = 104;
 se1.name = "Abhijit";
 se1.show();
Employee se2 = new Employee();
 se2.eid = 108;
 se2.name = "ankit";
 se2.show();
 }
Static methods in java
 Any method that uses the static keyword is referred to as a
static method.
 If the keyword static is prefixed before the method name, the
function is called a static method.
 you can call a static method without creating an object of the
class. Static methods are sometimes called class methods.
 Static methods do not need instance of its class for being
accessed.
 main() method is the most common example of static method.
 main() method is declared as static because it is called before
any object of the class is created.
Properties of Static Function
 It can access only static members.
 It can be called without an instance.
 It is not associated with the object.
 Non-static data members cannot be accessed by the static function.
Syntax:
1. [access specifier] static [return type] [function name] (parameter list)
2. {
3. //body of the function
4. }
 Calling Static Function
 In Java, we cannot call the static function by using the object. It is invoked by
using the class name.
1. [class name].[method name]

 import java.io.*;
 class StaticMethodExample1 {
 static int a = 40;
 int b = 50;
 void simpleDisplay()
 {
 System.out.println(a);
 System.out.println(b);
 }
 static void staticDisplay()
 {
 System.out.println(a);
 }}
 class StaticMethodExample{
 public static void main(String[] args) {
 StaticMethodExample1 obj = new StaticMethodExample1();
 obj.simpleDisplay();
 StaticMethodExample1.staticDisplay();
 }}
 A constructor is a special method that is used to initialize an object.
Every class has a constructor either implicitly or explicitly.
 It is called when an instance of the class is created. At the time of
calling the 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.
 constructor is a method that is called at runtime during the object
creation by using the new operator.
 The JVM calls it automatically when we create an object. When we
do not define a constructor in the class, the default constructor is
always invisibly present in the class.
 In short, we use the constructor to initialize the instance variable of
the class.
 We use constructors to initialize the object with the default or initial
state. The default values for primitives may not be what are you
looking for.
 Rules for creating Java constructor
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
 class classname
 {
 <class-name>( ) // constructor
 {
 code statements;
 }
Types of Constructor
 Java Supports two types of constructors:
• Default Constructor
• Parameterized constructor

 Default Constructor
 In Java, a constructor is said to be default constructor if it does
not have any parameter. Default constructor can be either user
defined or provided by JVM.
 If a class does not contain any constructor then during runtime
JVM generates a default constructor which is known as system
define default constructor.
 Syntax:
 class classname {
 <class-name>( ) // constructor
 {
 code statements; }
Example:
 class CSE {
 CSE( ) // default constructor
 {
 } }
class ConstructorDemo {
 public static void main(String ar[]) {
 System.out.println("hi");
 } }
 Java Program on Default Constructor
 A constructor which has a specific number of parameters is called a
parameterized constructor.
 Why use the parameterized constructor?
 The parameterized constructor is used to provide different values to
distinct objects. However, you can provide the same values also.
 A constructor that has parameters is known as parameterized constructor.
If we want to initialize fields of the class with our own values, then use a
parameterized constructor.
 Syntax:
 class classname
 {
 <class-name>( parameters list) // parameterized constructor
 {
 code statements;
 }
Copy Constructor
 In Java, a copy constructor is a special type of constructor that
creates an object using another object of the same Java class. It
returns a duplicate copy of an existing object of the class.
 It cannot be inherited by the subclasses. If we try to initialize a
child class object from a parent class reference, we face the casting
problem when cloning it with the copy constructor.
• If a field declared as final, the copy constructor can change it.
• There is no need for typecasting.
 Avoid the use of the Object.clone() method.
 If we are using the clone() method it is necessary to import
the Cloneable The method may throw the
exception CloneNotSupportException. So, handling the exception
in a program is a complex task. While in copy constructor there are
no such complexities.
 Method overloading is a concept that allows to declare multiple
methods with same name but different parameters in the same
class.
 If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
 Method overloading increases the readability of the program.
 Method overloading in Java is also known as Compile-time
Polymorphism, Static Polymorphism, or Early binding.
 Different Ways of Method Overloading in Java
1. Changing the Number of Parameters.
2. Changing Data Types of the Arguments.
3. Changing the Order of the Parameters of Methods
 Example:
 class CSE
 {
 void display(int a, int b)
 {
 }
 void display(int a, int b, int c) // no of parameters changed
 {
 }
 void display(int a, float f) // type of parameters changed
 { }
 void display(int b, float a) // order of parameters changed
 {
 }
 }
 Java program on methodoverloading
 One type is promoted to another implicitly if no matching datatype is found.
 As displayed in the below diagram, byte can be promoted to short, int, long, float
or double. The short datatype can be promoted to int, long, float or double. The
char datatype can be promoted to int,long,float or double and so on.

Short
Byte

Int long float double

Char
 In Java, we can overload constructors like methods.
 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.
 Overloaded constructors are differentiated on the basis of their type of
parameters or number of parameters.
 When we create an object to class JVM creates a default constructor to a
class to initialize the instance variables with default values.
 Constructor Chaining
 Constructor chaining is a process of calling one constructor from another
constructor in the same class. Since constructor can only be called from
another constructor, constructor chaining is used for this purpose.
 To call constructor from another constructor this keyword is used. This
keyword is used to refer current object.
 In Java, when we create an object of the class it occupies some space in
the memory (heap). If we do not delete these objects, it remains in the
memory
 To resolve this problem, we use the destructor.
 The destructor is the opposite of the constructor. The constructor is used
to initialize objects while the destructor is used to delete or destroy the
object that releases the resource occupied by the object.
 there is no concept of destructor in Java. In place of the destructor, Java
provides the garbage collector that works the same as the destructor.
 When an object completes its life-cycle the garbage collector deletes
that object and deallocates or releases the memory occupied by the
object.
 The Java Object class provides the finalize() method that works the same
as the destructor.
 Inheritance is one of the key features of Object Oriented Programming.
Inheritance provided mechanism that allowed a class to inherit property of
another class. When a Class extends another class it inherits all non-private
members including fields and methods.
 We can create a new class from existing class.
 Acquiring the properties from one class to another class.
 Inheritance defines is-a relationship between a Super class and its Sub class.
extends and implements keywords are used to describe inheritance in Java.
• Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
• Sub Class/Child Class: Subclass is a class which inherits the other class. It is
also called a derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
 Advantages of Inheritance:
1. It promotes the code reusabilty i.e the same methods and variables which are
defined in a parent/super/base class can be used in the child/sub/derived class.
2. It promotes polymorphism by allowing method overriding.

 Main disadvantage of using inheritance is that the two classes (parent and
child class) gets tightly coupled. This means that if we change code of parent
class, it will affect to all the child classes which is inheriting/deriving the parent
class.
 The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
In inheritance We always create the object to subclass. With this, we can access
the data members from sub class and its super class.
Types of Inheritance
 Java mainly supports only four types of inheritance that are listed below.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance:(It is not achieved directly but possible through
interface)

BTECH
 1.Single Inheritance:
 When a class extends to another class then it forms single inheritance.
 One class is inherited from only one super class
 In single inheritance only one super class and only one sub class CSE
 Multilevel Inheritance:
 When a class extends to another class that also extends some other class forms a
multilevel inheritance.
 In multi level inheritance, we have one Super class, one sub class along with
intermediate classes.
 Here Intermediate classes act as Super class and sub class based on situation.
 Syntax;
A
 Class A //super class
 {
 }
 class B extends A //sub class/
B
 super class
 {
 }
 class C extends B //sub class
 { C
 }
 Hierarchical Inheritance:
 When two or more classes inherits a single class, it is
known as hierarchical inheritance.
 In this inheritance, we can create two or more new classes
from a single super class.
 Syntax:
 class A A
 {
 }
 class B extends A
 {
B C
 }
 class C extends A
 {
 }
 If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
 Method overriding is a process of overriding base class method by derived class
method with more specific definition.
 It is performed between two classes using inheritance relation.
 Method overriding performs only if two classes have is-a relationship.(inheritance)
 Method overriding is also referred to as runtime polymorphism because calling
method is decided by JVM during runtime.
 Rules for Method Overriding
 1. Method name must be same for both parent and child classes.
2. Private, final and static methods cannot be overridden.
 3. There must be an IS-A relationship between classes (inheritance).
 class Eamcet {
 protected void displayInfo() {
 System.out.println("Iam aspirant of Eamcet");
 }
 }

 class Btech extends Eamcet {


 public void displayInfo() {
 super.displayInfo();
 System.out.println("Iam a Btech student");
 }
 }

 class MethodOverriding {
 public static void main(String[] args) {
 Btech d1 = new Btech();
 d1.displayInfo();
 }
 }
 In Java, this is a keyword which is used to refer current
object of a class. we can it to refer any member of the class. It
means we can access any instance variable and method by
using this keyword.
 The main purpose of using this keyword is to solve the
confusion when we have same variable name for instance and
local variables.
 We can use this keyword for the following purpose.
• this keyword is used to refer to current object.
• this is always a reference to the object on which method was
invoked.
• this can be used to invoke current class constructor.
this: to refer current class instance
1. variable
class Student{
2. int rollno;
3. String name;
4. Student(int rollno,String name) {
5. this.rollno=rollno;
6. this.name=name;
7. }
 this: to invoke current class method
1. class A{
2. void show(){
3. System.out.println("hello m"); }
4. void display(){
5. System.out.println("hello n");
this.show();
1. } }
 The super keyword in Java is a reference variable which is used to refer immediate
parent class object.
• super variable refers immediate parent class instance.
• super variable can invoke immediate parent class method.
• super() acts as immediate parent class constructor and should be first line in child
class constructor.

 Abstraction is the concept of object-oriented programming that “shows”
only essential attributes and “hides” unnecessary information.
 The main purpose of abstraction is hiding the unnecessary details from the
users.
 A class which is declared using abstract keyword known as abstract class.
An abstract class may or may not have abstract methods.
 We cannot create object of abstract class.
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
 An abstract class is a class that contains at least one abstract method.
 Abstract class can have concreate methods and abstract methods.
 Syntax:
 abstract class class_name
 {
 code of a class:
 }
 Example:

 abstract class CSE


 {
 code of a class:
 }
 Abstract method:
 a method which is declared with a keyword abstract.
 Abstract Method is a method that has just the method definition but
does not contain implementation.
 A method without a body is known as an Abstract Method.
 If we don’t know the implementation, it is also possible to declare a
method as abstract
 The method body will be defined by its subclass. Abstract method can
never be final and static. Because any class that extends an abstract
class must implement all the abstract methods.
 Syntax:
 abstract return_type function_name ( ); //No definition
Example:
abstract void show( );
 Interface is a concept which is used to achieve abstraction in Java.
 This is the only way by which we can achieve full abstraction.
 The interface in Java is a mechanism to achieve abstraction.
 There can be only abstract methods in the Java interface, not method
body. It is used to achieve abstraction and multiple inheritance in Java.
 Interfaces are syntactically similar to classes, but you cannot create
instance of an Interface and their methods are declared without any body.
 When an interface inherits another interface extends keyword is used
whereas class use implements keyword to inherit an interface.
 from Java 8, interface can have default and static methods and from Java
9, it can have private methods as well.
 Advantages of Interface
• It Support multiple inheritance
• It helps to achieve abstraction
• Methods inside interface must not be static, final, native or strictfp.
• All variables declared inside interface are implicitly public, static and final.
• All methods declared inside interfaces are implicitly public and abstract, even if you
don't use public or abstract keyword.
• Interface can extend one or more other interface.
• Interface cannot implement a class.
• Interface can be nested inside another interface.
 How to declare an interface?
 An interface is declared by using the interface keyword. It provides total
abstraction; means all the methods in an interface are declared with the empty
body,
 Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5.
6. }
 Extending Interfaces
 An interface can extend another interface in the same way that a class can
extend another class.
 The extends keyword is used to extend an interface, and the child interface
inherits the methods of the parent interface.
 Example;
 interface Runnable // parent interface
 {
 code of interface
 }
 interface CSE extends Runnable
 {
 code of sub interface
 }
 Though classes in Java doesn't support multiple inheritance, but a class can
implement more than one interfaces.
 If a class implements multiple interfaces, or an interface extends multiple interfaces, it
is known as multiple inheritance.

You might also like