You are on page 1of 123

JAVA PROGRAMMING

(MR23-1CS0105)

UNIT-I
OOP’s CONCEPTS

Java Programming
Python Programming Unit 1
4 Department of CSE
Procedure oriented Programming:
 In this approach, the problem is always considered as a sequence of
tasks to be done. A number of functions are written to accomplish
these tasks. Here primary focus on ―Functions and little attention on
data.
 There are many high level languages like COBOL, FORTRAN,
PASCAL, C used for conventional programming commonly known as
POP.
 POP basically consists of writing a list of instructions for the computer
to follow, and organizing these instructions into groups known as
functions.

Python
Java Programming
Programming Unit 14 Department of CSE
OOP:
 OOP allows us to decompose a problem into a number of entities
called objects and then builds data and methods around these entities.
OOP Characteristic:
 Emphasis on data.
 Programs are divided into what are known as methods.
 Data structures are designed such that they characterize the objects.
 Methods that operate on the data of an object are tied together.

Python
Java Programming
Programming Unit 14 Department of CSE
 Data is hidden
 Objects can communicate with each other through methods.
 Reusability- Follows bottom-up approach in program design

Python
Java Programming
Programming Unit 14 Department of CSE
Main Principle of OOP

Python
Java Programming
Programming Unit 14 Department of CSE
Java Programming:
 Java is an object-oriented programming language developed by Sun
Microsystems, and it was released in 1995.
 James Gosling initially developed Java in Sun Microsystems (which
was later merged with Oracle Corporation).
 Java is a set of features of C and C++. It has obtained its format from
C, and OOP features from C++.
 Java programs are platform independent which means they can be run
on any operating system with any processor as long as the Java
interpreter is available on that system.

Python
Java Programming
Programming Unit 14 Department of CSE
 Java code that runs on one platform does not need to be recompiled to
run on another platform; it's called write once, run anywhere(WORA).
 Java Virtual Machine (JVM) executes Java code, but it has been
written in platform-specific languages such as C/C++/ASM, etc. JVM
is not written in Java and hence cannot be platform independent, and
Java interpreter is a part of JVM.

Python
Java Programming
Programming Unit 14 Department of CSE
Mobile -
 In addition to the above technology, Java is widely used in mobile
devices nowadays, many types of games and applications are being
made in Java.
Types of Java Applications
 Web Application - Java is used to create server-side web applications.
Currently, Servlet, JSP, Struts etc. technologies are used.
 Standalone Application - It is also known as the desktop application or
window-based application.
 Enterprise Application - An application that is distributed in nature,
such as banking applications, etc.
 Mobile Application - Java is used to create application software for
mobile devices.

Python
Java Programming
Programming Unit 14 Department of CSE
 Java is one of the most important programming languages in today's
IT industries.
 JSP - In Java, JSP (Java Server Pages) is used to create dynamic web
pages, such as in PHP and ASP.
 Applets - Applets are another type of Java programs that are
implemented on Internet browsers and are always run as part of a web
document.
 J2EE - Java 2 Enterprise Edition is a platform-independent
environment that is a set of different protocols and APIs and is used by
various organizations to transfer data between each other.
JavaBeans - This is a set of reusable software components that can be
easily used to create new and advanced applications.

Python
Java Programming
Programming Unit 14 Department of CSE
Java Buzzwords/Java Features:

Python
Java Programming
Programming Unit 14 Department of CSE
Java Data Types
 Java programming language has a rich set of data types. The data type
is a category of data stored in variables. In java, data types are
classified into two types and they are as follows.
 Primitive Data Types
 Non-primitive Data Types
 A data type defines the type or/and behavior of a data, it tells to the
compiler about the type of data which is going to be stored and the
compiler reserves the fixed number of bytes for that particular
variable/constant.

Python
Java Programming
Programming Unit 14 Department of CSE
 Thus, we can say that, a data type defines two things:
 Type of data
 Memory blocks to be reserved for the data
 There are mainly two data types in Java
1. Primitive data types
2. Non-primitive data types

Python
Java Programming
Programming Unit 14 Department of CSE
Python
Java Programming
Programming Unit 14 Department of CSE
Java Primitive Data Types:

Python
Java Programming
Programming Unit 14 Department of CSE
Java Comments:
 Comments are not a part of the compiled program. They can be used
to explain Java code, and to make it more readable. It can also be
used to prevent execution when testing alternative code.
1. Single-line Comments: It starts with two forward slashes (//).
Any text between // and the end of the line is ignored by Java (will not be
executed).
2. Java Multi-line Comments: It starts with /* and ends with */.
Any text between /* and */ will be ignored by Java.

Python
Java Programming
Programming Unit 14 Department of CSE
Understanding First Java Program:
 Let's see what is the meaning of class, public, static, void, main,
String[], System.out.println().
 class keyword is used to declare a class in java.
 public keyword is an access modifier which represents visibility, it
means it is visible to all.
 static is a keyword, if we declare any method as static, it is known as
static method. The core advantage of static method is that there is no
need to create object to invoke the static method.

Python
Java Programming
Programming Unit 14 Department of CSE
 The main method is executed by the JVM, so it doesn't require to
create object to invoke the main method. So, it saves memory.
 void is the return type of the method; it means it doesn't return any
value. Main represents startup of the program.
 String[] args is used for command line argument. We will learn it later.
 System.out.println() is used print statement. We will learn about the
internal working of System.out.println statement later.

Python
Java Programming
Programming Unit 14 Department of CSE
How many ways can we write a java program
 There are many ways to write a java program. The modifications that
can be done in a java program are given below:
1) By changing sequence of the modifiers, method prototype is not
changed.
Let's see the simple code of main method.
static public void main(String args[])
2) subscript notation in java array can be used after type, before variable
or after variable.

Python
Java Programming
Programming Unit 14 Department of CSE
Let's see the different codes to write the main method.
public static void main(String[] args)
public static void main(String []args)
public static void main(String args[])
3) You can provide var-args support to main method by passing 3 ellipses
(dots)
Let's see the simple code of using var-args in main method.
1. public static void main(String... args)

Python
Java Programming
Programming Unit 14 Department of CSE
4) Having semicolon at the end of class in java is optional.
Let's see the simple code.
class A{
static public void main(String... args){
System.out.println("hello java4");
}
}; Your First Program
class HelloWorld {
public static void main(String[] args) {
String s= ("Hello, World!");
System.out.println(s);
}
}
Python
Java Programming
Programming Unit 14 Department of CSE
Java Types of Variables and its Scope
A variable is a named memory location used to store a data value. A
variable can be defined as a container that holds a data value.
In java, we use the following syntax to create variables
In java programming language variables are classified as follows.
Types of variables
 Local variables
 Instance variables or Member variables or Global variables
 Static variables or Class variables
 Final variables

Python
Java Programming
Programming Unit 14 Department of CSE
Local variables
 The variables declared inside a method or a block are known as local
variables. A local variable is visible within the method in which it is
declared.
 The local variable is created when execution control enters into the
method or block and destroyed after the method or block execution
completed.
Instance variables or Member variables or Global variables
 The variables declared inside a class and outside any method,
constructor or block are known as member variables. These variables
are visible to all the methods of the class. The changes made to these
variables by method affects all the methods in the class.

Python
Java Programming
Programming Unit 14 Department of CSE
 These variables are created separate copy for every object of that
class.
Static variables or Class variables
 A static variable is a variable that declared using static keyword.
 The instance variables can be static variables but local variables can
not. Static variables are initialized only once, at the start of the
program execution.
 The static variable only has one copy per class irrespective of how
many objects we create.
 The static variable is access by using class name.

Python
Java Programming
Programming Unit 14 Department of CSE
Example to understand the types of variables in java
public class A
{
static int m=100;//static variable
int data=50;//instance variable
public static void main(String args[])
{
int n=10;//local variable
}
}//end of class

Python
Java Programming
Programming Unit 14 Department of CSE
Final variables
 A final variable is a variable that declared using final keyword.
 The final variable is initialized only once, and does not allow any
method to change it's value again.
 The variable created using final keyword acts as constant.
 All variables like local, instance, and static variables can be final
variables.

Python
Java Programming
Programming Unit 14 Department of CSE
Java Constants:

Python
Java Programming
Programming Unit 14 Department of CSE
Examples of constants :
public static final String str = “abc”;
public static final float num = 1231.12f;
public static final char c = ‘A’;
Operators in Java
 Operator in Java is a symbol that is used to perform operations. For
example: +, -, *, / etc.
There are many types of operators in Java which are given below:
• Unary Operator •Relational Operator
• Arithmetic Operator •Bitwise Operator
• Shift Operator •Logical Operator
•Ternary Operator and
•Assignment Operator

Python
Java Programming
Programming Unit 14 Department of CSE
Python
Java Programming
Programming Unit 14 Department of CSE
Type Casting /Type conversion
In Java, type casting is a method or process that converts a data type
into another data type in both ways manually and automatically.
The automatic conversion is done by the compiler and manual
conversion performed by the programmer.
Widening Type Casting
 Converting a lower data type into a higher one is called widening type
casting. It is also known as implicit conversion or casting down. It is
done automatically. It is safe because there is no chance to lose data.
It takes place when:
 Both data types must be compatible with each other.
 The target type must be larger than the source type.

Python
Java Programming
Programming Unit 14 Department of CSE
byte -> short -> char -> int -> long -> float -> double
 The conversion between numeric data type to char or Boolean is not
done automatically. Also, the char and Boolean data types are not
compatible with each other
Widening Type Casting Example
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
long y = x;

Python
Java Programming
Programming Unit 14 Department of CSE
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}
OUTPUT
Before conversion, int value 7
After conversion, long value 7
After conversion, float value 7.0

Python
Java Programming
Programming Unit 14 Department of CSE
Narrowing Type Casting
 Converting a higher data type into a lower one is called narrowing
type casting. It is also known as explicit conversion or casting up. It is
done manually by the programmer. If we do not perform casting then
the compiler reports a compile-time error.
double -> float -> long -> int -> char -> short -> byte

Python
Java Programming
Programming Unit 14 Department of CSE
Narrowing Type Casting
public class NarrowingTypeCastingExample
{
public static void main(String args[])
{
double d = 166.66;
//converting double data type into long data type
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
System.out.println("Before conversion: "+d);
//fractional part lost

Python
Java Programming
Programming Unit 14 Department of CSE
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("After conversion into int type: "+i);
}
}
OUTPUT
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166

Python
Java Programming
Programming Unit 14 Department of CSE
Enumerated:
 The Enum in Java is a data type which contains a fixed set of
constants.
 To create an enum, use the enum keyword . and separate the
constants with a comma. Note that they should be in uppercase
letters.
 Enums are often used in switch statements to check for
corresponding values:
Example:
days – {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
and SATURDAY}
directions – {NORTH, SOUTH, EAST, and WEST)
season- {SPRING, SUMMER, WINTER, and AUTUMN or FALL}
colors – {RED, YELLOW, BLUE, GREEN, WHITE, and BLACK}

Python
Java Programming
Programming Unit 14 Department of CSE
public class Main
{
enum Level { LOW, MEDIUM, HIGH }

public static void main(String[] args)


{
Level myVar = Level.MEDIUM;
System.out.println(myVar);
System.out.println(Level.valueOf(“HIGH"));
}
}

Python
Java Programming
Programming Unit 14 Department of CSE
class EnumExample1
{ //defining the enum inside the class
public enum Season { WINTER, SPRING, SUMMER, FALL }
//main method
public static void main(String[] args)
{ //traversing the enum
for (Season s : Season.values())
{
System.out.println(s);
}
}
}

Python
Java Programming
Programming Unit 14 Department of CSE
Java Control Statements:
 In java, the default execution flow of a program is a sequential order.
But the sequential order of execution flow may not be suitable for all
situations.
 Sometimes, we may want to jump from line to another line, we may
want to skip a part of the program, or sometimes we may want to
execute a part of the program again and again.
 To solve this problem, java provides control statements.

Python
Java Programming
Programming Unit 14 Department of CSE
Selection Control Statements:
 In java, the selection statements are also known as decision making
statements or branching statements.
The selection statements are used to select a part of the program to be
executed based on a condition.
Java provides the following selection statements.
if statement
if-else statement
if-elseif statement
nested if statement
switch statement

Python
Java Programming
Programming Unit 14 Department of CSE
Simple if statement:
 It is the most basic statement among all control flow statements in
Java. It evaluates a Boolean expression and enables the program to
enter a block of code if the expression evaluates to true.
if (condition)
public class IfExample {
{
public static void main(String[] args)
statement 1;
{
}
int age=20;
if(age>18)
{
System.out.print("Age is greater than 18");
}
}
}
Python
Java Programming
Programming Unit 14 Department of CSE
if-else statement
 The if-else statement is an extension to the if-statement, which uses
another block of code, i.e., else block. The else block is executed if the
condition of the if-block is evaluated as false.
if(condition)
{
statement 1; //executes when condition is true
}
else
{
statement 2; //executes when condition is false
}

Python
Java Programming
Programming Unit 14 Department of CSE
public class IfElseExample
{
public static void main(String[] args)
{
int number=13;
if(number%2==0)
{
System.out.println("even number");
}
else{
System.out.println("odd number");
}
}
}

Python
Java Programming
Programming Unit 14 Department of CSE
if-else-if
 The if-else-if statement contains the if-statement followed by multiple
else-if statements. In other words, we can say that it is the chain of if-
else statements that create a decision tree where the program may
enter in the block of code where the condition is true

Python
Java Programming
Programming Unit 14 Department of CSE
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 2; //executes when all the conditions are false
}

Python
Java Programming
Programming Unit 14 Department of CSE
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;
else if(marks>=70 && marks<80){
if(marks<50){ System.out.println("B grade");
System.out.println("fail"); }
} else if(marks>=80 && marks<90){
else if(marks>=50 && marks<60){ System.out.println("A grade");
System.out.println("D grade"); }else if(marks>=90 && marks<100){
} System.out.println("A+ grade");
else if(marks>=60 && marks<70){ }else{
System.out.println("C grade"); System.out.println("Invalid!");
} }
}
}
Python
Java Programming
Programming Unit 14 Department of CSE
Nested if-statement
 In nested if-statements, the if statement can contain a if or if-else
statement inside another if or else-if statement.
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}

Python
Java Programming
Programming Unit 14 Department of CSE
public class JavaNestedIfExample2 {
public static void main(String[] args) {
int age=25;
int weight=48;
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
} else{
System.out.println("You are not eligible to donate blood");
}
} else{
System.out.println("Age must be greater than 18"); } } }

Python
Java Programming
Programming Unit 14 Department of CSE
Switch Statement
 In Java, Switch statements are similar to if-else-if statements. The
switch statement contains multiple blocks of code called cases and a
single case is executed based on the variable which is being switched.
The switch statement is easier to use instead of if-else-if statements.
It also enhances the readability of the program. The case variables
can be int, short, byte, char, or enumeration.
 String type is also supported since version 7 of Java
 Cases cannot be duplicate
 Default statement is executed when any of the case doesn't match
the value of expression. It is optional.

Python
Java Programming
Programming Unit 14 Department of CSE
Switch Statement
switch (expression){
case value1:
statement1;
break;
.
.
case valueN:
statementN;
break;
default:
default statement;
}

Python
Java Programming
Programming Unit 14 Department of CSE
public class SwitchExample {
public static void main(String[] args) {
int number=20;
switch(number)
{
case 10:
System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
default:System.out.println("Not in 10, 20 or 30"); } } }

Python
Java Programming
Programming Unit 14 Department of CSE
Iterative Control Statements
In java, the iterative statements are also known as looping statements or
repetitive statements.
 The iterative statements are used to execute a part of the program
repeatedly as long as the given condition is True.
 Using iterative statements reduces the size of the code, reduces the
code complexity, makes it more efficient, and increases the execution
speed.
 Java provides the following iterative statements.
 for statement
 while statement
 do-while statement

Python
Java Programming
Programming Unit 14 Department of CSE
Java for loop
 In Java, for loop is similar to C and C++. It enables us to initialize the
loop variable, check the condition, and increment/decrement in a
single line of code. We use the for loop only when we exactly know
the number of times, we want to execute the block of code.
for(initialization, condition, increment/decrement)
{
//block of statements
}

Python
Java Programming
Programming Unit 14 Department of CSE
public class Calculation
{
public static void main(String[] args)
{
for(int j = 1; j<=10; j++)
{
System.out.println(j);
}
}
}

Python
Java Programming
Programming Unit 14 Department of CSE
Java Nested for Loop
If we have a for loop inside the another loop, it is known as nested for
loop. The inner loop executes completely whenever outer loop executes.
public class NestedForExample {
public static void main(String[] args)
{
//loop of i
for(int i=1;i<=3;i++){
//loop of j
for(int j=1;j<=3;j++){
System.out.println(i+" "+j);
}
}
}
}
Python
Java Programming
Programming Unit 14 Department of CSE
Java for-each loop
 Java provides an enhanced for loop to traverse the data structures like
array or collection. In the for-each loop, we don't need to update the
loop variable.
for(data_type var : array_name/collection_name)
{
//statements public class Calculation {
public static void main(String[] args) {
}
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) { Output
System.out.println(name); Printing the content of the array names:
Java
} C
} C++
} Python
JavaScript
Python
Java Programming
Programming Unit 14 Department of CSE
Java while loop
 The while loop is also used to iterate over the number of statements
multiple times. However, if we don't know the number of iterations in
advance, it is recommended to use a while loop. Unlike for loop, the
initialization and increment/decrement doesn't take place inside the
loop statement in while loop.
 It is also known as the entry-controlled loop since the condition is
checked at the start of the loop. If the condition is true, then the loop
body will be executed; otherwise, the statements after the loop will
be executed.

Python
Java Programming
Programming Unit 14 Department of CSE
while(condition){
//looping statements
}
Example
public class Calculation {
public static void main(String[] args) {
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
}
}
}

Python
Java Programming
Programming Unit 14 Department of CSE
Java do-while loop
 The do-while loop checks the condition at the end of the loop after
executing the loop statements. When the number of iteration is not
known and we have to execute the loop at least once, we can use do-
while loop.
 It is also known as the exit-controlled loop since the condition is not
checked in advance.
do
{
//statements
} while (condition);

Python
Java Programming
Programming Unit 14 Department of CSE
public class Calculation {
public static void main(String[] args) {
int i = 1;
System.out.println("Printing the list of first 10 odd numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}

Python
Java Programming
Programming Unit 14 Department of CSE
Jump Statements
 Jump statements are used to transfer the control of the program to
the specific statements. In other words, jump statements transfer the
execution control to the other part of the program. There are two
types of jump statements in Java, i.e., break and continue.
Java break statement
 As the name suggests, the break statement is used to break the
current flow of the program and transfer the control to the next
statement outside a loop or switch statement.
 The break statement cannot be used independently in the Java
program, i.e., it can only be written inside the loop or switch
statement.

Python
Java Programming
Programming Unit 14 Department of CSE
public class BreakExample
{
public static void main(String[] args)
{
for(int i = 0; i<= 10; i++)
{
System.out.println(i);
if(i==6)
{
break;
}
}
}
}

Python
Java Programming
Programming Unit 14 Department of CSE
Java continue statement
The continue statement breaks one iteration(in the loop),if a specified condition occurs, continuous
with the next iteration in the loop.

public class ContinueExample


{
public static void main(String[] args)
{
for(int i = 0; i<= 10; i++)
{
if(i==6)
{
continue;
}
System.out.println(i);
}
}
}
Python
Java Programming
Programming Unit 14 Department of CSE
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 documentation.
 we will use the nextLine() method, which is used to read Strings:

Python
Java Programming
Programming Unit 14 Department of CSE
Input Types

Python
Java Programming
Programming Unit 14 Department of CSE
import java.util.Scanner;
class main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
String username;
System.out.println(“Enter User Name”);
username=obj.nextLine();
System.out.println(“User Name Is:” +username);
} OUT PUT
} Enter User Name
hari

User Name is: hari


Python
Java Programming
Programming Unit 14 Department of CSE
Python
Java Programming
Programming Unit 14 Department of CSE
Java Arrays
 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. It is a data structure where we store similar
elements. We can store only a fixed set of elements in a Java array.
 Array in Java is index-based, the first element of the array is stored at
the 0th index, 2nd element is stored on 1st index and so on.

Python
Java Programming
Programming Unit 14 Department of CSE
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.

Python
Java Programming
Programming Unit 14 Department of CSE
Example
class Testarray
{
public static void main(String args[]){
int a[]=new int[5];//declaration
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Python
Java Programming
Programming Unit 14 Department of CSE
Declaration and Initialization of Java Array
 We can declare and initialize the java array together by:
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}

Python
Java Programming
Programming Unit 14 Department of CSE
Multidimensional Array in Java
 In such case, data is stored in row and column based index (also
known as matrix form).
int[][] arr=new int[3][3];//3 row and 3 column
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

Python
Java Programming
Programming Unit 14 Department of CSE
Example
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}

Python
Java Programming
Programming Unit 14 Department of CSE
Passing Array to a Method
class Example
public static void main(String[] args)
{ {
public void x(int a[]) int a[]={1,2,3,4,5};
{ Example obj=new Example();
for(int i=0;i<a.length;i++) obj.x(a);
{ }
}
System.out.println(a[i]);
}
}

Python
Java Programming
Programming Unit 14 Department of CSE
ArrayIndexOutOfBoundsException
 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.
//Java Program to demonstrate the case of
//ArrayIndexOutOfBoundsException in a Java Array.
public class TestArrayException{
public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++){
System.out.println(arr[5]);
} } }

Python
Java Programming
Programming Unit 14 Department of CSE
Classes and Objects:
 class, object, and its methods constructors and methods, access
control, this reference, overloading constructors, recursion, exploring
string class, garbage collection.
Class
 Collection of objects is called class. It is a logical entity.
 A class can also be defined as a blueprint from which you can create
an individual object. Class doesn't consume any space.
Object
 Any entity that has state and behavior is known as an object.
 For example, a chair, pen, table, keyboard, bike, etc. It can be physical
or logical.An Object can be defined as an instance of a class. An object
contains an address and takes up some space in memory. Objects can
communicate without knowing the details of each other's data or
code.
Python
Java Programming
Programming Unit 14 Department of CSE
Python
Java Programming
Programming Unit 14 Department of CSE
Constructors in Java
 In Java, a constructor is a block of codes similar to the method. It is
called when an instance of the class is created. At the time of calling
constructor, memory for the object is allocated in the memory.
 It is a special type of method which is used to initialize the object.
 Every time an object is created using the new() keyword, at least one
constructor is called.
 It calls a default constructor if there is no constructor available in the
class. In such case, Java compiler provides a default constructor by
default.
 There are two types of constructors in Java: no-arg constructor, and
parameterized constructor

Python
Java Programming
Programming Unit 14 Department of CSE
Rules for creating Java constructor
 There are two rules defined for the constructor.
 Constructor name must be the same as its class name
 A Constructor must have no explicit return type
 A Java constructor cannot be abstract, static, final.
 We can use access modifiers while declaring a constructor. It controls
the object creation. In other words, we can have private, protected,
public or default constructor in Java.

Python
Java Programming
Programming Unit 14 Department of CSE
Types of Java constructors
 There are two types of constructors in Java:
 Parameterized constructor
 Non-Parameterized Constructor

A constructor is called "Default Constructor" when it doesn't have any


parameter.
Syntax of default constructor:
<class_name>(){}

Python
Java Programming
Programming Unit 14 Department of CSE
//Java Program to create and call a default constructor
class Bike1
{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}

Python
Java Programming
Programming Unit 14 Department of CSE
Java Parameterized 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.

Python
Java Programming
Programming Unit 14 Department of CSE
class Student4
public static void main(String args[]){
{
Student4 s1 = new
int id;
Student4(111,"Karan");
String name;
Student4 s2 = new
Student4(int i,String n)
Student4(222,"Aryan");
{
s1.display();
id = i;
s2.display();
name = n;
}
}
}
void display()
{
System.out.println(id+" "+name);
}

Python
Java Programming
Programming Unit 14 Department of CSE
Constructor Overloading in Java
 In Java, a constructor is just like a method but without return type. It
can also be overloaded like Java methods.
 Constructor overloading in Java is a technique of having more than
one constructor with different parameter lists. They are arranged in a
way that each constructor performs a different task.

Python
Java Programming
Programming Unit 14 Department of CSE
class Student5{
int id;
String name; void display(){System.out.println(id+"
int age; "+name+" "+age);
Student5(int i,String n){ }
id = i; public static void main(String args[])
name = n; {
} Student5 s1 = new
Student5(int i,String n,int a){ Student5(111,"Karan");
id = i; Student5 s2 = new
name = n; Student5(222,"Aryan",25);
age=a; s1.display();
} s2.display();
}
}
Python
Java Programming
Programming Unit 14 Department of CSE
Method in Java
 A method is a block of code or collection of statements to perform a
certain task or operation. It is used to achieve the reusability of code.
We write a method once and use it many times
Method Declaration
 The method declaration provides information about method
attributes, such as visibility, return-type, name, and arguments. It has
six components that are known as method header
Method Signature:
 Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.

Python
Java Programming
Programming Unit 14 Department of CSE
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. Suppose, if
we are creating a method for subtraction of two numbers, the
method name must be subtraction(). A method is invoked by its
name.
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. If
the method has no parameter, left the parentheses blank.
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.

Python
Java Programming
Programming Unit 14 Department of CSE
Types of Method
 There are two types of methods in Java:
 Predefined Method
 User-defined Method
Predefined Method
 In Java, predefined methods are the method that is already defined in
the Java class libraries is known as predefined methods. It is also
known as the standard library method or built-in method. We can
directly use these methods just by calling them in the program at any
point. Some pre-defined methods are length(), equals(), compareTo(),
sqrt().

Python
Java Programming
Programming Unit 14 Department of CSE
import java.lang.Math;
public class math
{
public static void main(String[] args)
{

System.out.print("The maximum number is: " + Math.max(9,7));


System.out.println(“Square root of a no is:” +Math.sqrt(9));
}
}
User-defined Method
 The method written by the user or programmer is known as a user-
defined method. These methods are modified according to the
requirement.

Python
Java Programming
Programming Unit 14 Department of CSE
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[]) { public static void findEvenOdd(int num)
Scanner scan=new Scanner(System.in); {
System.out.print("Enter the number: "); if(num%2==0)
int num=scan.nextInt(); System.out.println(num+" is even");
findEvenOdd(num); else
} System.out.println(num+" is odd");
}
}

Python
Java Programming
Programming Unit 14 Department of CSE
public class Addition
{
public static void main(String[] args) public static int add(int n1, int n2)
{ {
int a = 19; int s;
int b = 5; s=n1+n2;
int c = add(a, b); return s; //returning the sum
System.out.println("The sum of a and b is= " + c);
}
}
}

Python
Java Programming
Programming Unit 14 Department of CSE
Method Overloading
 If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
 If we have to perform only one operation, having same name of the
methods increases the readability of the program.
 Method overloading increases the readability of the program.
 Different ways to overload the method
 There are two ways to overload the method in java
By changing number of arguments
By changing the data type

Python
Java Programming
Programming Unit 14 Department of CSE
Method Overloading: changing no. of arguments
class TestOverloading1
{
public static void main(String[] args)
{ System.out.println(TestOverloading1
static int add(int a,int b) .add(11,11));
{ System.out.println(TestOverloading1
return a+b; .add(11,11,11);
} }
static int add(int a,int b,int c) }
{
return a+b+c;
}

Python
Java Programming
Programming Unit 14 Department of CSE
Method Overloading: changing data type of arguments
class Adder{
static int add(int a, int b) class TestOverloading2
{ {
return a+b; public static void main(String[] args){
} System.out.println(Adder.add(11,11));
static double add(double a, double b) System.out.println(Adder.add(12.3,12.6);
{
return a+b; }
} }
}

Python
Java Programming
Programming Unit 14 Department of CSE
Can we overload java main() method?
 Yes, by method overloading. You can have any number of main
methods in a class by method overloading. But JVM calls main()
method which receives string array as arguments only. Let's see the
simple example:
class TestOverloading4{
public static void main(String[] args){System.out.println("main with
String[]");}
public static void main(String args){System.out.println("main with
String");}
public static void main(){System.out.println("main without args");}
}

Python
Java Programming
Programming Unit 14 Department of CSE
 Difference between constructor and method in Java
 There are many differences between constructors and methods. They
are given below.

Python
Java Programming
Programming Unit 14 Department of CSE
This key word
 It is common for a class to contain instance variables and methods.
 It is also common for methods to have parameters.
 So, what happens when the names of instance variables and the
parameters are same?
class Box
{
int length, width, height;
void setDim(int length, int width, int
height)
{
length = length;
width = width;
height = height;
} }
Python
Java Programming
Programming Unit 14 Department of CSE
1) To change the names of parameters.
2) Using “this” keyword.
•The “this” keyword always refers to the current object.
•“this” can be used to resolve the naming conflicts between instance
variables and parameters. class Box
{
int length, width, height;
void setDim(int length, int width, int
height)
{
this.length = length;
this.width = width;
this.height = height;
}
}
Python
Java Programming
Programming Unit 14 Department of CSE
Recursion in Java
 Recursion in java is a process in which a method calls itself
continuously.
 A method in java that calls itself is called recursive method.
public class Recursion{
static int count=0;
static void p(){
count++;
if(count<=5){
System.out.println("hello "+count);
p();
}
}
public static void main(String[] args) {
p(); } }
Python
Java Programming
Programming Unit 14 Department of CSE
public class Main {
public static void main(String[] args) 10 + sum(9)
{ 10 + ( 9 + sum(8) )
int result = sum(10); 10 + ( 9 + ( 8 + sum(7) ) )
System.out.println(result); ...
} 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 +
public static int sum(int k) { sum(0)
if (k > 0) { 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
return k + sum(k - 1);
} else {
return 0;
}
}
}

Python
Java Programming
Programming Unit 14 Department of CSE
Java Command Line Arguments
 The java command-line argument is an argument i.e. passed at the
time of running the java program.
 The arguments passed from the console can be received in the java
program and it can be used as an input.
 So, it provides a convenient way to check the behavior of the program
for the different values. You can pass N (1,2,3 and so on) numbers of
arguments from the command prompt.
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}

Python
Java Programming
Programming Unit 14 Department of CSE
class A{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}

compile by > javac A.java


run by > java A sonoo jaiswal 1 3 abc

Python
Java Programming
Programming Unit 14 Department of CSE
Exploring Methods of String Class
 String is a sequence of characters. In java, objects of String are
immutable which means a constant and cannot be changed once
created.
 String class has a variety of methods for string manipulation.
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";

Python
Java Programming
Programming Unit 14 Department of CSE
String Handling
 String is probably the most commonly used class in Java's class
library. The obvious reason for this is that strings are a very
important part of programming.
 The first thing to understand about strings is that every string you
create is actually an object of type String. Even string constants are
actually
 String objects.

Python
Java Programming
Programming Unit 14 Department of CSE
How to create a string object?
 There are two ways to create String object:
By string literal
By new keyword
1) String Literal
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

Python
Java Programming
Programming Unit 14 Department of CSE
2) By new keyword
 String s=new String("Welcome");//creates two objects and one
reference variable
 In such case, JVM will create a new string object in normal (non-pool)
heap memory, and the literal "Welcome" will be placed in the string
constant pool. public class StringExample{
public static void main(String args[]){
String s1="java";
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);
String s3=new String("example");
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Python
Java Programming
Programming Unit 14 Department of CSE
 The String class contains several methods that you can use. Here are
a few.
 Test two strings for equality by using equals( ).
 You can obtain the length of a string by calling the length( ) method.
 You can obtain the character at a specified index within a string by
calling charAt( ).
 To compare two strings for equality, use equals( ) and to perform a
comparison that ignores case differences, call equalsIgnoreCase( )

Python
Java Programming
Programming Unit 14 Department of CSE
 compareTo( )- it is not enough to simply know whether two strings
are identical. For sorting applications, you need to know which is less
than, equal to, or greater than the next. A string is less than another if
it comes before the other in dictionary order. A string is greater than
another if it comes after the other in dictionary order
 indexOf( ) Searches for the first occurrence of a character or
substring.
 lastIndexOf( ) Searches for the last occurrence of a character or
substring.
 we can extract a substring using substring( ).

Python
Java Programming
Programming Unit 14 Department of CSE
 concat( ) performs the same function as +.
 replace( ): The replace( ) method has two forms.
1) The first replaces all occurrences of one character in the invoking
string with another character. It has the following general form:
String replace(char original, char replacement)
Ex: String s = "Hello".replace('l', 'w');
2) The second form of replace( ) replaces one character sequence with
another. It has this general form:

Python
Java Programming
Programming Unit 14 Department of CSE
 String replace(CharSequence original, CharSequence replacement)
• trim( ): The trim( ) method returns a copy of the invoking string from
which any leading and trailing whitespace has been removed. It has
this general form:
String trim( )
Ex: String s = " Hello World ".trim();

• The startsWith( ) method determines whether a given String begins


with a specified string. Conversely, endsWith( ) determines whether
the String in question ends with a specified string.
boolean startsWith(String str)
boolean endsWith(String str)

Python
Java Programming
Programming Unit 14 Department of CSE
 WAP to design a String class that performs String methods (Equal,
Reverse the string, and change the case etc).

package project1;
public class StringDemo
{
public static void main(String[] args)
{
String str = "This is some sample String with some words that
have been repeated some times";
System.out.println("Total no. of characters : " + str.length());

Python
Java Programming
Programming Unit 14 Department of CSE
System.out.println("To Upper Case : " + str.toUpperCase());
System.out.println("To Lower Case : " + str.toLowerCase());
System.out.println("Original String : " + str);
System.out.println(str.substring(8));
System.out.println(str.substring(8,19));
System.out.println(str.indexOf("some"));
String s = " " + str + " ";
System.out.println(s);
System.out.println("[" + s.trim() + "]");
System.out.println(str.replace("s","$$##"));
String sh = "parth is a good boy";
System.out.println(sh + " -> " + new StringBuffer(sh).reverse());
}
}

Python
Java Programming
Programming Unit 14 Department of CSE
Access Modifiers in Java
 The access modifiers in Java specifies the accessibility or scope of a
field, method, constructor, or class. We can change the access level of
fields, constructors, methods, and class by applying the access
modifier on it.
 There are four types of Java access modifiers:
Private:
 The access level of a private modifier is only within the class. It cannot
be accessed from outside the class.
Default:
 The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify
any access level, it will be the default.

Python
Java Programming
Programming Unit 14 Department of CSE
Protected:
 The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child
class, it cannot be accessed from outside the package.
Public:
 The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and
outside the package.

Python
Java Programming
Programming Unit 14 Department of CSE
Understanding Java Access Modifiers

Python
Java Programming
Programming Unit 14 Department of CSE
Private
class A{
private int data=40;
private void msg()
{
System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}

Python
Java Programming
Programming Unit 14 Department of CSE
Default
 If you don't use any modifier, it is treated as default by default. The
default modifier is accessible only within package. It cannot be
accessed from outside the package. It provides more accessibility
than private. But, it is more restrictive than protected, and public.
//save by A.java
//save by B.java
package pack;
package mypack;
class A{
import pack.*;
void msg()
class B{
{
public static void main(String args[]){
System.out.println("Hello");}
A obj = new A();//Compile Time Error
}
obj.msg();//Compile Time Error
}
}
Python
Java Programming
Programming Unit 14 Department of CSE
Protected
 The protected access modifier is accessible within package and
outside the package but through inheritance only.
 The protected access modifier can be applied on the data member,
method and constructor. It can't be applied on the class.
//save by A.java
package pack;
public class A{
protected void msg()
{
System.out.println("Hello");
}
}

Python
Java Programming
Programming Unit 14 Department of CSE
//save by B.java
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
 The A class of pack package is public, so can be accessed from outside
the package. But msg method of this package is declared as
protected, so it can be accessed from outside the class only through
inheritance.

Python
Java Programming
Programming Unit 14 Department of CSE
Public
 The public access modifier is accessible everywhere. It has the widest
scope among all other modifiers.
//save by B.java
//save by A.java
package mypack;
package pack; import pack.*;
public class A{
public void msg() class B{
public static void main(String args[]){
{System.out.println("Hello");}
A obj = new A();
} obj.msg();
}
}

Python
Java Programming
Programming Unit 14 Department of CSE
Garbage Collection
 Objects are dynamically allocated by using the new operator, such
objects are destroyed automatically and their memory is released for
later reallocation in java. This techniques is called garbage collection.
 C uses free() to release allocated memory.
 C++, dynamically allocated objects must be manually released by use
of a delete operator.
 But java takes a different approach, it handles deallocation
automatically.
 It works like this: when no references to an object exist, that object is
assumed to be no longer needed, and the memory occupied by the
object can be reclaimed.
1. By default garbage collection method
2. Finalize() method -> it contains actions that must be performed before
an object is destroyed
Python
Java Programming
Programming Unit 14 Department of CSE
 Finalize() is the method of Object class. This method is called
just before an object is garbage collected. finalize() method
overrides to dispose system resources, perform clean-up
activities and minimize memory leaks.

Syntax:
protected void finalize()
{
//finalization code
}

Python
Java Programming
Programming Unit 14 Department of CSE
Example:
package sec4java;
//override
public class JavafinalizeExample1 protected void finalize()
{ {
public static void main(String args[]) System.out.println("finalize method called");
{ }
JavafinalizeExample1 obj=new JavafinalizeExample1();
//obj=null; }
System.gc();
System.out.println("end of garbage collection");
}
Output:
end of garbage collection
finalize method called

Python
Java Programming
Programming Unit 14 Department of CSE
Thank You

Java Programming
Python Programming Unit 1
4 Department of CSE

You might also like