GOVERNMENTPOLYTECHNIC
KALABURAGI-109
Board Register No:
CERTIFICATE
This is to certify that Mr/Miss.
of 4th semester, Computer Science & Engineering
Department, has satisfactorily completed the “OBJECT
ORIENTED PROGRAMMING AND DESIGN WITH
JAVA.” during the year2025-2026
Staff Signature HOD signature
Examiners signature with date
1)
2)
Page 1
WEEK TITLEOF THEPRACTISE PAGE DATE REMARKS
NO
1 1. Install and Setup java
environment
2. Install java editor(Eclipse for
Enterprise Java) and configure
workspace
3. Execution of first java program
4. Java code execution process
2 1. Code, execute and debug
programs that uses different
Types of variables and datatypes;
3 1. Code, execute and debug
programs
a. That uses different types
of constructors
4 [Link] allocation explanation
through the programs
5 1. Code, execute and debug
programs that uses different
control statements (A. if elif
else
[Link] loop, [Link] loop)
6 1. Code, execution debug
programs
2. That uses encapsulation concept
7 1. Code, execute and
debug programs that
Uses array concept(arrayList)
8 1. Code, execute and debug
programs that uses inheritance
concept(Employee Management
System ).
8 1. Code, execute and debug
programs that uses inheritance
concept
*Employee System
Page 2
9 1. Code, execute and
debug programs that uses
a. Static binding
b. Dynamic binding
10 1. Code, execute and debug
programs that uses
2. Interface code
11 1. Design a oops with java program
using a final variable in a class.
2. Design a oops with java program
using static.
12 1. Design a oops with
java program using
setter getter for car
class
13 1. Develop a Java application that
connects to a MySQL database
using JDBC and retrieves
student details from a table
named "student". Provide the
code solution and the output of
the application
Page 3
Week-1
1. Install and Setup java environment
Setup Java EnvironmentinWindows10or Install Java Manually
To setup Java Environment inWindows10 or older Windows operating systems, you
need to download Java from Oracle website and Install it in the computer. There are
two variations of Java.
1. JDK or Java SE(Java Standard Edition )
2. JRE(Java Runtime Environment )
1. Java SE
Java SE installs both JDK and JRE. JDK is Java Developer Kit. If you are developing
Java applications, you need to compile the java programs. Hence JDK is the right
option to install in this case.
2. JRE
JRE is useful only to run Java Applications but not for development works. Some
websites force users to install JRE in order to display customized information that is
displayedonlyonJavaSupported(Orinstalled)[Link] java
programs or software, just install JRE on your machine.
Setting up Java Environment in Windows is nothing but adding Java Installation
Path to Operating System Variables. It is called Setting Up Java Home.
There are two path variables to be setup in a Windows10 Computer
1. Setup JAVA_HOME or Java Home Directory-To access JDK, JRE Tools
2. Setup CLASS PATH or Class Path-To attach or add Libraries and Helper Classes
1. Setting Up Java Home or Java_Home Path
Step 1
Open Control Panel. Go to System & Security. Open System.
or
Right Click on My Computer and go to Properties.
Page 4
Step2:Here you can see your computer hardware specifications like RAM, Processor
Type and Windows Activation status etc. Go to Advanced System Settings on the left
side.
Step3
Under system properties, go to Advanced Tab. On the bottom, you can find a button
with name 'Environment Variables..'. Just click.
Page 5
Step4
Under Environment Variables, you can see two sections. The top section shows User
variables and
The bottom section shows System Variables. In either of them, find for Variable
Name PATH or path. If it is not available click New on any section and add PATH
as variable
NAME and Value as C:\ProgramFiles\Java\jdk1.8.0_131\binforexample.
If the PATH variable is already existing in any section, simply click Edit and add the
Java
Installation Path.
If the requirement is to set up java_home as required by any applications like Tomcat,
add the
Variable name as java_home and the path requested by the application.
A. Setting CLASS PATH using Command Prompt or CMD
The advantage of adding Class path in command prompt is that you can include or
add different libraries for different projects. This can be achieved using -cp or –
class path options as part of JAVAC and JAVA commands.
B. Adding CLASS PATH to Windows Environment Variables
This approach is not recommended as you can no thate differentlibrariesfordifferent
projects. Libraries required for one java project may not be required for another java
project. Including unnecessary libraries consume memory and affects performance.
Follow the below steps toadd CLASSPATH to WindowsEnvironment Variables.
Step1:OpenEnvironmentVariablesscreenasshownintheaboveJAVA_HOME
tutorial.
Page 6
Step2:Check forCLASSPATHvariable Under UserVariablesorSystemVariables. If
CLASSPATH variable is available, add an entry with the path of your Libraries or
Class Files.
Step 3: If the CLASSPATH variable is not available, add it manually under User
VariablesorSystemVariablesandthenaddanentryormultipleentrieswithPathsof your
libraries or JAR files.
Step4:[Link]
CLASSPATH in your [Link] program or any other programs or any projects
running on the PC.
CLASSPATHPathRulesforAddingmultipleJarandClassFiles
Rule1:You can mentionthefullpath ofaClassfileorJarfileforinclusioninClass Path.
Rule2:You canmentionthepath uptoadirectory nametoincludeallJarfilesand Class Files
in that directory.
Rule3:Takecareoftheorderofinclusionoffilesassomelibrariesdependonother libraries to
be loaded first.
Rule4:OnaWindowsmachine,useSemicolon(;)[Link] youareusing Command
Prompt, use Colon (:) to separate multiple paths.
HowtoCheckJavaisInstalledorNot
YoucancrosscheckwhetheryousuccessfullyinstalledJavaornotusingthe command
prompt.
Thischeck alsocovers whether JavaEnvironmentissetupproperly or not.
Step1:OpenCMDorCommand Prompt
Step2:Ifyoucangetreplytojavacommand,itmeansJREissuccessfullysetupfor running
java programs.
Step 3: If you can get reply to javac command, it means JDK or Java SE is
[Link] up of
JAVA_HOME path.
Page 7
Step4:Youcanalsocheck theinstalledJAVAVersionusing-versioncommand.
Howtosolveerrorjavacisnotrecognizedasaninternalorexternalcommand
Step1:CheckwhetheryouinstalledJavaontheSystemornotbypinging'javac'in
command prompt. You should install Java SE or JDK but not JRE.
Step2:SetupJavaHomePath [Link] path
should be either added to User Variables or System Variables under Environmental
Variables.
Step3:RestartCMDorCommandPrompt.
Step4:RestartWindowsandpingjavac again.
2. Installjavaeditor(EclipseforEnterpriseJava)and
configure workspace
To install and configure Eclipse, you can do the
following:GototheEclipsedownloadpageandyouwillseesomethin
glike below.
Onthatpagethelatestversionwillbedisplayedfordownload,you can
directly click on download 64 bit (this depends on the OS you have
on your machine) or click on download packages to view more
packages available.
Page 8
Onclickingdownloadpackages,thefollowingpagewillbe
displayed with multiple Eclipse versions.
Youcanchoosetogowiththelatestversion, orifyouwanttogo with a
previous version, click on the one you want from the highlighted
other versions. Once you click on that a similar list of available
Eclipse IDE download links will be displayed for that version.
ForExample,ifyouclickonEclipseNeon,youwillgetalistof Neon IDE
downloads.
Select Eclipse IDE for Java developers and select the download
linkfromoneofthebelowdependingontheoperatingsystem of
your machine.
Page 9
Forawindowssystem,youcancheckyourOStypefromyour system
information, by going through the control panel.
OnceyouselecttheOStypedownloadlink,youwillbe redirected to
the following page.
Page 10
Assoonasyouclickthehighlightedlink,thedownloadbeginsandafter some
time the downloaded zipped file will be saved in your machines
downloads folder.
Extractthecontents ofthis Zipfolder,andyouwillgetafolderbythe name of
“Eclipse” and place this in the C drive.
Youshouldseethebelowfolderstructureonceyouaredonewiththe above
steps.
EclipseIDEdoesnotrequireinstallation,onceyouhavethisfolder structure
look for the Eclipse executable file highlighted above.
LaunchingthisexecutablefileopenstheIDEforyouruse.
Page 11
SettingUpYourEclipseWorkspace
Once youhavethe Eclipse applicationonyourmachine, youcan launch
[Link],thefirsttime you
open Eclipse, you will be asked to create a workspace.
Aworkspaceisalocationonyourmachinewherealltheworkyoudo
through Eclipse will be stored as files. It is easier to create one
workspace and saveit as default so that your applicationremembers
your past work.
OnceyouopenEclipse,you willseethebelowimage.
Thefollowingwindowwillshowupafterafewseconds.
Page 12
Here you can see the highlighted default workspace location. If you are
finewiththis,thensimplyclickthelaunch [Link] youwanttocreatea
workspace in a specific location on your machine, then browse to that
folder and then click launch.
Youcanseethecheckboxaskingtousethelocationasdefaultchecked, this is
to ensure that the next time when you launch Eclipse it
automaticallyopens thesameworkspace,sothatyouhaveaccesstoall the
work saved in this location.
After clicking the launch button, it may take some time for the Eclipse
[Link] case
of an existing workspace, the projects, etc. maybe fetched. Hence, do
not worry if it takes a few minutes.
Oncetheworkbenchislaunched,youwillseethefollowingdefault view.
[Link], youmay want
to read through some of the links given regarding the tutorials or
Page 13
samplesto [Link] through
the “What’s new” section to see what this latest version of Eclipse has.
Ifyoudonotwanttoseethewelcomepagewhenyoulaunch Eclipsein future,
then you can turn it off by unchecking the checkbox highlighted
atthebottomofthepageoryoucansimplyclosethewelcomepageby clicking
on the closed sign on the title of the welcome page.
Afterclosingthewelcomepage,youwillseethefollowingview.
Atthispoint,youhavesuccessfullylaunchedyourEclipseIDEworkbench and
are ready to start creating your first code.
Before we get into creating projects and writing actual codes, there are
few more setup related things that you must know. These are
environment variables. Eclipse automatically configures itself to the
availableJREinthesystem,ifyouhavesettheenvironmentvariablesat the
time of setting up Java.
Page 14
Theprimaryenvironmentvariablesinclude:
1. JAVA_HOME:PointtoJDKfolder.
2. JRE_HOME:PointtoJREfolder
3. Path:[Link]
ensure that you do not delete anything that is already present in
this variable, just add your new folder locations.
InEclipse,ifyouwanttoupdateanypath relatedtoJavafiles,thenyou can do
this by going to preferences (Go to top menu item Window->
Preferences) and the below window will open up.
However,do not get confused with this now .Wew ill discuss more on
this while we are creating and working with projects.
Page 15
3. Execution of first java program
Step1:Write a Simple Java Program
Create an own file with the name [Link] and write the
following code:
Public class HelloWorld{
public static void main(String[] args) {
[Link]("Hello,World!");
}
}
Step2:Compile the Java Program
Open your terminal/command prompt, navigate to the directory where
your file is saved, and run:
Javac [Link]
This will compile the code and generate a file named [Link].
Step3:Run the Compiled Java Program
Now run the program using the java command:
java HelloWorld
You should see the output:
Hello,World!
Key Points:
File name must match the class name(HelloWorld).
Make sure Java is installed and javac /java are in your system's PATH.
Page 16
4. Java code execution process
Great! Let me explain the Java code execution process step-by-step—
from writing code to running it on your machine.
Java Code Execution Process:
1. Write Java Code
You write code in a .java file using at exted it eror IDE.
public class HelloWorld {
public static void main(String[] args)
{[Link]("Hello,World!");
2. Compilation(SourceCode→Bytecode)
The .java file is compiled by the Java Compiler(javac) into bytecode,
which is stored in a .class file.
javac [Link]
Output: [Link]
This .class file contains platform-independent bytecode.
3. Class Loader
When your in the program, the Class Loader loads the. Class file into
memory.
It loads classes from your program, Java libraries, and external
libraries.
It verifies and prepares classes for execution.
Page 17
4. Bytecode Verification
The Bytecode Verifier checks the bytecode for:
Security(no illegal code)
Stack overflows
Type safety, etc.
5. JVM Execution(Bytecode→MachineCode)
The Java Virtual Machine(JVM) executes the bytecode:
Uses the Interpreter for simple execution
Uses JIT(Just-In-Time)Compiler to convert bytecode into native
machine code for faster performance
Your Code(.java)
Javac Compiler
Bytecode(.class)
Class Loader→ Bytecode Verifier
JVM
(Interpreter + JIT)
Output on Screen
Page 18
Week-2
1. Code, execute and debug programs that uses different types of
variables and datatypes;
CODE:
import [Link];
class Result {
public static void main(String args[]){
String name;
int roll_number;
float percentage;
Scanner sc = new Scanner([Link]);
[Link]("Enter student name");
name=[Link]();
[Link]("Enter student rollno");
roll_number=[Link]();
[Link]("Enter student percentage");
percentage=[Link]();
[Link]("student name:"+name);
[Link]("student roll
number:"+roll_number);
[Link]("student percentage:"+percentage);
if (percentage>=35) {
[Link]("Pass");
}
else{
[Link]("Fail");
}
}
}
Output:
Enter student name: James
Enter student roll no: 6
Enterstudentpercentage:97
student name: James
student roll number:6
studentpercentage:97.0
Page 19
Pass
Page 20
Week-3
2. Code, execute and debug programs
a. That uses different types of constructors
CODE:
class Restaurant{
private String restaurantName;
private long restaurantContact;
private String restaurantAddress;
private float rating;
public Restaurant(String restaurantName, long restaurantContact, String
restaurantAddress, float rating){
[Link]=restaurantName;
[Link]=restaurantContact;
[Link]=restaurantAddress; [Link]=rating;
}
public void displayRestaurantDetails() {
[Link]("restaurantName:"+ restaurantName);
[Link]("restaurantconatct:"+restaurantContact);
[Link]("restaurantAddress:"+restaurantAddress);
[Link]("rating:"+rating);
}
}
classTester{
public static void main(String[] args){
Restaurant r1=new Restaurant("GoodLuck",123456,"GPT",10);
[Link]();
}
}
Output:
Restaurant Name: GoodLuck
Restaurant conatct:123456
Restaurant Address: GPT
rating:10.0
Page 21
b. Write a java program for expression evaluation
CODE:
import [Link];
class Arithmetic{
publicstaticvoidmain(String[]args){ int
num1,num2;
Scanner sc=newScanner([Link]);
[Link](“enter num1:");
num1=[Link]();
[Link]("enternumTwo:");
numTwo=[Link]();
[Link]("Addition:"+num1 + num2);
[Link]("Substraction:"+num1 - num2);
[Link]("Multiplication:"+num1 * num2);
[Link]("Division:"+num1 / num2);
[Link]("Modulo:"+num1 % num2);
}
}
Output:
enternum1:
13
enternum2:
13
Addition:26
Substraction:0
Multiplication:169
Division:1
Modulo:0
Page 22
Week-4
[Link] allocation explanation through the programs
class MemoryExample{
static String staticVar="I am in Meta space";
public static void main(String args[]){
int x=10;
String str="Hello";
Students1=new Student("John",101);
Students2=newStudent("Alice",102);
[Link]("Done");
class Student{
String name;
int rollNo;
Student(String name, int rollNo) {
[Link] = name;
[Link]=rollNo;
Element Stored In
Page 23
x(int) Stack(local primitive variable)
"Hello" String Pool(Meta space)
Stack references, but objects are in
s1,s2
Heap
Page 24
Element Stored In
staticVar Meta space(class-level data)
Student class structure Meta space
name, rollNo(inside Student
Heap
object)
How JVM Allocates Memory at Runtime
When main()starts:
Stack frame is created.
Local variables(x,str,referencess1,s2)are allocated on Stack.
When new Student(...)is called:
JVM allocates memory in Heap.
Name and rollNo become instance variables on the Heap.
Class loading:
JVM loads Student and Memory Example class meta data
into Meta space.
Page 25
Week-5
1. Code, execute and debug programs that uses different control
statements.
A. Write a Java program that checks whether a given number is
positive, negative, or zero. Display an appropriate message based on the
condition.
CODE:
import [Link];
class NumberCheck {
public static void main(String args[]){
Scanner sc=newScanner([Link]);
[Link]("Enter a number: ");
int number=[Link]();
if (number > 0) {
[Link]("The number is positive.");
}
elseif(number <0){
[Link]("The number is negative.");
}
else{
} [Link]("The number is zero.");
}
}
Output:
Enter a number:10
The number is
positive.
Enter a number: -4
The number is negative.
Enter a number: 0
The number is zero.
Page 26
B. Write a Java program to find the sum of all numbers from 1 to 100
using a while loop
CODE:
class SumOfNumbers{
public static void main(String[]args){
int sum = 0;
int i =1;
while(i<=100){
sum+=i;
i++;
}
[Link]("Sum:"+sum);
}
}
Output:
Sum:5050
C. Write a program to calculate the factorial of a given number using a
for loop. Here’s a Java program that calculates the factorial of a given
number using a for loop:
CODE:
import [Link].*;
import [Link];
class Factorial{
public static void main(String args[]){
int fact=1;
Scanner s = new Scanner([Link]);
[Link]("Enter a number");
int num = [Link]();
for(int i=1; i<=num; i++){
fact=fact*i;
}
[Link]("The number of factorial="+fact);
}
}Output:
Enter a number to calculate its factorial: 5
Factorialof5is:120
Page 27
Week-6
[Link] a Java class called `Student` that encapsulates the information
of a student, including their name, age, and grade.
Also, include a method to check if the student is eligible for graduation
(i.e., if their grade is above a certain threshold).
CODE:
class Student{
private String name;
private int age;
private double grade;
public Student (String name,int age, double grade){
[Link]=name;
[Link]=age;
[Link]=grade;
}
public boolean isEligible(){
boolean threshHold= grade>=70;
return threshHold;
}
public void display (){
[Link]("Name:"+name);
[Link]("Age:"+age);
[Link]("Grade:"+grade);
}
}
class TesterStudent{
public static void main(String[] args) {
Student s1= new Student ("Rahul",21, 86.77);
[Link]();
[Link]("is Eligible for Graduation:"+[Link]());
}
}
OUTPUT:
Name: Rahul
Age: 21
Grade:86.77
Eligible for Graduation: true
Page 28
Week-7
[Link], execute and debug programs that uses array concept
CODE:
class Restaurant{
private String restaurantName;
private long[] restaurantContact;
private String restaurantAddress;
private float rating;
public Restaurant(String restaurantName,long []
restaurantContact,String restaurantAddress,float rating){
[Link]=restaurantName;
[Link]=restaurantContact;
[Link]=restaurantAddress;
[Link]=rating;
}
public void displayRestaurantDetails(){
[Link]("displayrestaurant
details\n***********");
[Link]("Restaurant
name:"+restaurantName);
[Link]("Restaurantrating:"+rating);
[Link]("Restaurant contact:");
for(int index=0; index<[Link]; index++)
[Link]([Link][index]);
[Link]("Restaurant
address:"+restaurantAddress);
[Link]();
}
}
classTester{
public static void main(String[]args){
long[] restaurantContact={12345L,12346L,12347L};
Restaurant r1= new
Restaurant("swiftfood",restaurantContact, "gpt" ,4.1f);
[Link]();
}
}
Page 29
Output:
Display restaurant details
***********
Restaurant name: swiftfood
Restaurant rating:4.1
Restaurant contacts:
12345
12346
12347
Restaurant address: gpt
Page 30
Week-8
1. Code, execute and debug programs that uses inheritance
concept
Create a class hierarchy to represent different types of animals. The base class is
called "Animal" and has a method named `makeSound()` that prints "Animal is
making a sound". Derive two subclasses from Animal: "Dog" and "Cat". Override
the `makeSound()` method in each subclass to provide a specific sound for each
[Link],createinstancesofbothDogandCatclassesandcall the
`makeSound()` method on each object. Provide the code and the expected output.
CODE:
class Animal{
Public void makeSound(){
[Link]("Animal is making a sound");
}
}
class Dog extends Animal{
public void makeSound() {
[Link]("Dog is barking");
}
}
class Cat extends Animal{
public void makeSound() {
[Link]("Cat is meowing");
}
}
class AnimalDemo{
public static void main(String args[]){
Animal animal1 = new Animal();
Cat animal2 = new Cat();
Dog animal3=new Dog();
[Link]();
[Link]();
[Link]();
}
}
Output:
Dog is barking
Cat is meow
Page 31
Employee Management System
You have different types of Workers of college like faculty, officestaff,
Teacher. Calculate the salary of different workers
CODE:
class Faculty{
protected String name;
protected float basicSalary;
protected float bonusPercentage ;
protected float carAllowancePercentage;
public Faculty(String name, float basicSalary, float bonusPercentage, float
carAllowancePercentage){
[Link]=name;
[Link]=basicSalary;
[Link]=bonusPercentage;
[Link]= carAllowancePercentage;
}
public double calculateSalary(){
float b= basicSalary * bonusPercentage/100;
float c= basicSalary * carAllowancePercentage/100;
return (basicSalary+b+c);
}
public void display (){
[Link]("Name:"+name);
[Link]("Basic Salary:"+basicSalary);
[Link]("Bonus percentage:"+ bonusPercentage);
[Link]("Car allowance percentage:"+
carAllowancePercentage);
}
}
class officeStaff extends Faculty{
protected String designation;
public officeStaff(String name, float basicSalary, float bonusPercentage,
float carAllowancePercentage, String designation){
super(name,basicSalary,bonusPercentage,carAllowancePercentage);
Page 32
[Link]=designation;
}
public double calculateSalary(){
return super. calculateSalary();
}
public void display (){
[Link]();
[Link]("Designation:"+designation);
}
}
class Teacher extends Faculty{
protected String qualification;
public Teacher (String name, float basicSalary, float bonusPercentage, float
carAllowancePercentage, String qualification){
super(name,basicSalary,bonusPercentage,carAllowancePercentage);
[Link]=qualification;
}
public double calculateSalary(){
float bonusOfTeacher=basicSalary * bonusPercentage/100;
return basicSalary+bonusOfTeacher;
}
public void display (){
[Link]();
[Link]("Qualification:"+ qualification);
}
}
class TesterFault{
public static void main(String[]args){
Faculty f= new Faculty ("Ramesh", 256.7f, 5.5f, 7.1f);
officeStaff o= new officeStaff("Ram", 456.6f, 8.7f, 3.6f, "Manager");
Teacher t= new Teacher ("Don", 345.7f, 6.1f, 2.3f, "Engineering");
[Link]();
Page 33
[Link]("Faculty salary:"+ [Link]());
[Link]();
[Link]("Office staff salary:"+ [Link]());
[Link]();
[Link]("Teacher salary:"+ [Link]());
}
}
Output:
Name: Ramesh
Basic salary: 256.7
Bonus percentage: 5.5
Car allowance percentage: 7.1
Faculty salary: 289.03
Name: Ram
Basic salary: 456.6
Bonus percentage: 8.7
Car allowance percentage: 3.6
Designation: Manager
Office staff salary: 512.75
Name: Don
Basic salary: 345.7
Bonus percentage: 6.1
Car allowance percentage: 2.3
Qualification: Engineering
Teacher salary: 289.03
2. Design a class to find area of rectangle and area of circle and
check compliance with OCP.
Page 34
CODE:
class Rectangle {
double length, breadth;
public Rectangle(double length, double breadth) {
[Link] = length;
[Link] = breadth;
}
public double calculateArea() {
double area=length * breadth;
return area;
}
}
class Circle {
double radius;
public Circle(double radius) {
[Link] = radius;
}
public double calculateArea() {
double circleArea=3.14 * radius * radius;
return circleArea;
}
}
class TesterArea{
public static void main(String[] args) {
Rectangle r = new Rectangle(5, 4);
[Link]("Area of Rectangle = " + [Link]());
Circle c = new Circle(3);
[Link]("Area of Circle = " + [Link]());
}
}
Output:
RectangleArea:200.0
CircleArea:113.09733552923255
Page 35
Week-9
1. Code, execute and debug programs that uses
a. Staticbinding
CODE :
class Perimeter{
public void calculate(int length, int breadth) {
int perimeter = 2 * (length + breadth);
[Link]("Perimeter of Rectangle: " + perimeter);
}
public void calculate(double radius) {
double perimeter = 2 * 3.14 * radius;
[Link]("Perimeter of Circle: " + perimeter);
}
}
class TesterPerimeter{
public static void main(String[] args) {
Perimeter obj = new Perimeter();
[Link](10, 5);
[Link](7.0);
}
}
Output:
Perimeter of Circle:30
Perimeter of
rectangle:43.96
b. Dynamic binding
The code given below shows the different possibilities of using
parent and child class referencing and object [Link]
the code given below, observe the output.
Code:
class Customer {
double amount;
Page 36
Customer(double amount) {
[Link] = amount;
}
public double finalBill() {
double discount = 0;
double total = amount - discount;
return total;
}
}
class RegularCustomer extends Customer {
RegularCustomer(double amount) {
super(amount);
}
public double finalBill() {
double discount = amount * 0.10;
double total = amount - discount;
return total;
}
}
class TesterCustomer{
public static void main(String[] args) {
Customer c= new Customer(1000.87);
[Link]("Customer Final Bill:"+[Link]());
RegularCustomer r= new RegularCustomer(1000.87);
[Link]("Regular customer bill:"+[Link]());
}
}
Output:
Customer Final Bill:1000.87
Regular customer bill: 900.67
Page 37
Week-10
1. Code, execute and debug programs that usage of
abstract class
Code:
abstract class Employee{
abstract void calculateSalary();
}
class Manager extends Employee {
void calculateSalary() {
[Link]("Manager Salary: 50000");
}
}
class Clerk extends Employee {
void calculateSalary() {
[Link]("Clerk Salary: 20000");
}
}
class TesterEmployee {
public static void main(String args[]) {
Manager m= new Manager();
Clerk c= new Clerk();
[Link]();
[Link]();
}
}
Output:
Manager Salary: 50000
Clerk Salary:20000
Page 38
[Link] Code :
interface Tax{
double calculateTax(double price);
}
class purchaseDetails implements Tax{
private int purchaseId;
private String purchaseType;
private double taxPercentage;
public purchaseDetails(int purchaseId, String purchaseType, double
taxPercentage){
[Link]=purchaseId;
[Link]=purchaseType;
[Link]=taxPercentage;
}
public double calculateTax(double price){
double Tax=price * taxPercentage /100;
return Tax;
}
public void display(){
[Link](“ID:”+purchaseId);
[Link](“Type:”+purchaseType);
[Link](“Tax:”+taxPercentage);
}
}
class Seller implements Tax{
private String location;
private double taxPercentage;
public Seller(String location, double taxPercentage){
[Link]=location;
[Link]=taxPercentage;
}
public double calculateTax(double price){
double Tax2=price * taxPercentage /100;
return Tax2;
Page 39
}
public void displaySeller(){
[Link](“Location:”+location);
[Link](“Tax:”+taxPercentage);
}
}
class TesterTax{
public static void main(String args[]){
purchaseDetails p=new purchaseDetails(109, “Gold”,3.66);
Seller s=new Seller(“Kalaburagi”, 4.22);
[Link]();
[Link](“Tax Percentage:”+[Link](5000));
[Link]();
[Link](“Tax Percentage:”+[Link](4000));
}
}
Output:
ID:109
Type: Gold
Tax:3.66
Tax Percentage:183.0
Location: Kalaburagi
Tax:4.22
Tax Percentage:168.8
Page 40
Week-11
1. Design a oops with java program using a Final Variable in a Class:
Code:
class Employee{
final double Bonus=500;
String name;
double salary;
public Employee(String name, double salary){
[Link]=name;
[Link]=salary;
}
public double totalSalary(){
double total=salary + Bonus;
return total;
}
public void display(){
[Link]( “Name:”+name);
[Link](“Basic Salary:”+salary);
[Link](“Bonus:”+Bonus);
}
}
class TesterEmployee{
public static void main(String args[]){
Employee e1=new Employee(“Rahul”,2500.87);
Employee e2=new Employee(“Radha”,1400.26);
[Link]();
[Link](“Total salary:”+[Link]());
[Link]();
[Link](“Total Salary:”+[Link]());
}
}
Page 41
Output:
Name: Rahul
Basic Salary:2500.87
Bonus:500.0
Total salary:3000.87
Name: Radha
Basic Salary:1400.26
Bonus:500.0
Total Salary:1900.26
Page 42
2. Design a oops with java program using static:
CODE:
class Student{
int id;
String name;
static String college=”GPT”;
public Student(int id,String name){
[Link]=id;
[Link]=name;
}
public void display(){
[Link](“ID:”+id);
[Link](“Name:”+name);
[Link](“College:”+college);
}
}
class TesterStudent {
public static void main(String args[]){
Student s1=new Student(1,”ABC”);
Student s2=new Student(2,”XYZ”);
[Link]();
[Link]();
}
}
Output:
ID : 1
Name : ABC
College : GPT
ID : 2
Name : XYZ
College : GPT
Page 43
Week-12
[Link] a oops with java program using setter and getter for car
class:
CODE:
class Car{
private String brand;
private String model;
private int year;
public void setBrand(String b){
brand=b;
}
public void setModel(String m){
model=m;
}
public void setYear(int y){
year=y;
}
public String getBrand(){
return brand;
}
public String getModel(){
return model;
}
public int getYear(){
return year;
}
}
class TesterCar{
public static void main(String args[]){
Car c=new Car();
[Link](“Toyota”);
[Link](“Fortuner”);
[Link](2022);
Page 44
[Link](“This car is a”+ [Link]() + [Link]() + [Link]());
}
}
Output:
ID:109
Type: Gold
Tax:3.66
Tax Percentage:183.0
Location: Kalaburagi
Tax:4.22
Tax Percentage:168.8
Page 45
Week-13
Develop a Java application that connects to a MySQL database using
JDBC and retrieves Student details from a table named "Student".
Provide the code solution and the output of the application
CODE:
import [Link].*;
class Example{
public static void main(String args[]){
try{
[Link](“[Link]”);
Connection
con=[Link](“jdbc:mysql://localhost:33
06/College”,”root”,””);
Statement st=[Link]();
ResultSet rs=[Link](“Select * from College”);
while([Link]()){
String id=[Link](“ID”);
String name=[Link](“Name”);
[Link](“Name:”+name+”Id:”+id);
}
[Link]();
[Link]();
[Link]();
}
catch(Exception e){
[Link](e);
}
}
}
Output:
Page 46
Page 47