0% found this document useful (0 votes)
12 views49 pages

BCA III YR - JAVA (Part 2)

Uploaded by

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

BCA III YR - JAVA (Part 2)

Uploaded by

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

MAHILA PG MAHAVIDYALAY,

JODHPUR

BCA 301: JAVA


PROGRAMMING LANGUAGE

By: Dr Shweta Purohit

Dr. Shweta Purohit,MTMC Jodhpur 1


Constructor
• Constructors are methods defined inside a class
which have the same name as the class, and
which are used to create an instance of a class.
• This can also be called creating an object,
• As in:
Car c = new Car();
Constructors are also used for the initialization of
objects. Constructors are identified by the two
following rules:
– The method name must exactly match the class name
– There must not be a return type declared for the
method.

Dr. Shweta Purohit,MTMC Jodhpur 2


• A Constructor with return type will be treated as a
different method, and will not be called implicitly.
• Every class has at least one constructor.
• If you do not write any Constructor for your class,
Java provides a Constructor with no arguments, and
an empty body.
• This default Constructor allows you to create an
object with the new operator by using the syntax:
new ABC();
• A parameterized constructor is when it accepts a
specific number of parameters to initialize data
members of a class with distinct values.

Dr. Shweta Purohit,MTMC Jodhpur 3


Example-
Class ConstructorTest
{
String str;
public ConstructorTest (String str)
{
this.str = str;
System.out.printIn(str);
}
}
class TestingConstructor
{
public static void main(String argv[ ])
{
new ConstructorTest(“Jack”);
new ConstructorTest(“Scott”);
new ConstructorTest(“Ted”);
}
}

Dr. Shweta Purohit,MTMC Jodhpur 4


Access Modifier
• These are used for setting the access level to classes,
variables, methods, and constructors.
• There are four access modifiers:
public, private, protected and default (no keyword)
• Default: we don't use any keyword explicitly, Java will set a
default access to a given class, method or property. The
default access modifier is also called package-private, which
means that all members are visible within the same package
but aren't accessible from other packages.
• Public: If we add the public keyword to a class, method or
property then we're making it available to the whole world,
i.e. all other classes in all packages will be able to use it. This
is the least restrictive access modifier

Dr. Shweta Purohit,MTMC Jodhpur 5


• Private: Any method, property or constructor with
the private keyword is accessible from the same
class only. This is the most restrictive access
modifier and is core to the concept of
encapsulation. All data will be hidden from the
outside world.
• Protected: Between public and private access
levels, there's the protected access modifier. If we
declare a method, property or constructor with the
protected keyword, we can access the member
from the same package (as with package-private
access level) and in addition from all subclasses of
its class, even if they lie in other packages

Dr. Shweta Purohit,MTMC Jodhpur 6


Dr. Shweta Purohit,MTMC Jodhpur 7
Static Members & Methods
• Static keyword can be used with instance variables, constants,
and methods.
• static means that the variable, constant, or method belongs to
the class.
• It is not necessary to instantiate an object to access a static
variable, constant or method.
• Static variables are initialized only once, at the start of the
execution.
• It is a variable which belongs to the class and not to
object(instance)
• Static variables are initialized only once, at the start of the
execution. These variables will be initialized first, before the
initialization of any instance variables
• single copy to be shared by all instances of the class
• A static variable can be accessed directly by the class name and
doesn’t need any object .
Dr. Shweta Purohit,MTMC Jodhpur 8
• A static method can access only static data. It can
not access non-static data (instance variables).
• A static method can call only other static methods
and can not call a non-static method from it.
• A static method can be accessed directly by the class
name and doesn’t need any object.
• A static method cannot refer to "this" or "super"
keywords in anyway.
• The static keyword is placed right after the
public/private modifier and right before the type of
variables and methods in their declarations.
• Static methods can be public or private.
Dr. Shweta Purohit,MTMC Jodhpur 9
Dr. Shweta Purohit,MTMC Jodhpur 10
class Student
{ private static int count=0; //static variable
Student()
{ count++; //increment static variable }
static void showCount() //static method
{ System.out.println(“Number Of students : “+count); }
}
public class StaticDemo
{
public static void main(String[] args)
{
Student s1=new Student(); Student s2=new Student();
Student.showCount(); //calling static method
Student s3=new Student();
Student s4=new Student();
s4.showCount(); //calling static method
} }
Dr. Shweta Purohit,MTMC Jodhpur 11
//static block demo
• The static block is a class c1{
block of statement static int p; static int q;
inside a Java class static {
p = 100;
that will be q = 200; } }
executed when a class Staticblockdemo {
class is first loaded static int a; static int b;
static {
into the JVM . a = 10;
• A static block helps b = 20; }
public static void main(String args[]) {
to initialize the System.out.println("Value of a = " + a);
static data System.out.println("Value of b = " + b);
members, just like System.out.println("Value of p = " + c1.p);
System.out.println("Value of q = " + c1.q);
constructors help }
to initialize }
instance members
Dr. Shweta Purohit,MTMC Jodhpur 12
Basic Output
• The I/O methods belong to classes in the java.io package.
• Any source or destination for I/O is considered a stream
of bytes.
• There are three objects that can be used for input and
output.
– System.out can be used to write output to the console.
– System.err can be used to write error messages to the
console.
– System.in can be used to handle input from the console.
• The System.out object has two methods –
• The println() method will print a carriage return and line feed after
printing so that the next output will be printed on a new line.
• The method print() will keep
Dr Shweta theMTMC
Purohit, cursor on the same line after printing.
Jodhpur 13
User Input
Using Scanner Class
• Java uses the Scanner class found
in java.util package to get user input.
• To use the Scanner class, you have to create an
object of the class and use any of the methods to
read string, numbers
Method Description
etc.
int nextInt() It is used to scan the next token of the input as an integer.

float nextFloat() It is used to scan the next token of the input as a float.

double nextDouble() It is used to scan the next token of the input as a double.

byte nextByte() It is used to scan the next token of the input as a byte.

String nextLine() Advances this scanner past the current line.


Dr Shweta Purohit, MTMC Jodhpur 14
• Example:
import java.util.*;
class Input1{
public static void main(String args[]){
System.out.println("Hello Enter your Name:");
Scanner scanner = new Scanner(System.in);

String name = scanner.nextLine();

System.out.println(name + " is a nice name!");


}
}

Dr Shweta Purohit, MTMC Jodhpur 15


Using BufferReader Class
• There is a java.io.BufferedReader class that has a
method readLine() to take input .
• A buffer is a region in memory where input from
the terminal is stored until needed by the program.
• If we want to perform buffered input on the
System.in stream we would pass the System.in
object into the constructor.
Method Description
int read() It is used for reading a single character.
String readLine() It is used for reading a line of text.
It repositions the stream at a position where the mark method was last
void reset()
called on this input stream.
It closes the input stream and releases any system resources associated
void close()
with it.
Dr Shweta Purohit, MTMC Jodhpur 16
• Example:
import java.util.*;
import java.io.*;
public class Input2 {

public static void main(String[] args) throws IOException{


System.out.print ( "Enter the radius:" );

BufferedReader input = new BufferedReader ( new InputStreamReader ( System.in ) );

String inputString = input.readLine();

double radius = Double.parseDouble ( inputString );

double area = 3.14159 * radius * radius;

System.out.println ( "Area is: " + area );


}

} Dr Shweta Purohit, MTMC Jodhpur 17


Difference between Scanner Class and BufferReader Class

Scanner Class BufferReader Class

BufferReader is synchronous in nature. In a


Scanner is not is synchronous in nature and should be
multithreading environment, BufferReader should be
used only in a single-threaded case.
used.

It can be imported using java.util packages. It can be imported using java.io packages.

BufferReader has a large buffer of 8 KB bytes as compared


The scanner has a small buffer of 1 KB char buffer.
to Scanner.

The scanner is a bit slower as it needs to parse data as BufferReader is faster than Scanner, as it only reads a
well. character stream.

BufferReader has methods like parseInt(), parseShort(),


Scanner has methods like nextInt(), nextShort(), etc.
etc.

The scanner has the method nextLine() to read a line. BufferReader has the method readLine() to read a line.

Dr Shweta Purohit, MTMC Jodhpur 18


Array
• Array is collection of similar type of data.
• Java uses various approaches to initialize an array, these
are:
– Setting up an array without values: An array can be set up to a
specific size, and each element's default value is 0.
– Array initialization after declaration: An array can also be
created after declaration.
– Giving values to an array's initial state: An array can also be
begun while being created.
– Putting default values in an array's initialization: Java allows
starting an array with default values by using the new keyword
with the array's data type and size enclosed in square brackets.
– Initializing an array using a loop: Java also allows using a loop to
create an array.

Dr Shweta Purohit, MTMC Jodhpur 19


Example: Arrays.fill(num3, 0);
import java.util.*; import java.io.*; //initializing 2d array
public class arrayEx { int[][] num4 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
public static void main(String[] args) throws System.out.println("Accessing Elements of
IOException{ Array:");
// declare an array System.out.println("First Element: " +
double[] ar1; num1[0]);
// allocate memory System.out.println("Second Element: " +
ar1 = new double[10]; num1[1]);
//declare and initialize and array System.out.println("Using for Loop:");
int[] num1= {1, 2, 3, 4, 5}; for(int i = 0; i < num2.length; i++) {
//initialize an array using For loop: System.out.println(num2[i]);
int size = 5; }
int[] num2 = new int[size]; System.out.println("Using for-each Loop:");
for (int i = 0; i < size; i++) { for(int a : num3) {
num2[i] = i + 1; } System.out.println(a);
//initialize using fill() function }
int size1 = 5; }
int[] num3 = new int[size1]; }
Dr Shweta Purohit, MTMC Jodhpur 20
Inheritance
• Create a new class from an existing class.
• The extends keyword is used to perform inheritance in
Java.
class Animal {
// methods and fields }
// use of extends keyword // to perform
inheritance
class Dog extends Animal {
// methods and fields of Animal // methods and
fields of Dog
}
• Inheritance is an is-a relationship between two
classes.
Dr Shweta Purohit, MTMC Jodhpur 21
• Inheritance supports the concept of “reusability”.
• Method overriding is achieved through
inheritance and this supports run time
polymorphism.
• Abstraction can be achieved by inheritance.
• Every class has one and only one direct superclass
(except object class).
• A superclass can have any number of subclasses.
But a subclass can have only one superclass.
• Constructors are not are not inherited by
subclasses, but the constructor of the superclass
can be invoked from the subclass.
• A subclass does not inherit the private members
of its parent class.
Dr Shweta Purohit, MTMC Jodhpur 22
Types of Inheritance

Through Interface

Dr Shweta Purohit, MTMC Jodhpur 23


Interface
• An interface is a fully abstract class. It includes a group of abstract methods
(methods without a body).
• The interface keyword is used to create an interface in Java.
interface Language {
public void getType();
public void getVersion();
}
• We cannot create objects of interfaces.
• To use an interface, other classes must implement it.
• The implements keyword is used to implement an interface.

interface A { // members of A }
interface B { // members of B }

class C implements A, B {
// abstract members of A
// abstract members of B
Dr Shweta } MTMC Jodhpur
Purohit, 24
Abstract Class and Method
• Abstraction is an important concept of object-oriented programming
that allows us to hide unnecessary details and only show the needed
information.
• Abstract classes and methods is to achieve abstraction in Java.
• We cannot create objects of abstract classes.
• Abstract keyword is used to declare an abstract class.
• Syntax-
// create an abstract class
abstract class class_name {
// fields and methods
}
• An abstract class can have both the regular methods and abstract
methods.
• A method that doesn't have its body is known as an abstract method.
We use the same abstract keyword to create abstract methods.
• Example
abstract void method1(); Dr Shweta Purohit, MTMC Jodhpur 25
• If a class contains an abstract method, then the class
should be declared abstract. Otherwise, it will generate
an error.
• As abstract classes cannot be instantiated, we can create
subclasses from it.
• We can then access members of the abstract class using
the object of the subclass.
• An abstract class can have constructors like the regular
class.
• we can access the constructor of an abstract class from
the subclass using the super keyword.
• Abstract classes are used when:
– Want to share some common methods and fields among
multiple classes.
– Declaring non-static and non-final fields in order to modify
the state of the object to which they are bound.
Dr Shweta Purohit, MTMC Jodhpur 26
Abstract Class Interface

Inheritance & Only one abstract class can be inherited by a Multiple interfaces can be
Implementation class. implemented by a class.

It can have final, non-final, static, and non- It can have only static and final
Variable Types
static variables. variables.

It can only contain abstract


It can contain both abstract as well as non-
Method Types methods, but static methods are
abstract methods.
an exception.

The method signatures defined in


An abstract class can have an access the interface are public by
Access Modifiers
modifier. default. An interface doesn’t
have an access modifier.

Constructors & It can’t declare constructors or


It can declare constructors and destructors.
Destructors destructors.

Speed Fast Slow

Dr Shweta Purohit, MTMC Jodhpur 27


Method Overloading
• If a class has multiple methods having same name but different
in parameters, it is known as Method Overloading.
• ava compiler differentiates overloaded methods with their
signatures. The signature of a method is defined by its name
and a list of parameters.
• The return type of method is not part of the method signature.
It does not play any role in resolving methods overloaded.
• Rules for Method Overloading
1. Overloading can take place in the same or in its sub-class.
2. Constructor in Java can be overloaded
3. Overloaded methods must have a different argument list.
4. Overloaded method should always be in part of the same class, with
same name but different parameters.
5. The parameters may differ in their type or number, or in both.
6. They may have the same or different return types.
7. It is also known as compile time polymorphism.
Dr Shweta Purohit, MTMC Jodhpur 28
• Example-
class calculate{
int multiply(int a,int b){
return a*b;
}
double multiply(double a,double b){
return a*b;
}

• Example2-
class calculate{
int multiply(int a,int b){
return a*b;
}
int multiply(int a,int b,int c){
return a*b*c;
}

Dr Shweta Purohit, MTMC Jodhpur 29


Method Overriding
• If the same method is defined in both the superclass and the subclass.
• Then the method of the subclass class overrides the method of the
superclass. This is known as method overriding.
• Both the superclass and the subclass must have the same method
name, the same return type and the same parameter list.
• Rules for Method Overriding:
1. Applies only to inherited methods
2. Object type (NOT reference variable type) determines which overridden
method will be used at runtime
3. Overriding methods must have the same return type
4. Overriding method must not have more restrictive access modifier
5. Abstract methods must be overridden
6. Static and final methods cannot be overridden
7. Constructors cannot be overridden
8. It is also known as Runtime polymorphism.

Dr Shweta Purohit, MTMC Jodhpur 30


class Animal {
public void displayInfo() {
System.out.println("I am an animal.");
}
}

class Dog extends Animal {


@Override
public void displayInfo() {
System.out.println("I am a dog.");
}
}

class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
Dr Shweta Purohit, MTMC Jodhpur 31
• The same method declared in the superclass and its subclasses can have different
access specifiers.
• We can only use those access specifiers in subclasses that provide larger access than
the access specifier of the superclass.
Example-
class Animal {
protected void displayInfo() {
System.out.println("I am an animal.");
}
}
class Dog extends Animal {
public void displayInfo() {
System.out.println("I am a dog.");
}
}
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}

Dr Shweta Purohit, MTMC Jodhpur 32


• When invoking a superclass version of an
overridden method the super keyword is used.
• Method overriding implements both
polymorphism and inheritance for code
scalability.
• Error Handling in Overriding in JAVA:
– When the parent class doesn’t declare an exception, the child
class can declare only unchecked exceptions.
– When the parent class has declared an exception, the child
class can declare the same exception, not any other
exceptions.
– When the parent class has declared an exception, the child
class can declare without exceptions.
Dr Shweta Purohit, MTMC Jodhpur 33
Method Overloading Method Overriding

Overloading in Java is the ability to create Overriding in Java is providing a specific


multiple methods of the same name with implementation in subclass method for a
different implementations. method already exist in the superclass.

In overloading, the methods have the In overriding, the methods have the same
same name but a different number of name and parameters must be the same.
parameters or a different type of
parameters.

Overloading occurs within the class. Overriding occurs within the two classes
that have an inheritance relationship.

Overloading is called compiled time Overriding is called run time


polymorphism. polymorphism.

Dr Shweta Purohit, MTMC Jodhpur 34


Nesting Methods
• When a method in java calls another method in
the same class, it is called Nesting of methods.
class Main
{
method1(){
// statements
}

method2()
{
// statements
// calling method1() from method2()
method1();
}
method3()
{
// statements
// calling of method2() from method3()
method2();
}
}
Dr. Shweta Purohit,MTMC Jodhpur 35
Final Keyword
• The final keyword in java is used to restrict the user
from further modifying the entity to which it is
applied.
• The java final keyword can be used in many context
like
– Variable: A final variable is a constant; once initialized, its
value cannot be changed.
final int VARVALUE = 100;
– Method: A final method cannot be overridden by
subclasses, ensuring that the method's implementation
remains unchanged.
class Parent {
public final void display()
{ System.out.println("This is a final method."); } }
Dr. Shweta Purohit,MTMC Jodhpur 36
• Class: If a class is declared as final, which means it cannot be extended by
any other class.
public final class FinalClass {
public void show()
{
System.out.println("This is a final class.");
}
}
• The Final keyword is a non-access modifier.
• The Final keyword can be primitive and non-primitive data
types.
• The final keyword can provide hints to the compiler to
perform optimizations. For example, it may inline constant
values or methods, improving performance.
• This is often used to prevent modification or extension of
certain classes, particularly utility classes.
Dr. Shweta Purohit,MTMC Jodhpur 37
Finalize Method
• The finalize() method in Java is a method of the Object class
used to perform cleanup activity before destroying any object.
• Garbage collector calls it before destroying the objects from
memory.
• Finalize method in Java is called by default for every object
before its deletion.
• This method helps the Garbage Collector close all the resources
the object uses and helps JVM in-memory optimization.
• All classes inherit the Object class directly or indirectly in Java.
The finalize() method is protected in the Object class so that all
classes in Java can override and use it.
protected void finalize() throws Throwable{}

Dr. Shweta Purohit,MTMC Jodhpur 38


Packages
• A package is a way to bundle together related classes,
packages, and interfaces.
• A package name is made up of the reverse of the
Internet Domain Name (to ensure uniqueness) plus
ones own organization's internal project name,
separated by dots '.'.
• Package names are in lowercase.
• The classes and interfaces of a package are like books
in the library that can reuse several times when we
need them.
• This reusability nature of packages makes
programming easy.
Dr. Shweta Purohit,MTMC Jodhpur 39
• Advantage of using packages in Java
– Maintenance: Java packages are used for proper maintenance.
If any developer newly joined a company, he can easily reach to
files needed.
– Reusability: We can place the common code in a common
folder so that everybody can check that folder and use it
whenever needed.
– Name conflict: Packages help to resolve the naming conflict
between the two classes with the same name. Assume that
there are two classes with the same name Student.java.
• Each class will be stored in its own packages such as stdPack1 and
stdPack2 without having any conflict of names.
– Organized: It also helps in organizing the files within our
project.
– Access Protection: A package provides access protection. It can
be used to provide visibility control. The members of the class
can be defined in such a manner that they will be visible only to
elements of that package.

Dr. Shweta Purohit,MTMC Jodhpur 40


Dr. Shweta Purohit,MTMC Jodhpur 41
• Pre Written classes from the Java API are included in the
built-in packages.
• Predefined packages in java are those which are
developed by Sun Microsystem.
• Several of the frequently used built-in packages include:
– Java.lang: Provides classes for languages in use (e.g classed
which defines primitive data types, math operations). This
package is imported automatically.
– Java.io: This package contains classes that handle input and
output operations.
– java.util: Contains utility classes which provide data structures
like Linked List, Dictionary and support ; for Date / Time
operations.
– java.applet: This package includes classes for building Applets.
• Classes for implementing the elements of graphical user interfaces are
implemented in the Java.awt library (like button , ;menus etc).
– Java.net: This library includes classes that support networking
operations.
Dr. Shweta Purohit,MTMC Jodhpur 42
Dr. Shweta Purohit,MTMC Jodhpur 43
• The package which is defined by the user is called a
User-defined package.
• It contains user-defined classes and interfaces.
• A keyword called “package” is used to create user-
defined packages in java.
• Syntax-
package packageName;
• The package statement must be the first line in a java
source code file followed by one or more classes.
package myPackage;
public class A {
// class body
}

Dr. Shweta Purohit,MTMC Jodhpur 44


where,
com ➝ It is generally company specification name and the folder starts with com
which is called root folder.
ibm ➝ Company name where the product is developed. It is the subfolder.
2. hdfc ➝ Client name for which we are developing our product or working for the
project.
3. loan ➝ Name of the project.
4. homeloan ➝ It is the name of the modules of the loan project.

Dr. Shweta Purohit,MTMC Jodhpur 45


• To Compile the application:
javac -d . directory javafilename
– Here, javac means java compiler.
– -d means directory. It creates the folder structure.
– .(dot) means the current directory. It places the
folder structure in the current working directory.
• For example:
• javac -d.Example.java // Here, Example.java is
the file name.
• To run Java package program
java completePackageName.className
Dr. Shweta Purohit,MTMC Jodhpur 46
• There are three approaches to import one
package into another package in Java.
– import package.*;
– import package.classname;
– Using fully qualified name.

Dr. Shweta Purohit,MTMC Jodhpur 47


API
• A programmer is given a set of tools to work with, like the
set of basic tools that are built into the language: variables,
assignment statements, if statements, and loops.
• These tools, if well-designed, can be used as black boxes
i.e. they can be called to perform their assigned tasks
without worrying about the particular steps they go
through to accomplish those tasks.
• The part of programming that takes all these tools and
apply them to some particular project or problem is known
as application programming.
• API(Applications Programming Interface) is interface that
specification of what routines are in the toolbox, what
parameters they use, and what tasks they perform.
Dr. Shweta Purohit,MTMC Jodhpur 48
• Java Application Programming Interface (API) is a
very large collection of pre-packaged, ready-made
software components that provides the core
functionality of the Java programming language.
• Java API is grouped into libraries of related classes
and interfaces along with their fields, constructors,
and methods.
• It provides many useful capabilities, such as
Graphical User Interface (GUI), Date, Time, and
Calendar capabilities to programmers.
• Since Java API is flexible, it can be opened to add
new packages or libraries into it.
Dr. Shweta Purohit,MTMC Jodhpur 49

You might also like