0% found this document useful (0 votes)
9 views

Java+Programming+ +UNIT I+Part+B

Uploaded by

2311cs050086
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Java+Programming+ +UNIT I+Part+B

Uploaded by

2311cs050086
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 50

JAVA PROGRAMMING

(MR23-1CS0105)

UNIT-I
OOP’s CONCEPTS

Java Programming
Python Programming Unit 1
4 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