Shri Balaji institute of Technology & Management, Betul (M.P.
Department of Electrical & Electronics Engineering
Practical file
Subject :- Computer Programming-I (JAVA) Subject Code :- EX306
Semester :- III Year :- II
Name of the student:-………………………………… Enroll. No. :-……………………….
Index
[Link]. List of Program to be perform Date signature
1. Installation of J2SDK
2. Write a program to show Concept of CLASS in JAVA
3. Write a program to show Type Casting in JAVA
4. Write a program to show How Exception Handling is
in JAVA
5. Write a Program to show Inheritance and
Polymorphism
6. Write a program to show Interfacing between two
classes
7. Write a program to Add a Class to a Package
8. Write a program to demonstrate AWT.
Name of the faculty : Prof.
Signature :________________________
Practical 01
Aim: Installation of J2SDK
Theory:-
System Requirements
Software - Java 2 SDK Standard Edition, 1.4.2 is supported on i586 Intel and 100%
compatible platforms running Microsoft Windows. For a list of supported operating
systems and desktop managers, see System Configurations.
Steps:-
1. Install J2SDK 1.4.2_06.
a. Click J2SDK 1.4.2_06 to download Sun Java 2 SDK, Standard
Edition, version 1.4.2_06.
b. Click 'Download J2SDK'.
[Link] the license agreement.
d. Click the download link for the Windows Offline Installation Multi-
Language. The file j2sdk-1_4_2_06-[Link] is downloaded.
e. Run the program after it has finished downloading.
f. Accept all of the default installation options, unless changes are required.
Setting the PATH Environment Variable
It is useful to set the PATH variable permanently for JDK 10 so that it is persistent
after rebooting.
Note: The PATH variable is set automatically for the JRE. This topic only applies to
the JDK.
If you do not set the PATH variable, then you must specify the full path to the
executable file every time that you run it. For example:
C:\> "C:\Program Files\Java\jdk-10\bin\javac" [Link]
To set the PATH variable permanently, add the full path of the jdk-10\bin directory
to the PATH variable. Typically, the full path is:
C:\Program Files\Java\jdk-10\bin
To set the PATH variable on Microsoft Windows:
1. Select Control Panel and then System.
2. Click Advanced and then Environment Variables.
3. Add the location of the bin folder of the JDK installation to the PATH variable
in System Variables.
Note:The PATH environment variable is a series of directories separated by
semicolons (;) and is not case-sensitive. Microsoft Windows looks for
programs in the PATH directories in order, from left to right.
You should only have one bin directory for a JDK in the path at a time. Those
following the first instance are [Link] you are not sure where to add the
JDK path, append it.
The new path takes effect in each new command window that you open after
setting the PATH variable.
The following is a typical value for the PATH variable:
C:\WINDOWS\system32;C:\WINDOWS;"C:\Program Files\Java\jdk-10\bin"
-----------------------------------------000----------------------------------------------
Practical -02
Aim:- Write a program to show Concept of CLASS in JAVA
Theory :- What is Class?
A class is an entity that determines how an object will behave and what the object
will contain. In other words, it is a blueprint or a set of instruction to build a specific
type of object. A class is a user defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are common to all objects
of one type.
Syntax
class <class_name>{
field;
method;
}
What is an Object?
An object is nothing but a self-contained component which consists of methods and
properties to make a particular type of data useful. Object determines the behavior
of the class. When you send a message to an object, you are asking the object to
invoke or execute one of its methods.
From a programming point of view, an object can be a data structure, a variable or a
function. It has a memory location allocated. The object is designed as class
hierarchies.
Syntax
ClassName ReferenceVariable = new ClassName();
What is the Difference Between Object & Class?
A class is a blueprint or prototype that defines the variables and the methods
(functions) common to all objects of a certain kind.
An object is a specimen of a class. Software objects are often used to model real-
world objects you find in everyday life.
Understand the concept of Java Classes and Objects with an example.
Let's take an example of developing a pet management system, specially meant for
dogs. You will need various information about the dogs like different breeds of the
dogs, the age, size, etc.
You need to model real-life beings, i.e., dogs into software entities.
Moreover, the million dollar question is, how you design such software? Here is the
solution-
First, let's do an exercise.
You can see the picture of three different breeds of dogs below.
Stop here right now! List down the differences between them.
Some of the differences you might have listed out maybe breed, age, size, color, etc.
If you think for a minute, these differences are also some common characteristics
shared by these dogs. These characteristics (breed, age, size, color) can form a data
members for your object.
Next, list out the common behaviors of these dogs like sleep, sit, eat, etc. So these
will be the actions of our software objects.
So far we have defined following things,
● Class - Dogs
● Data members or objects- size, age, color, breed, etc.
● Methods- eat, sleep, sit and run.
Now, for different values of data members (breed size, age, and color) in Java class,
you will get different dog objects.
You can design any program using this OOPs approach.
While creating a class, one must follow the following principles.
● Single Responsibility Principle (SRP)- A class should have only one reason to
change
● Open Closed Responsibility (OCP)- It should be able to extend any classes
without modifying it
● Liskov Substitution Responsibility (LSR)- Derived classes must be
substitutable for their base classes
● Dependency Inversion Principle (DIP)- Depend on abstraction and not on
concretions
● Interface Segregation Principle (ISP)- Prepare fine grained interfaces that are
client specific.
Program:- Class and Object
// Class Declaration
public class Dog
{
// Instance Variables
String breed;
String size;
int age;
String color;
// method 1
public String getInfo()
{
return ("Breed is: "+breed+" Size is:"+size+" Age is:"+age+" color is: "+color);
}
public static void main(String[] args)
{
Dog maltese = new Dog();
[Link]="Maltese";
[Link]="Small";
[Link]=2;
[Link]="white";
[Link]([Link]());
}
}
Output:
Breed is: Maltese Size is:Small Age is:2 color is: white
---------------------------000-----------------------------
Program 03
AIM:-Write a program to show Type Casting in JAVA
Theory :- Type Casting in Java
Assigning a value of one type to a variable of another type is known as Type Casting.
Example :
int x = 10;
byte y = (byte)x;
In Java, type casting is classified into two types,
● Widening Casting(Implicit)
● Narrowing Casting(Explicitly done)
Widening or Automatic type conversion
Automatic Type casting take place when,
● the two types are compatible
● the target type is larger than the source type
Example:
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
[Link]("Int value "+i);
[Link]("Long value "+l);
[Link]("Float value "+f);
}
Output:-
Int value 100
Long value 100
Float value 100.0
Narrowing or Explicit type conversion
When you are assigning a larger type value to a variable of smaller type, then you
need to perform explicit type casting.
Example :
public class Test
{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required
[Link]("Double value "+d);
[Link]("Long value "+l);
[Link]("Int value "+i);
}
}
Output:-
Double value 100.04
Long value 100
Int value 100
---------------------000----------------------
Program 04
Aim:- Write a program to show How Exception Handling is in JAVA
Exception handling in java with examples
Exception handling is one of the most important feature of java programming that
allows us to handle the runtime errors caused by exceptions. In this guide, we will
learn what is an exception, types of it, exception classes and how to handle
exceptions in java with examples.
What is an exception?
An Exception is an unwanted event that interrupts the normal flow of the program.
When an exception occurs program execution gets terminated. In such cases we get
a system generated error message. The good thing about exceptions is that they can
be handled in Java. By handling the exceptions we can provide a meaningful
message to the user about the issue rather than a system generated message, which
may not be understandable to a user.
Why an exception occurs?
There can be several reasons that can cause a program to throw exception. For
example: Opening a non-existing file in your program, Network connection problem,
bad input data provided by user etc.
Exception Handling
If an exception occurs, which has not been handled by programmer then program
execution gets terminated and a system generated error message is shown to the
user. For example look at the system generated exception below:
An exception generated by the system is given below
Exception in thread "main" [Link]: / by zero at ExceptionDemo
.main([Link])
ExceptionDemo : The class name
main : The method name
[Link] : The filename
java:5 : Line number
This message is not user friendly so a user will not be able to understand what went
wrong. In order to let them know the reason in simple language, we handle
exceptions. We handle such conditions and then prints a user friendly warning
message to user, which lets them correct the error as most of the time exception
occurs due to bad data provided by user.
Advantage of exception handling
Exception handling ensures that the flow of the program doesn’t break when an
exception occurs. For example, if a program has bunch of statements and an
exception occurs mid way after executing certain statements then the statements
after the exception will not execute and the program will terminate abruptly.
By handling we make sure that all the statements execute and the flow of program
doesn’t break.
Difference between error and exception
Errors indicate that something severe enough has gone wrong, the application should
crash rather than try to handle the error.
Exceptions are events that occurs in the code. A programmer can handle such
conditions and take necessary corrective actions. Few examples:
NullPointerException – When you try to use a reference that points to null.
ArithmeticException – When bad data is provided by user, for example, when you try
to divide a number by zero this exception occurs because dividing a number by zero
is undefined.
ArrayIndexOutOfBoundsException – When you try to access the elements of an array
out of its bounds, for example array size is 5 (which means it has five elements) and
you are trying to access the 10th element.
Types of exceptions
There are two types of exceptions in Java:
1)Checked exceptions
2)Unchecked exceptions
Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as
the compiler checks them during compilation to see whether the programmer has
handled them or not. If these exceptions are not handled/declared in the program,
you will get compilation error. For example, SQLException, IOException,
ClassNotFoundException etc.
Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are
not checked at compile-time so compiler does not check whether the programmer
has handled them or not but it’s the responsibility of the programmer to handle these
exceptions and provide a safe exit. For example, ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc.
Example 1: Arithmetic exception
Class: [Link]
This is a built-in-class present in [Link] package. This exception occurs when an
integer is divided by zero.
class Example1
{
public static void main(String args[])
{
Try
{
int num1=30, num2=0;
int output=num1/num2;
[Link] ("Result: "+output);
}
catch(ArithmeticException e)
{
[Link] ("You Shouldn't divide a number by zero");
}
}
}
Output of above program:
You Shouldn't divide a number by zero
Explanation: In the above example I’ve divided an integer by a zero and because of
this ArithmeticException is thrown.
-----------------000------------------
Program 05
Aim:- Write a Program to show Inheritance and Polymorphism
Theory:- Inheritance in Java
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.
Inheritance in Java
1. Inheritance
2. Types of Inheritance
3. Why multiple inheritance is not possible in Java in case of class?
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
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.
Terms used in Inheritance
o Class: A class is a group of objects which have common properties. It is
a template or blueprint from which objects are created.
o 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.
o 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.
o 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
1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }
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.
In the terminology of Java, a class which is inherited is called a parent or superclass,
and the new class is called child or subclass.
Java Inheritance Example
1. class Employee
2. {
3. float salary=40000;
4. }
5. class Programmer extends Employee
6. {
7. int bonus=10000;
8. public static void main(String args[])
9. {
10. Programmer p=new Programmer();
11. [Link]("Programmer salary is:"+[Link]);
12. [Link]("Bonus of Programmer is:"+[Link]);
13. }
14. }
Output:- Programmer salary is:40000.0
Bonus of programmer is:10000
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.
Note: Multiple inheritance is not supported in Java through class.
When one class inherits multiple classes, it is known as multiple inheritance. For Example:
Single Inheritance Example
File: [Link]
1. class Animal
2. {
3. void eat(){[Link]("eating...");}
4. }
5. class Dog extends Animal
6. {
7. void bark(){[Link]("barking...");
8. }
9. }
10. class TestInheritance
11. {
12. public static void main(String args[])
13. {
14. Dog d=new Dog();
15. [Link]();
16. [Link]();
17. }
18. }
Output:
barking...
eating...
Multilevel Inheritance Example
File: [Link]
1. class Animal
2. {
3. void eat()
4. {
5. [Link]("eating...");
6. }
7. }
8. class Dog extends Animal
9. {
10. void bark()
11. {
12. [Link]("barking...");
13. }
14. }
15. class BabyDog extends Dog
16. {
17. void weep()
18. {
19. [Link]("weeping...");
20. }
21. }
22. class TestInheritance2
23. {
24. public static void main(String args[])
25. {
26. BabyDog d=new BabyDog();
27. [Link]();
28. [Link]();
29. [Link]();
30. }
31. }
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
File: [Link]
1. class Animal
2. {
3. void eat()
4. {
5. [Link]("eating...");
6. }
7. }
8. class Dog extends Animal
9. {
10. void bark()
11. {
12. [Link]("barking...");
13. }
14. }
15. class Cat extends Animal
16. {
17. void meow()
18. {
19. [Link]("meowing...");
20. }
21. }
22. class TestInheritance3
23. {
24. public static void main(String args[])
25. {
26. Cat c=new Cat();
27. [Link]();
28. [Link]();
29. //[Link]();//[Link]
30. }}
Output:
meowing...
eating...
Q) 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. {
3. void msg()
4. {
5. [Link]("Hello");
6. }
7. }
8. class B
9. {
10. void msg()
11. {
12. [Link]("Welcome");
13. }
14. }
15. class C extends A,B
16. {
17. //suppose if it were
18.
19. public static void main(String args[])
20. {
21. C obj=new C();
22. [Link]();//Now which msg() method would be invoked?
23. }
24. }
Output: Compile Time Error
-----------------------000---------------------
Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action in different
ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word
"poly" means many and "morphs" means forms. So polymorphism means many
forms.
There are two types of polymorphism in Java: compile-time polymorphism and
runtime polymorphism. We can perform polymorphism in java by method
overloading and method overriding.
If you overload a static method in Java, it is the example of compile time
polymorphism. Here, we will focus on runtime polymorphism in java.
Runtime Polymorphism in Java
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a
superclass. The determination of the method to be called is based on the object
being referred to by the reference variable.
Let's first understand the upcasting before Runtime Polymorphism.
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known
as upcasting. For example:
1. class A
2. {
3. }
4. class B extends A
5. {
6. }
1. A a=new B();//upcasting
For upcasting, we can use the reference variable of class type or an interface type. For Example:
1. interface I
2. {
3. }
4. class A
5. {
6. }
7. class B extends A implements I
8. {
9. }
Here, the relationship of B class would be:
B IS-A A
B IS-A I
B IS-A Object
Since Object is the root class of all classes in Java, so we can write B IS-A Object.
Example of Java Runtime Polymorphism
In this example, we are creating two classes Bike and Splendor. Splendor class
extends Bike class and overrides its run() method. We are calling the run method by
the reference variable of Parent class. Since it refers to the subclass object and
subclass method overrides the Parent class method, the subclass method is invoked
at runtime.
Since method invocation is determined by the JVM not compiler, it is known as
runtime polymorphism.
1. class Bike
2. {
3. void run()
4. {
5. [Link]("running");
6. }
7. }
8. class Splendor extends Bike
9. {
10. void run()
11. {
12. [Link]("running safely with 60km");
13. }
14.
15. public static void main(String args[])
16. {
17. Bike b = new Splendor();//upcasting
18. [Link]();
19. }
20. }
Output:
running safely with 60km.
Java Runtime Polymorphism Example: Bank
Consider a scenario where Bank is a class that provides a method to get the rate of
interest. However, the rate of interest may differ according to banks. For example,
SBI, ICICI, and AXIS banks are providing 8.4%, 7.3%, and 9.7% rate of interest.
Note: This example is also given in method overriding but there was no upcasting.
1. class Bank
2. {
3. float getRateOfInterest()
4. {
5. return 0;
6. }
7. }
8. class SBI extends Bank
9. {
10. float getRateOfInterest()
11. {
12. return 8.4f;
13. }
14. }
15. class ICICI extends Bank
16. {
17. float getRateOfInterest()
18. {
19. return 7.3f;
20. }
21. }
22. class AXIS extends Bank
23. {
24. float getRateOfInterest()
25. {
26. return 9.7f;
27. }
28. }
29. class TestPolymorphism
30. {
31. public static void main(String args[])
32. {
33. Bank b;
34. b=new SBI();
35. [Link]("SBI Rate of Interest: "+[Link]());
36. b=new ICICI();
37. [Link]("ICICI Rate of Interest: "+[Link]());
38. b=new AXIS();
39. [Link]("AXIS Rate of Interest: "+[Link]());
40. }
41. }
Output:
SBI Rate of Interest: 8.4
ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7
Java Runtime Polymorphism Example: Shape
1. class Shape
2. {
3. void draw()
4. {
5. [Link]("drawing...");
6. }
7. }
8. class Rectangle extends Shape
9. {
10. void draw()
11. {
12. [Link]("drawing rectangle...");
13. }
14. }
15. class Circle extends Shape
16. {
17. void draw()
18. {
19. [Link]("drawing circle...");
20. }
21. }
22. class Triangle extends Shape
23. {
24. void draw()
25. {
26. [Link]("drawing triangle...");
27. }
28. }
29. class TestPolymorphism2
30. {
31. public static void main(String args[])
32. {
33. Shape s;
34. s=new Rectangle();
35. [Link]();
36. s=new Circle();
37. [Link]();
38. s=new Triangle();
39. [Link]();
40. }
41. }
Output:
drawing rectangle...
drawing circle...
drawing triangle..
Java Runtime Polymorphism Example: Animal
1. class Animal
2. {
3. void eat()
4. {
5. [Link]("eating...");
6. }
7. }
8. class Dog extends Animal
9. {
10. void eat()
11. {
12. [Link]("eating bread...");
13. }
14. }
15. class Cat extends Animal
16. {
17. void eat(){[Link]("eating rat...");
18. }
19. }
20. class Lion extends Animal
21. {
22. void eat()
23. {
24. [Link]("eating meat...");
25. }
26. }
27. class TestPolymorphism3
28. {
29. public static void main(String[] args)
30. {
31. Animal a;
32. a=new Dog();
33. [Link]();
34. a=new Cat();
35. [Link]();
36. a=new Lion();
37. [Link]();
38. }
39. }
Output:
eating bread...
eating rat...
eating meat...
Java Runtime Polymorphism with Data Member
A method is overridden, not the data members, so runtime polymorphism can't be
achieved by data members.
In the example given below, both the classes have a data member speedlimit. We are
accessing the data member by the reference variable of Parent class which refers to
the subclass object. Since we are accessing the data member which is not
overridden, hence it will access the data member of the Parent class always.
Rule: Runtime polymorphism can't be achieved by data members.
1. class Bike
2. {
3. int speedlimit=90;
4. }
5. class Honda3 extends Bike
6. {
7. int speedlimit=150;
8.
9. public static void main(String args[])
10. {
11. Bike obj=new Honda3();
12. [Link]([Link]);//90
13. }
Output:
90
Java Runtime Polymorphism with Multilevel Inheritance
Let's see the simple example of Runtime Polymorphism with multilevel inheritance.
1. class Animal
2. {
3. void eat()
4. {
5. [Link]("eating");
6. }
7. }
8. class Dog extends Animal
9. {
10. void eat()
11. {
12. [Link]("eating fruits");
13. }
14. }
15. class BabyDog extends Dog
16. {
17. void eat()
18. {
19. [Link]("drinking milk");
20. }
21. public static void main(String args[])
22. {
23. Animal a1,a2,a3;
24. a1=new Animal();
25. a2=new Dog();
26. a3=new BabyDog();
27. [Link]();
28. [Link]();
29. [Link]();
30. }
31. }
Output:
eating
eating fruits
drinking Milk
Try for Output
1. class Animal
2. {
3. void eat()
4. {
5. [Link]("animal is eating...");
6. }
7. }
8. class Dog extends Animal
9. {
10. void eat()
11. {
12. [Link]("dog is eating...");
13. }
14. }
15. class BabyDog1 extends Dog
16. {
17. public static void main(String args[])
18. {
19. Animal a=new BabyDog1();
20. [Link]();
21. }
22. }
Output:
Dog is eating
Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is invoked.
---------000-------
Program 06
Write a program to show Interfacing between two classes.