0% found this document useful (0 votes)
9 views60 pages

Java Record 495

The document provides an introduction to core Object-Oriented Programming (OOP) concepts in Java, including encapsulation, inheritance, polymorphism, and abstraction. It outlines the steps to run a Java program, describes the program logic flow, and presents various experiments covering basic Java programming, operators, control statements, iteration, and arrays. Each week focuses on specific objectives, with practical coding examples demonstrating the concepts learned.

Uploaded by

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

Java Record 495

The document provides an introduction to core Object-Oriented Programming (OOP) concepts in Java, including encapsulation, inheritance, polymorphism, and abstraction. It outlines the steps to run a Java program, describes the program logic flow, and presents various experiments covering basic Java programming, operators, control statements, iteration, and arrays. Each week focuses on specific objectives, with practical coding examples demonstrating the concepts learned.

Uploaded by

poojikunibilli2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1

INTRODUCTION:

 Core OOP Concepts in Java


Java is built on four primary pillars that organize how code is structured:

Encapsulation: Wrapping data (variables) and code (methods) together as


a single unit (a Class) and restricting direct access using private modifiers.

Inheritance: Allowing a new class (subclass) to acquire the properties and


methods of an existing class (superclass) using the extends keyword.

Polymorphism: The ability of an object to take on many forms (e.g., Method


Overloading or Method Overriding).

Abstraction: Hiding complex implementation details and showing only the


necessary features of an object using abstract classes or interfaces

 How to Run a Java Program (The Steps)


Java follows a “Write Once, Run Anywhere” (WORA) philosophy. This happens
through a two-step process: compilation and interpretation.

Step-by-Step Execution:

Write: Create your file with a .java extension (e.g., [Link]).

Compile: Use the Java Compiler (javac). This converts your human-readable
code into Bytecode (a .class file).

Command: javac [Link]

Run: Use the Java Virtual Machine (JVM) to execute the bytecode.

Command: java MyProgram

Check Output: The JVM interacts with your operating system to display
results in the console/terminal.

 Program Logic Flow Chart

The flow of a standard Java program follows a predictable path from the
moment you hit “Run.”

The Logic Lifecycle:

Start: The JVM searches for the main method: public static void
main(String[] args).

23331A0495
2

Object Creation: If the program ses OOP, the main method instantiates
objects from classes.

Memory Allocation: The new keyword allocates memory on the “Heap.”

Method Calls: The program jumps to specific methods to perform tasks.

Conditional/Looping: The program checks for logic gates (if/else) or


repetitions (for/while).

Termination: Once the main method finishes, the program exits.

23331A0495
3

WEEK 1
INTRODUCTION TO JAVA AND STRUCTURED
PROGRAMMING
OBJECTIVE: To introduce the foundations of Object-Oriented Programming
(OOP) and the core components of the Java Platform.

DESCRIPTION: a brief introduction to Java and structured programming


basics—setup, first programs, and core language elements. You start with
Hello World, writing a minimal program that prints “Hello, World!” to learn
class structure, the main method, and `[Link]`. Then you work
with the Scanner class, using `[Link]` to read user input from the
console and introducing object creation and basic interactive I/O. Next, you
explore data types, demonstrating Java’s primitive types (byte, short, int,
long, float, double, char, boolean) by declaring variables and printing their
values. Finally, you practice type conversion by casting from floating-point to
integer, explaining truncation and how Java handles narrowing conversions.

EXPERIMENT 1 :

AIM: a simple Java program that prints ‘Hello, World!’ to the console.

CODE:

Class helloworld

23331A0495
4

Public static void main(String args[])

[Link](“helloworld”);

OUTPUT:

EXPERIMENT-2:

AIM:Write a Java program to demonstrate all primitive data types.

CODE:

Class details {

Public static void main(String args[])

Int a = 495;

Double b = 8.5;

String c = “poojitha”;

[Link](“reg number is”+a);

[Link](“cgpa is”+b);

[Link](“name is”+c);

OUTPUT:

23331A0495
5

EXPERIMENT-3:

AIM:Write a Java program that takes user input using the Scanner class and
prints the entered data.

CODE:

Import [Link];

Class detailsscan {

Public static void main(String args[])

Scanner sc=new Scanner([Link]);

[Link](“enter name”);

String name=[Link]();

[Link](“enter age”);

Int age=[Link]();

[Link](“enter marks”);

Float marks=[Link]();

OUTPUT:

EXPERIMENT-4:

AIM:Implement a Java program that converts a floating-point number to an


integer.

CODE:

Class type {

Public static void main (String args[]){

23331A0495
6

Byte b=30;

Short s=b;

Int i=s;

Long l=I;

Float f=s;

Double d=f;

//narrowing conversion

/*double d=123.456;

Float f=(float)d;

Long l=(long)f;

Int i=(int)l;

Short s=(short)I;

Byte b=(byte)s;*/

[Link](“widening conversion :” +b +s +I +l +f +d);

/*[Link](“narrowing conversion :”+d+f+l+i+s+b);*/

OUTPUT:

CONCLUSION:In this experiment ,introduced to Java programming and


structured programming concepts. Programs for Hello World, user input using
Scanner, demonstration of primitive data types, type conversion from
floating-point to integer, and use of the final keyword were implemented
successfully. The execution verified correct output and understanding of
basic syntax, data handling, and constants. Thus, Week 1 fundamentals were
completed.

23331A0495
7

WEEK 2
INTRODUCTION TO OPERATORS AND SELECTION CONTROL
STATEMENTS

OBJECTIVE: To explore the core concepts of Java operators


(arithmetic, relational, and logical) and understand fundamental
selection control structures using if-else and the ternary operator.

DESCRIPTION: This week introduces the language’s essential


tools for performing calculations and making decisions within a
program. It starts with implementing various operators—including
arithmetic, relational for comparisons, and logical for complex
conditions. Next, it demonstrates conditional logic by finding the
largest of three numbers using multi-way if-else statements.
Finally, it teaches how to optimize code for simple conditions
using Java’s ternary operator.

EXPERIMENT-1:

AIM:Implement a Java program that uses arithmetic, relational, and logical


operators.

23331A0495
8

CODE:

Import [Link];

Class operators

Public static void main(String args[])

Scanner sc = new Scanner([Link]);

// arithmetic operators

[Link](“Enter two integers for arithmetic operations:”);

Int a = [Link]();

Int b = [Link]();

[Link](“a + b = “ + (a + b));

[Link](“a – b = “ + (a – b));

[Link](“a * b = “ + (a * b));

[Link](“a / b = “ + (a / b));

[Link](“a % b = “ + (a % b));

// relational operators

[Link](“\nEnter two integers for relational operations:”);

Int r1 = [Link]();

Int r2 = [Link]();

[Link](“r1 == r2 : “ + (r1 == r2));

[Link](“r1 != r2 : “ + (r1 != r2));

[Link](“r1 >= r2 : “ + (r1 >= r2));

[Link](“r1 <= r2 : “ + (r1 <= r2));

//logical operators

[Link](“\nEnter two boolean values (true/false):”);

Boolean l1 = [Link]();

23331A0495
9

Boolean l2 = [Link]();

[Link](“l1 && l2 = “ + (l1 && l2));

[Link](“l1 || l2 = “ + (l1 || l2));

[Link](“!l1 = “ + (!l1));

OUTPUT:

EXPERIMENT -2:

AIM:Write a Java program to find the largest of three numbers using if-else
statements.

CODE:

Import [Link];

Class largest

Public static void main(String args[])

Scanner sc = new Scanner([Link]);

23331A0495
10

[Link](“Enter three numbers: “);

Int a = [Link]();

Int b = [Link]();

Int c = [Link]();

If (a >= b && a >= c)

[Link](“Largest number is: “ + a);

Else if (b >= a && b >= c)

[Link](“Largest number is: “ + b);

Else

[Link](“Largest number is: “ + c);

OUTPUT:

EXPERIMENT-3:

AIM:Use the ternary operator to implement a simple conditional check.

CODE:

Class ternary

23331A0495
11

Public static void main(String args[])

Int age = 16;

String result = (age >= 18) ? “Eligible” : “Not Eligible”;

[Link](result);

OUTPUT:

CONCLUSION:This experiment explored operators and selection control


statements in Java. Programs implementing arithmetic, relational, and logical
operators, finding the largest of three numbers using if-else ladders, and
applying the ternary operator for conditional checks executed successfully.
Outputs confirmed proper decision-making logic and operator usage. Week 2
objectives were achieved.

23331A0495
12

WEEK 3
CONTROL STATEMENTS – ITERATION

OBJECTIVE: To master the distinct types of looping constructs in Java (for,


while, do-while) for executing code repeatedly.

DESCRIPTION: The focus shifts to implementing iteration. This includes


using for loops to iterate over a defined range (e.g., printing numbers), while
loops for indefinite loops with unknown iteration counts (e.g., calculating
factorial), and implementing the Fibonacci sequence. It will also demonstrate
how to create user-friendly, menu-driven programs using the do-while loop.

EXPERIMENT -1:

AIM:Write a Java program that prints all even numbers between 1 and 100
using a for loop.

CODE:

Class even

23331A0495
13

Public static void main(String args[])

For (int I = 1; I <= 100; i++)

If (I % 2 == 0)

[Link]( I + “ “ );

OUTPUT:

EXPERIMENT -2:

AIM:Create a Java program that calculates the factorial of a given number


using a while loop.

CODE:

Import [Link];

Class factorial

Public static void main(String args[])

Scanner sc = new Scanner([Link]);

[Link](“Enter a number: “);

Int n = [Link]();

23331A0495
14

Int fact = 1;

Int I = 1;

While (I <= n)

Fact = fact * I;

I++;

[Link](“Factorial of “ + n + “ is: “ + fact);

OUTPUT:

EXPERIMENT -3:

AIM:Write a JAVA program to display the Fibonacci sequence.

CODE:

Import [Link];

Class fibonacci

Public static void main(String args[])

Scanner sc = new Scanner([Link]);

[Link](“Enter number of terms: “);

Int n = [Link]();

23331A0495
15

Int a = 0, b = 1;

Int I = 1;

[Link](“Fibonacci Series: “);

While (I <= n)

[Link](a + “ “);

Int next = a + b;

A = b;

B = next;

I++;

OUTPUT:

EXPERIMENT-4:

AIM:Implement a menu-driven program using a do-while loop.

CODE:

Import [Link];

Class dowhile

Public static void main(String args[])

Scanner sc = new Scanner([Link]);

23331A0495
16

Int choice;

Do

[Link](“\n--- MENU ---“);

[Link](“1. Addition”);

[Link](“2. Subtraction”);

[Link](“3. Multiplication”);

[Link](“4. Division”);

[Link](“5. Exit”);

[Link](“Enter your choice: “);

Choice = [Link]();

If (choice >= 1 && choice <= 4)

[Link](“Enter two numbers: “);

Int a = [Link]();

Int b = [Link]();

Switch (choice)

Case 1:

[Link](“Result = “ + (a + b));

Break;

Case 2:

[Link](“Result = “ + (a – b));

Break;

Case 3:

[Link](“Result = “ + (a * b));

Break;

23331A0495
17

Case 4:

If (b != 0)

[Link](“Result = “ + (a / b));

Else

[Link](“Division by zero not allowed”);

Break;

Else if (choice != 5)

[Link](“Invalid choice”);

While (choice != 5);

[Link](“Program exited”);

OUTPUT:

23331A0495
18

CONCLUSION : This experiment covered Java looping constructs. Programs


to print the Fibonacci series, check whether a number is prime, and
demonstrate break and continue while looping through natural numbers
executed correctly. Outputs validated loop control and termination behavior.
Week 3 objectives were completed.

WEEK 4
ARRAYS

OBJECTIVE: To understand and implement data storage using single-


dimensional and two-dimensional arrays in Java, along with basic data
manipulation techniques.

DESCRIPTION: Labs will focus on declaring, initializing, and traversing


arrays. They will demonstrate how to perform common tasks such as
searching for an element within an array and reversing array elements.
Additionally, the week covers working with multidimensional arrays,
culminating in a program to perform matrix multiplication.

23331A0495
19

EXPERIMENT-1:

AIM:Write a Java program to reverse a one-dimensional array of integers.

CODE:

Import [Link];

Class reverse{

Public static void main(String args[])

Scanner sc=new Scanner([Link]);

[Link](“enter no of elements”);

Int n=[Link]();

Int arr[]=new int[n];

[Link](“enter array elements”);

For(int i=0;i<n;i++)

Arr[i]=[Link]();

[Link](“reversed array:”);

23331A0495
20

For(int i=n-1;i>=0;i--)

[Link](arr[i]+” “);

OUTPUT:

EXPERIMENT -2:

AIM:Implement a Java program to find matrix multiplication using two-

Dimensional arrays.

CODE:

Import [Link];

Class matrix {

Public static void main(String args[]) {

Scanner sc=new Scanner([Link]);

Int[][]a=new int[2][2];

Int[][]b=new int[2][2];

Int[][]c=new int[2][2];

[Link](“enter elements of first matrix:”);

23331A0495
21

For(int i=0;i<2;i++){

For(int j=0;j<2;j++){

A[i][j]=[Link]();

[Link](“enter elements of second matrix:”);

For(int i=0;i<2;i++)

For(int j=0;j<2;j++)

B[i][j]=[Link]();

For(int i=0;i<2;i++)

For(int j=0;j<2;j++)

C[i][j]=0;

For(int k=0;k<2;k++)

C[i][j]+=a[i][k]*b[k][j];

[Link](“resultant matrix:”);

For(int i=0;i<2;i++)

23331A0495
22

For(int j=0;j<2;j++)

[Link](c[i][j]+” “);

[Link]();

OUTPUT:

EXPERIMENT -3:

AIM:Write a Java program to search for an element in an array.

CODE:

Import [Link];

Class search {

Public static void main(String args[]) {

Scanner sc=new Scanner([Link]);

[Link](“enter no of elements”);

Int n=[Link]();

Int arr[]=new int[n];

23331A0495
23

[Link](“enter array elements”);

For(int i=0;i<n;i++)

Arr[i]=[Link]();

[Link](“enter element to search:”);

Int key=[Link]();

Boolean found=false;

For(int i=0;i<n;i++)

If(arr[i]==key)

[Link](“element found at position: “ +(i+1));

Found=true;

Break;

If(!found)

[Link](“element not found”);

23331A0495
24

OUTPUT:

CONCLUSION:This experiment focused on array operations in Java. Programs


to sum array elements, search for a value, and sort the array executed
successfully. Outputs confirmed correct indexing, traversal, and manipulation
of arrays. Week 4 array objectives were completed.

WEEK 5
CLASSES AND METHODS

OBJECTIVE: To understand the foundation of Object-Oriented Programming


(OOP) in Java by creating classes, defining attributes and behaviors, and
invoking methods.

23331A0495
25

DESCRIPTION: This week marks the transition into full OOP concepts.
Students will learn to define classes with fields (attributes) and methods
(behaviors). The labs cover creating objects (instantiating the class) and
calling their methods to calculate values like rectangle area. Furthermore, it
introduces method overloading, demonstrating how multiple methods can

have the same name with different parameters to handle varying input types
(e.g., calculating areas of different shapes).

EXPERIMENT -1:

AIM: Create a class with fields and methods, then instantiate and use it.

CODE:

Class fields {

String name;

Int id;

Int marks;

Void display()

[Link](“Name: “ + name);

[Link](“ID: “ + id);

[Link](“Grade: “ +marks);

23331A0495
26

Public static void main(String args[])

Fields s1 = new fields();

[Link]=495;

[Link]=”poojitha”;

[Link]=960;

[Link]();

OUTPUT:

EXPERIMENT -2:

AIM:Create a program that returns the area of different shapes (circle,


square, rectangle) using method overloading.

CODE:

Class shapes

Double area(double radius)

Double d=3.14*radius*radius;

Return d;

Int area(int side){

Int a =side*side;

23331A0495
27

Return a;

Int area(int l,int b)

Int rect = l*b;

Return rect;

Public static void main(String args[])

Shapes obj=new shapes();

[Link]([Link](5.5));

[Link]([Link](5));

[Link]([Link](10,5));

OUTPUT:

EXPERIMENT-3:

AIM:Create a program that returns the area of different shapes (circle,


square, rectangle) using method overloading.

CODE:

Class Rectangle

Void Area(int length, int breadth)

23331A0495
28

Int area = length * breadth;

[Link](“Area of Rectangle = “ + area);

Public static void main(String args[])

Rectangle r = new Rectangle();

[Link](10, 5);

OUTPUT:

CONCLUSION :This experiment implemented classes and methods in Java.


Programs defining a class with methods and demonstrating method calls
executed successfully. Outputs confirmed object creation, method invocation,
and proper use of instance members. Week 5 classes and methods
objectives were completed.

WEEK 6
CONSTRUCTORS, this KEYWORD, AND GARBAGE
COLLECTION

23331A0495
29

OBJECTIVE: To learn techniques for object initialization using


constructors, resolve scope issues with the this keyword, and understand
Java’s automatic memory management system.

DESCRIPTION: This module covers different ways to initialize


newly created objects by defining parameterized constructors.
The labs will teach students how to use the this keyword
effectively within methods and constructors to distinguish
between instance variables and local variables (variable
shadowing). Lastly, it explores memory management concepts
with exercises related to [Link]() and the garbage collection

process
EXPERIMENT -1:
AIM:Implement a class with parameterized constructors and demonstrate
object initialization.

CODE:

Class Student {

String name;

Int id;

Int marks;

23331A0495
30

Student(String initial, int rollno,int grade) {

Name=initial;

Id=rollno;

Marks=grade;

Void display() {

[Link](“Name: “ + name);

[Link](“ID: “ + id);

[Link](“Grade: “ +marks);

Public static void main(String args[]) {

Student s = new Student(“Pooji”, 495, 960);

[Link]();

OUTPUT:

EXPERIMENT -2;

AIM:Use ‘this’ keyword to resolve variable shadowing within methods and


constructors.

CODE:

Class thisk {

String name;

Int id;

Int marks;

23331A0495
31

Thisk(String name, int id,int marks) {

[Link]=name;

[Link]=id;

[Link]=marks;

Void display() {

[Link](“Name: “ + name);

[Link](“ID: “ + id);

[Link](“Grade: “ +marks);

Public static void main(String args[]) {

Thisk s = new thisk(“Pooji”, 495, 960);

[Link]();

OUTPUT:

EXPERIMENT -3:

AIM:Write a program that simulates garbage collection using [Link]() and


observe the results.

CODE:

Class mobile {

Int price;

String name;

Int ram;

23331A0495
32

Mobile(int p,String n,int r) {

Price=p;

Name=n;

Ram=r;

Void display() {

[Link](price+” “+name+” “+ram);

Public static void main(String args[]) {

Mobile m1 = new mobile(20000,”samsung”,64);

[Link]();

[Link]();

[Link]();

OUTPUT:

CONCLUSION: This experiment examined constructors, the this keyword, and


garbage collection in Java. Programs using default and parameterized
constructors, demonstrating this for field reference, and illustrating object
eligibility for garbage collection executed successfully. Outputs confirmed
proper initialization, disambiguation, and memory management concepts.
Week 6 objectives were completed.

WEEK 7

23331A0495
33

INHERITANCE AND POLYMORPHISM

OBJECTIVE: To master key OOP principles of inheritance and


polymorphism for code reuse and flexibility.

DESCRIPTION: The labs demonstrate how to establish hierarchical


relationships by creating superclasses and subclasses to demonstrate basic
inheritance. Students will learn how subclasses can override methods
inherited from parent classes to provide custom implementations and
explore the distinction between calling subclass methods versus parent class
methods. The use of the super keyword to access parent class variables,
methods, and constructors is also practiced.

EXPERIMENT-1.A:

AIM:Single inheritance -student &marks .create a base class student


(name,roll no ) &derived class marks (sub1,sub2,total). Display student
details and total marks.

CODE:

Class Student

String name = “Poojitha”;

23331A0495
34

Int rollNo = 495;

Class Marks extends Student

Int sub1 = 75;

Int sub2 = 85;

Int total;

Void display()

Total = sub1 + sub2;

[Link](“Name: “ + name);

[Link](“Roll No: “ + rollNo);

[Link](“Subject 1: “ + sub1);

[Link](“Subject 2: “ + sub2);

[Link](“Total Marks: “ + total);

Class singleinheritance

Public static void main(String args[])

Marks m = new Marks();

[Link]();

23331A0495
35

OUTPUT:

EXPERIMENT -1.B:

AIM:Single inheritance -shape & rectangle . Base class: shape – contains


length and width derived class:rectangle-calculate area

CODE:

Class shape

Int length=14;

Int width=2;

Class Rectangle extends shape

Int area;

Void CalculateArea();

Area=length*width;

[Link](“length: “ + length);

[Link](“width“ + width);

[Link](“Area of rectangle: “ +area);

Class Shape

23331A0495
36

Public static void main(String args[])

Rectangle r=new Rectangle();

[Link]();

OUTPUT:

EXPERIMENT -1.C:

AIM: hierarchical inheritance ..vehicle example : base class- vehicle ,derived


class -car bike display details from all sub classes.

CODE:

Class Vehicle

String brand = “Honda”;

Int year = 2023;

Class Car extends Vehicle

Int doors = 4;

Void displayCar()

[Link](“Car Details”);

[Link](“Brand: “ + brand);

23331A0495
37

[Link](“Year: “ + year);

[Link](“Doors: “ + doors);

[Link]();

Class Bike extends Vehicle

String type = “Sports”;

Void displayBike()

[Link](“Bike Details”);

[Link](“Brand: “ + brand);

[Link](“Year: “ + year);

[Link](“Type: “ + type);

Class hierarchial

Public static void main(String args[])

Car c = new Car();

Bike b = new Bike();

[Link]();

[Link]();

23331A0495
38

OUTPUT:

EXPERIMENT -1.D:

AIM: multilevel inheritance with person employee manager…person has :


name, age;employee has: empid ,salary; manager has department. display
details using manager object.

CODE:

Class Person {

String name;

Int age;

Class Employee extends Person {

Int empId;

Int salary;

Class Manager extends Employee {

String department;

Void display() {

Name = “john”;

Age = 40;

empId = 1;

salary = 10000;

23331A0495
39

department = “sales”;

[Link](“Name: “ + name);

[Link](“Age: “ + age);

[Link](“ID: “ + empId);

[Link](“Salary: “ + salary);

[Link](“Department: “ + department);

Class MultilevelInheritance {

Public static void main(String args[]) {

Manager m = new Manager();

[Link]();

OUTPUT:

EXPERIMENT -2:

AIM:Override a method in sub class and call it from main method.

CODE:

Class Bank {

Void interest() {

Int interest = 30;

[Link](“Bank Interest: “ + interest);

23331A0495
40

Class IOB extends Bank {

Void interest() {

Int interest = 40;

[Link](“IOB Interest: “ + interest);

Class BANK {

Public static void main(String args[]) {

Bank obj=new Bank();

Bank obj1 = new IOB();

[Link]();

[Link]();

OUTPUT:

EXPERIMENT -3:

AIM:Use super keyword to call the parent class variable method, constructor.

CODE:

Class Bank{

void interest(){

Int interest=30;

[Link](“Bank Interest:”+interest);

23331A0495
41

Class IOB extends Bank{

Void interest(){

[Link]();

Int interest=40;

[Link](“IOB Interest:”+interest);

Class BANKS{

Public static void main(String args[]){

Bank obj1=new IOB();

[Link]();

OUTPUT:

EXPERIMENT-4:

AIM:Final keyword with inheritance.

CODE:

Class Bank {

Final void interest() {

Int interest = 30;

[Link](“Bank Interest: “ + interest);

23331A0495
42

Class IOB extends Bank {

Void interest() {

Int interest = 60;

[Link](“IOB Interest: “ + interest);

Class s {

Public static void main(String args[]) {

Bank obj = new IOB();

[Link]();

OUTPUT:

CONCLUSION:This experiment demonstrated inheritance in Java, including


single and multilevel hierarchies and use of super to invoke parent methods.
Programs executed successfully, showing subclasses extending superclass
fields and behaviors while allowing specialized functionality. Outputs
confirmed correct code reuse, method overriding, and hierarchical
initialization. Week 7 inheritance objectives were completed with expected
results.

23331A0495
43

WEEK 8
ABSTRACT CLASSES AND INTERFACES

OBJECTIVE: To understand how abstract classes and interfaces are used


to define contracts and enable loose coupling, as well as handle multiple
inheritance in Java.

DESCRIPTION: This week covers techniques for implementing design


structures using abstract classes with abstract and concrete methods. The
labs focus on implementing interfaces within classes and explore scenarios
where multiple interfaces can be implemented to solve problems related to
multiple inheritance, effectively illustrating how interfaces create a
separation between definition and implementation.

EXPERIMENT -1:

AIM:Write an abstract class with an abstract method and a concrete method.

CODE:

Abstract class student

23331A0495
44

Abstract void show();

Void display()

[Link](“pooji”);

Class grade extends student

Void show()

[Link](“s”);

Abstract class demo

Public static void main(String args[])

Student s=new grade();

[Link]();

[Link]();

OUTPUT:

23331A0495
45

EXPERIMENT -2:

AIM: Implement an interface and demonstrate how to implement in a class.

CODE:

Interface A

Void a();

Interface B extends A

Void b();

Class C implements B

Public void a()

[Link](“this is a”);

Public void b()

[Link](“this is b”);

Public static void main(String args[])

C obj=new C();

Obj.a();

Obj.b();

23331A0495
46

OUTPUT:

EXPERIMENT -3:

AIM:Create a scenario where Interfaces solve the multiple inheritance


problem.

CODE:

Interface student

Void study();

Interface employee extends student

Void work();

Class person implements student,employee

Public void study()

[Link](“studying”);

Public void work()

[Link](“working”);

23331A0495
47

Public static void main(String args[])

Person p=new person();

[Link]();

[Link]();

OUTPUT :

CONCLUSION:

Programs implementing an abstract class with abstract and concrete


methods, a standard interface with a class implementation, and a scenario
using interfaces to resolve multiple inheritance executed successfully.
Outputs confirmed abstraction, contract enforcement, and how interfaces
enable a form of multiple inheritance. Week 8 objectives were completed.

23331A0495
48

WEEK 9
EXCEPTION HANDLING

:
OBJECTIVE To learn how to make Java programs more robust and error-
resistant by robustly handling runtime errors.

DESCRIPTION : Students will explore the mechanisms for managing


unexpected errors in programs. This includes understanding the basic try-
catch structure to handle single exceptions and moving toward handling
multiple specific exceptions efficiently using multiple catch clauses.
Additionally, the labs cover the implementation of custom exception classes
to handle unique, application-specific error conditions effectively.

EXPERIMENT -1:

AIM:Write a program that demonstrates basic exception handling using try


and catch blocks .

CODE

Import [Link];

Class exception{

Public static void main(String args[]){

23331A0495
49

Scanner sc = new Scanner([Link]);

[Link](“Enter two values”);

Int a = [Link]();

Int b = [Link]();

Try {

Int c = b / (b – a);

[Link](“Result: “ + c);

Catch (ArithmeticException e) {

[Link](“Division by zero error”);

[Link](“Value of a: “ + a);

[Link](“Value of b: “ + b);

OUTPUT:

EXPERIMENT -2:

AIM: Implement a program that handles multiple exceptions using multiple


catch blocks.

CODE:

Import [Link].*;

Class MultiException {

Public static void main(String args[]) {

23331A0495
50

Scanner sc = new Scanner([Link]);

Try {

[Link](“Enter a number:”);

Int a = [Link]();

Int arr[] = {10, 20, 30};

[Link](“Enter array index:”);

Int index = [Link]();

[Link](“Array Element: “ + arr[index]);

String str = null;

[Link]([Link]());

Catch (InputMismatchException e) {

[Link](“Input Mismatch Exception”);

Catch (ArrayIndexOutOfBoundsException e) {

[Link](“Array Index Out Of Bounds Exception”);

Catch (NullPointerException e) {

[Link](“Null Pointer Exception”);

[Link](“Program Ended”);

Import [Link];

Class NegativeNumberException extends Exception

NegativeNumberException(String msg)

23331A0495
51

Super(msg);

OUTPUT:

EXPERIMENT -3:

AIM: Create a custom exception Class and use it to handle specific errors in a
program.

CODE:

Class Test

Public static void main(String args[])

23331A0495
52

Scanner sc = new Scanner([Link]);

[Link](“Enter a number: “);

Int num = [Link]();

Try

If(num < 0)

Throw new NegativeNumberException(“Number should not be


negative”);

[Link](“Number is: “ + num);

Catch(NegativeNumberException e)

[Link](“Custom Error: “ + [Link]());

OUTPUT:

CONCLUSION:

Programs demonstrating basic try-catch, multiple catch clauses, and a


custom exception class to handle a specific error executed successfully.
Outputs verified controlled flow during errors, proper matching of exception
types, and user-defined error signaling. Week 9 objectives were completed.

23331A0495
53

WEEK 10
MULTITHREADING
OBJECTIVE: To introduce the concepts of multithreading to achieve
concurrent execution and manage race conditions.

DESCRIPTION: This week covers techniques for parallel programming in


Java. The labs start by creating basic threads by extending the Thread class.
They then move into complex topics such as understanding the various
states in a thread life cycle and managing transitions. Furthermore, it
introduces critical concurrency concepts by demonstrating how to use thread
synchronization effectively to prevent data corruption from multiple threads
accessing shared resources simultaneouslyAIM: implement a thread with
extending thread class .

EXPERIMENT-1:

CODE:

Class MyThread extends Thread

Public void run()

23331A0495
54

For(int I = 0; I < 3; i++)

[Link](“watching video”);

Class thread{

Public static void main(String args[]) {

MyThread obj = new MyThread();

[Link]();

For(int I = 0; I < 3; i++)

[Link](“downloading file”);

OUTPUT:

EXPERIMENT -2:

AIM:Create a program that demonstrates thread life cycle and state


transitions.

CODE:

Class LifeCycleDemo extends Thread{

23331A0495
55

Public void run(){

Try{

[Link](“thread is running”);

[Link](2000);

Catch(InterruptedException e){

[Link]€;

Public static void main(String args[]) throws InterruptedException{

LifeCycleDemo t1=new LifeCycleDemo();

[Link](“state after creation :”+ [Link]());

[Link]();

[Link](“state after start() :”+ [Link]());

[Link](2000);

[Link](“state during sleep :”+ [Link]());

[Link]();

[Link](“state after completion :”+ [Link]());

OUTPUT:

EXPERIMENT-3:

23331A0495
56

AIM: Implement thread synchronisation to avoid race conditions in a multi


threaded environment.

CODE:

Class Bank {

Int balance = 5000;

Synchronized void withdraw(int amount) {

If(balance >= amount) {

[Link](“Withdrawing “ + amount);

Balance = balance – amount;

[Link](“Balance = “ + balance);

} else {

[Link](“Not enough balance”);

Class MyThread extends Thread {

Bank b;

MyThread(Bank obj) {

B = obj;

Public void run() {

[Link](3000);

Class TS {

Public static void main(String args[]) {

Bank account = new Bank();

23331A0495
57

MyThread t1 = new MyThread(account);

MyThread t2 = new MyThread(account);

[Link]();

[Link]();

OUTPUT:

CONCLUSION:Programs creating threads by extending Thread, displaying


thread lifecycle states, and applying synchronization to prevent race
conditions executed successfully. Outputs confirmed concurrent execution
and safe access to shared resources. Week 10 objectives were completed.

WEEK 11

23331A0495
58

EVENT HANDLING AND AWT


OBJECTIVE:To understand the fundamentals of the Abstract Window Toolkit
(AWT) and learn how to create a basic Graphical User Interface (GUI)
containing interactive components like buttons, text fields, and labels.

DESCRIPTION:The Abstract Window Toolkit (AWT) is Java’s original platform-


dependent windowing, graphics, and user-interface widget toolkit. In this
experiment, we use the Frame class to create a window. We then populate
this window with:

Label: To display static text.

TextField: To allow user input.

Button: To trigger an action.

EXPERIMENT-1:

AIM: To write a simple AWT program that displays a window containing a


Button, a TextField, and a Label

CODE:import [Link].*;

Import [Link].*;

Public class Week11GuiBase extends Frame {

23331A0495
59

Public Week11GuiBase() {

// 1. Setting the layout (FlowLayout arranges components in a line)

setLayout(new FlowLayout());

// 2. Creating components

Label lblName = new Label(“Enter Name:”);

TextField txtName = new TextField(20);

Button btnSubmit = new Button(“Submit”);

// 3. Adding components to the Frame

Add(lblName);

Add(txtName);

Add(btnSubmit);

// 4. Frame settings

setTitle(“AWT Basic Window”);

setSize(300, 200);

setVisible(true);

// Closing the window properly

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

dispose();

Public static void main(String[] args) {

New Week11GuiBase();

OUTPUT:

23331A0495
60

CONCLUSION:By completing this program, we have successfully


demonstrated the creation of a functional GUI window using Java AWT. We
learned how to instantiate various UI components and add them to a
container (Frame) using a Layout Manager. This forms the foundation for
building more complex interactive desktop applications.

23331A0495

You might also like