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

4th to 7th Java Lab Programs.docx

The document provides an overview of Java programming concepts including constructor and method overloading, inheritance, method overriding, packages, and exception handling. It explains the rules and types of constructors, the significance of inheritance in object-oriented programming, and the differences between method overloading and overriding. Additionally, it discusses how to create and use packages in Java, as well as the importance of exception handling for maintaining application flow during runtime errors.

Uploaded by

mailtesting7670
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)
11 views

4th to 7th Java Lab Programs.docx

The document provides an overview of Java programming concepts including constructor and method overloading, inheritance, method overriding, packages, and exception handling. It explains the rules and types of constructors, the significance of inheritance in object-oriented programming, and the differences between method overloading and overriding. Additionally, it discusses how to create and use packages in Java, as well as the importance of exception handling for maintaining application flow during runtime errors.

Uploaded by

mailtesting7670
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/ 22

4. Write a program in JAVA to demonstrate the method and constructor overloading.

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.

Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java
compiler creates a default constructor if your class doesn't have any.

Rules for creating Java constructor

There are two rules defined for the constructor.

1. Constructor name must be the same as its class name

2. A Constructor must have no explicit return type

3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)

2. Parameterized constructor

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. They are differentiated by the compiler
by the number of parameters in the list and their types.

There are many differences between constructors and methods.

Java Constructor Java Method

A constructor is used to initialize the state of an A method is used to expose the

object. behavior of an object.

A constructor must not have a return type. A method must have a return

type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor The method is not provided by

if you don't have any constructor in a class. the compiler in any case.

The constructor name must be same as the class The method name may or may

name. not be same as the class name.


class Cs
{
int p,q;
public Cs()
{}
public Cs(int x, int y)
{
p=x;
q=y;
}
public int add(int i, int j)
{
return (i+j);
}
public int add(int i, int j, int k)
{
return (i+j+k);
}
public float add(float f1, float f2)
{
return (f1+f2);
}
public void printData()
{
System.out.println("p = "+p);
System.out.println("q = "+q);
}
}
class ConstructorOverlaoding
{
public static void main(String args[])
{
int x=2, y=3, z=4;
Cs c=new Cs();
Cs c1=new Cs(x, z );
c1.printData();
float m=7.2F, n=5.2F;
int k=c.add(x,y);
int t=c.add(x,y,z);
float ft=c.add(m, n);
System.out.println("k = "+k);
System.out.println("t = "+t);
System.out.println("ft = "+ft);
}
}
5. Program to define inheritance and show method overriding.

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).The idea behind inheritance in Java is that you can create new
classes that are built upon existing classes. When you inherit from an existing class, you
can reuse methods and fields of the parent class. Moreover, you can add new methods
and fields in your current class also.Inheritance represents the IS-A relationship which
is also known as a parent-child relationship.
Why use inheritance in java

● For Method Overriding (so runtime polymorphism can be achieved).

● For Code Reusability.

Terms used in Inheritance

● Class: A class is a group of objects which have common properties. It is a


template or blueprint from which objects are created.

● Sub Class/Child Class: Subclass is a class which inherits the other class. It is
also called a derived class, extended class, or child class.

● Super Class/Parent Class: Superclass is the class from where a subclass inherits
the features. It is also called a base class or a parent class.

● Reusability: As the name specifies, reusability is a mechanism which facilitates


you to reuse the fields and methods of the existing class when you create a new
class. You can use the same fields and methods already defined in the previous
class.

The syntax of Java Inheritance


class Subclass-name extends Superclass-name

//methods and fields

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface


only. We will learn about interfaces later.

When one class inherits multiple classes, it is known as multiple inheritance. For
Example:
Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B
classes. If A and B classes have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B class.Since compile-time
errors are better than runtime errors, Java renders compile-time error if you inherit 2
classes. So whether you have same method or different, there will be compile time error.

1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. public static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }

Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.In other words, If a subclass provides the specific
implementation of the method that has been declared by one of its parent class, it is
known as method overriding.

Usage of Java Method Overriding

● Method overriding is used to provide the specific implementation of a method


which is already provided by its superclass.

● Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

1. The method must have the same name as in the parent class

2. The method must have the same parameter as in the parent class.

3. There must be an IS-A relationship (inheritance).

Can we override static method?

No, a static method cannot be overridden. It can be proved by runtime polymorphism, so


we will learn it later.

Why can we not override static method?


It is because the static method is bound with class whereas instance method is bound
with an object. Static belongs to the class area, and an instance belongs to the heap
area.

Can we override java main method?

No, because the main is a static method.

Difference between method Overloading and Method Overriding in java

N Method Overloading Method Overriding


o.

1) Method overloading is used to increase the Method overriding is used to

readability of the program. provide the specific

implementation of the method

that is already provided by its

super class.

2) Method overloading is performed within Method overriding occurs in two

class. classes that have IS-A

(inheritance) relationship.
3) In case of method overloading, parameter In case of method overriding,

must be different. parameter must be same.

4) Method overloading is the example of Method overriding is the

compile time polymorphism. example of run time

polymorphism.

5) In java, method overloading can't be Return type must be same or

performed by changing return type of the covariant in method overriding.

method only. Return type can be same or

different in method overloading. But you

must have to change the parameter.

Programs :

// Base Class
class Parent {
void show()
{
System.out.println("Parent's show()");
}
}
// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
@Override
void show()
{
System.out.println("Child's show()");
}
}
// Driver class
class Main {
public static void main(String[] args)
{
// If a Parent type reference refers
// to a Parent object, then Parent's
// show is called
Parent obj1 = new Parent();
obj1.show();
// If a Parent type reference refers
// to a Child object Child's show()
// is called. This is called RUN TIME
// POLYMORPHISM.
Parent obj2 = new Child();
obj2.show();
}
}

6. Program to demonstrate Packages.

A java package is a group of similar types of classes, interfaces and


sub-packages.Package in java can be categorized in two form, built-in package and
user-defined package.There are many built-in packages such as java, lang, awt, javax,
swing, net, io, util, sql etc.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.


How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

1. javac -d directory javafilename

For example

1. javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You can
use any directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If
you want to keep the package within the same directory, you can use . (dot).

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.

How to access package from another package?


There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

6.1) Using packagename.*


If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.

The import keyword is used to make the classes and interface of another package
accessible to the current package.

//save by A.java

package pack;

public class A{

public void msg(){System.out.println("Hello");}

//save by B.java

package mypack;

import pack.*;

class B{

public static void main(String args[]){

A obj = new A();

obj.msg();

}
6.2) Using packagename.classname

If you import package.classname then only declared class of this package will be
accessible.

Example of package by import package.classname


//save by A.java

package pack;

public class A{

public void msg(){System.out.println("Hello");}

//save by B.java

package mypack;

import pack.A;

class B{
public static void main(String args[]){

A obj = new A();

obj.msg();

6.3) Using fully qualified name


If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.

It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.

Example of package by import fully qualified name


//save by A.java

package pack;

public class A{

public void msg(){System.out.println("Hello");}

//save by B.java

package mypack;

class B{

public static void main(String args[]){

pack.A obj = new pack.A();//using fully qualified name

obj.msg();
}

Note: If you import a package, subpackages will not be imported.

If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import the
subpackage as well.

Note: Sequence of the program must be package then import then class.

Subpackage in java
Package inside the package is called the subpackage. It should be created to
categorize the package further.

Let's take an example, Sun Microsystem has definded a package named java that
contains many classes like System, String, Reader, Writer, Socket etc. These classes
represent a particular group e.g. Reader and Writer classes are for Input/Output
operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun
has subcategorized the java package into subpackages such as lang, net, io etc. and put
the Input/Output related classes in io package, Server and ServerSocket classes in net
packages and so on.

The standard of defining package is domain.company.package e.g. com.javatpoint.bean or


org.sssit.dao.

Example of Subpackage
package com.javatpoint.core;

class Simple{

public static void main(String args[]){

System.out.println("Hello subpackage");

To Compile: javac -d . Simple.java

To Run: java com.javatpoint.core.Simple

7. Program to demonstrate Exception Handling.

The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.

Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.

What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application; that is
why we need to handle exceptions. Let's consider a scenario:

Suppose there are 10 statements in a Java program and an exception occurs at


statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be
executed. However, when we perform exception handling, the rest of the statements will
be executed. That is why we use exception handling in Java.

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by
two subclasses: Exception and Error. The hierarchy of Java Exception classes is given
below:
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are three
types of exceptions namely:

1. Checked Exception

2. Unchecked Exception

3. Error
Difference between Checked and Unchecked Exceptions

1) Checked Exception:The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions. For example,
IOException, SQLException, etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception:The classes that inherit the RuntimeException are known as


unchecked exceptions. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.

3)Error:Error is irrecoverable. Some example of errors are OutOfMemoryError,


VirtualMachineError, AssertionError etc.

Common Scenarios of Java Exceptions


There are given some scenarios where unchecked exceptions may occur. They are as
follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.

1. String s=null;
2. System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result into


NumberFormatException. Suppose we have a string variable that has characters;
converting this variable into digit will cause NumberFormatException.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there


may be other reasons to occur ArrayIndexOutOfBoundsException. Consider the
following statements.

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException

7.1 Write a program in java if number is less than 10 and greater than 50 it generate the
exception out of range. Else it displays the square of number.

class CustomTest
{
public static void main(String arr[])
{
try
{
int a=Integer.parseInt(arr[0]);
if(a<0|| a>50)
throw(new Exception("valid range is 10 to 50"));
{
int s=a*a;
System.out.println("Square is:"+s);
}
}catch(Exception ex)
{
System.out.println(ex);
}
}
}
7.2 Write a program in java to enter the number through command line argument if first
and second number is not entered it will generate the exception. Also divide the first
number with second number and generate the arithmetic exception.

class Divide2
{
public static void main(String arr[])
{
try
{
if(arr.length<2)
throw(new Exception("two argument must be provided"));
int a= Integer.parseInt(arr[0]);
int b=Integer.parseInt(arr[1]);
if(b==0)
throw(new Exception("second argument should be non zero"));
int c=a/b;
System.out.println("result:"+c);
}
catch(Exception e)
{
System.out.println(e);
}
}}

7.3 Write a program in java to enter the number through command line argument if first
and second number using the method divides the first number with second and generate
the exception.
class Divide3
{
public static int divide(int x, int y)
{
int z=0;
try
{
try
{
z= x/y;
}
finally
{
//return Z;
}
}
catch(ArithmeticException ex)
{
System.out.println(ex);
}
return z;
}
public static void main(String arr[])
{
try
{
int a=Integer.parseInt(arr[0]);
int b=Integer.parseInt(arr[1]);
int c=divide(a,b);
System.out.println("Result is="+c);
}
catch(Exception e)
{
System.out.println(e);
}
}
}

You might also like