4th to 7th Java Lab Programs.docx
4th to 7th Java Lab Programs.docx
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.
2. Parameterized constructor
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.
A constructor must not have a return type. A method must have a return
type.
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
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
● 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.
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.
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. }
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.
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.
super class.
(inheritance) relationship.
3) In case of method overloading, parameter In case of method overriding,
polymorphism.
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();
}
}
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
If you are not using any IDE, you need to follow the syntax given below:
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).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
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.
1. import package.*;
2. import package.classname;
3. fully qualified name.
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{
//save by B.java
package mypack;
import pack.*;
class B{
obj.msg();
}
6.2) Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible.
package pack;
public class A{
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
obj.msg();
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
package pack;
public class A{
//save by B.java
package mypack;
class B{
obj.msg();
}
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.
Example of Subpackage
package com.javatpoint.core;
class Simple{
System.out.println("Hello subpackage");
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.
In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
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:
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.
1. int a=50/0;//ArithmeticException
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
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);
}
}
}