0% found this document useful (0 votes)
4 views45 pages

Java Programs Record-1

The document outlines a course on Object Oriented Programming and Design using Java, detailing weekly practices and coding exercises. It includes instructions for setting up the Java environment, coding examples, and concepts such as data types, constructors, encapsulation, and control statements. Additionally, it provides sample code snippets and expected outputs for various programming tasks.

Uploaded by

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

Java Programs Record-1

The document outlines a course on Object Oriented Programming and Design using Java, detailing weekly practices and coding exercises. It includes instructions for setting up the Java environment, coding examples, and concepts such as data types, constructors, encapsulation, and control statements. Additionally, it provides sample code snippets and expected outputs for various programming tasks.

Uploaded by

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

Object

Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

Table of Contents

Sl. Page Date of


Practice Remarks
No. Numbers Submission

10

11

12

13

Signature of the Student Course Coordinator

Page 3|
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

WEEK -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

JAVA ENVIRONMENT SETUP


Install And Setup Java Environment [Practice Session]

You can download the JDK 8 from this link click (CTRL + CLICK) here  jdk software
or
You can download from [Link]
For this you have to create an account on Oracle

Step 1: click on the jdk-8u271-windows-x64 exe file and click on Next button

Page 4|
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

Step 2: if you want to change the path change it or else let it be default depends on your
convenience. And click on to Next

Step 3: This gives the window for installing wait till it goes to another window.
Step 4: if you want to change the JRE path you can change it or let it be default depends on
your convenience and click on to Next
Step 5: wait until it completes

Page 5|
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

Step 6: Now you have successfully installed JDK software only when you click Finish/close
button. After installing your JDK your work is not done Still lot more things to do……..

Setting up your path and classpath for making your programs run anywhere in the
drive

Open the command prompt and give javac command you get the above error as javac is not
recognized as an internal or external command. So you need to set the path.
Here how it goes…..

P a g e 62|023
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

Right click on My computer and click properties

Click on the advanced


tab… in the system
properties dialog box…
and then click for
environment variables..
Button

- 2023

Page 7|
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

If you don’t have path in the


display then go for new
otherwise go for Edit button

In this we don’t have path in


the display we’ll go for new

In this section you have 2 parts one is user variables and system variables

You need to type this

click the new tab in the user variable and type


C:\Program Files\Java\jdk1.8.0_271\bin next click on OK

- 2023

Page 8|
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

Because the jdk is installed in this path and you should take the full path till bin because bin
contains javac tool

Finally click on to Ok

Now open a Fresh command prompt and give javac –version and java -version

Now you can see the version displayed now you path and class path is set successfully and
you can run anywhere in your hard disk drives (c, d, e etc…)

 This [Link] is in the D: drive since you have already set the path and class path.
Any where you can compile and run..
 If you use any of the IDE’s like eclipse IDE, Netbeans IDE you no need to worry of
the path settings. This IDE’s will take care..
 But this path setting should be known by every one because if you sit working in any
of the system in any part of the world unfortunately you might not get this IDE
software at that moment. only option is to use notepad and set the path.

- 2023

Page 9|
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

How to Download and Install Eclipse to Run Java. Following is a step by step
guide to download and install Eclipse IDE:
Step 1) Installing Eclipse. Open your browser and type [Link]
Step 2) Click on "Download" button. Step3)
Click on "Download 64 bit" button. Step 4)
Click on "Download" button.

1) Java Program Example


class simple
{
public static void main(String args[])
{
[Link]("Hello Java");
}
}

Output :
Hello Java

- 2023

P a g e 10 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

WEEK – 2
1. Code, execute and debug programs in java
a. that uses different types of variables and datatypes;
2. Identify and resolve issues in the given code snippet

How to assign variable and datatypes


class JavaExample{
public static void main(String[] args){
byte b = 100;

short s = 200;
int num = 1331313131;
long l = 516515351;
double num1 = 22.4;
float num2 = 22.4f;

[Link](b);
[Link](s);
[Link](num);
[Link](l);
[Link](num1);
[Link](num2);

}
}

Output:
100
200

1331313131
516515351

- 2023

P a g e 11 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

22.4
22.4

How to read the elements through keyboard


import [Link];
public class Demo{
public static void main(String args[]){
Scanner scan = new Scanner([Link]);
[Link]("Enter any number :");
int num = [Link]();

[Link]();
[Link]("The number entered by user : "+num);

}
}

Output :
Enter any number :
63
The number entered by user : 63

- 2023

P a g e 12 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

WEEK - 3
1. Code, execute and debug programs in java
a. That uses different types of constructors
b. For expression evaluation
c. To perform autoboxing and unboxing
2. Identify and resolve issues in the given code snippet

/* Write a Java Program to define a class, describe its constructor, types of Constructors */

import [Link].*;
class student
{
String name;
int regno;
int marks1, marks2, marks3;

//null constructor
student()
{
name = "raju";

regno = 131234760;

marks1 = 23;
marks2 = 55;
marks3 = 100;

}
// parameterized constructor
student(String n, int r, int m1, int m2, int m3)
{
name = n;
- 2023

P a g e 13 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

regno = r;
marks1 = m1;
marks2 = m2;
marks3 = m3;

//copy constructor
student(student s)

{
name = [Link];
regno = [Link];
marks1 = s.marks1;
marks2 = s.marks2;
marks3 = s.marks3;

}
void display()

{
[Link](name+"\t"+regno+"\t"+marks1+"\t"+marks2+"\t"+marks3);
}
}

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

{
student s1 = new student();
student s2 = new student("John", 23422, 62,12,45);
student s3 = new student(s2);

- 2023

P a g e 14 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

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

}
}

Output :
raju 13123 23 55 100
John 23422 62 12 45
John 23422 62 12 45

3) b) AutoBoxing
Wrapper class Example: Primitive to Wrapper

//Java program to convert primitive into objects


//Autoboxing example of int to Integer

public class WrapperExample1


{
public static void main(String args[])
{
int a = 20;
Integer i = [Link](a);
Integer j = a;
[Link](a+" "+i+" "+j);

}
}

output :
20 20 20

- 2023

P a g e 15 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

Unboxing

Wrapper class Example: Wrapper to Primitive

//Java program to convert object into primitives


//Unboxing example of Integer to int
public class WrapperExample2
{

public static void main(String args[])


{
Integer a = new Integer(3);
int i = [Link]();

int j = a;
[Link](a+" "+i+" " +j);
}
}

Output :
333

- 2023

P a g e 16 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

WEEK - 4
1. Install memory monitoring tool and observe how JVM allocates memory
2. Memory allocation explanation through the programs

What are the different java monitoring tools?


There are the types of Java monitoring tools you could use to ensure peak JVM
performance. Standard Java Profilers give you visibility into all the JVM metrics
(memory, CPU, threads, garbage collection) and browse heap dumps for fine-grained
memory analysis.
The eclipse memory analyzer is the most prominent tool that is used to monitor
the java based application as it helps to analyze the memory.
The java heap usage of the application is continuously monitor in this tool. When a java
application is developed it contains objects and the objects created are stored in heap.

- 2023

P a g e 17 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

WEEK - 5
1. Code, execute and debug programs in java that uses different control
statements.
2. Implement Grading system
3. Identify and resolve issues in the given code snippet
Wap to accepts average from the user, calculates the grade and prints
import [Link];
public class CalculateStudentGrades{
public static void main(String agrs[]){
Scanner sc = new Scanner([Link]);
[Link]("Enter average of your marks(less than 100)::");
int average = [Link]();
char grade;

if(average>=80){
grade = 'A';
}else if(average>=60&&average<80){
grade = 'B';
}
else if(average>=40&&average<60){
grade = 'C';
}
else{
grade = 'D';
}

switch(grade){
case'A':

- 2023

P a g e 18 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

[Link]("Excellent!");
break;
case'B':
case'C':
[Link]("well done");
break;
case'D':
[Link]("Your passed");
case'F':
[Link]("Better try again");
break;
default:
[Link]("Invalid grade");
}
[Link]("Your grade i"+grade);
}
}

Output:-
Enter average of your marks(less than 100)::
22
Your passed
Better try again
Your grade D

- 2023

P a g e 19 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

WEEK - 6
1. Code, execute and debug programs in java
a. that uses encapsulation concept.
2. define class & Implement simple calculator and check compliance with
SRP

Encapsulation in Java

File: [Link]

//A Account class which is a fully encapsulated class.


//It has a private data member and getter and setter methods
class Account {
private long acc_no;
private String name, email;
private float amount;

public long getAcc_no() {


return acc_no;
}

public void setAcc_no(long acc_no) {


this.acc_no = acc_no;
}

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


[Link] = email;
}
- 2023

P a g e 20 |
public float getAmount() {
return amount;
}

public void setAmount(float amount) {


[Link] = amount;
}
}

public class Main {


public static void main(String[] args) {
Account acc = new Account();

acc.setAcc_no(21017);
[Link]("Meganadhan");
[Link]("mega@[Link]");
[Link](5000);

[Link](
acc.getAcc_no() + " " +
[Link]() + " " +
[Link]() + " " +
[Link]()
);
}

Output:-
21017 Meganadhan mega@[Link] 5000.0

- 2023

P a g e 21 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

- 2023

P a g e 22 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

2) Simple Calculator using Java switch Statement


import [Link];

class main{
public static void main(String args[]){
char operator;

Double number1,number2,result;

Scanner input = new Scanner([Link]);

[Link]("Choose an operator:+,-,*,or /");


operator = [Link]().charAt(0);

[Link]("Enter first number");

number1 = [Link]();

[Link]("Enter Second number");


number2 = [Link]();

- 2023

P a g e 23 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

switch(operator){
case'+':
result = number1+number2;
[Link](number1+"+"+number2+"="+result);
break;

case'-':

result = number1- number2;


[Link](number1+"-"+number2+"="+result);
break;

case'*':
result = number1* number2;
[Link](number1+"*"+number2+"="+result);
break;

case'/':
result = number1/ number2;
[Link](number1+"/"+number2+"="+result);
break;

default:
[Link]("Invalid operator!");
}

[Link]();
}
}

Output :-

- 2023

P a g e 24 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

Choose an operator:+,-,*,or /
*
Enter first number : 56
Enter Second number : 23
56.0*23.0=1288.0

- 2023

P a g e 25 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

WEEK - 7
1. Code, execute and debug programs in java that uses array concept
2. Code, execute and debug programs in java to perform string
manipulation

Program declare, instantiate, initialize array


//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.

class Testarray{
public static void main(String args[]){
int a[] = new int[5];
a[0] = 10;

a[1] = 20;
a[2] = 30;
a[3] = 40;
a[4] = 50;

for(int i = 0;i<[Link];i++)
[Link](a[i]);
}
}

Output:-
10

20

- 2023

P a g e 26 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

30

40

50

- 2023

P a g e 27 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

WEEK - 8
[Link], execute and debug programs in java that uses inheritance concept
[Link] simple calculator and check compliance with OCP
[Link] file parser and check compliance with SRP and OCP

class Animal {
void eat() {
[Link]("Eating...");
}
}

class Dog extends Animal {


void bark() {
[Link]("Barking...");
}
}

public class Main {


public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
}
}
Output:-
barking..
Eating...

- 2023

P a g e 28 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

b) Open/Closed Principle

Building a calculator app that might have several operations:


interface Shape {
Double calculateArea();
}

class Rectangle implements Shape {


Double length;
Double width;

public Double calculateArea() {


return length * width;
}
}

class Circle implements Shape {


Double radius;

public Double calculateArea() {


return (22.0 / 7) * radius * radius;
}
}

class AreaCalculator {
public Double calculateShapeArea(Shape shape) {
return [Link]();
}
}

public class Main {


public static void main(String[] args) {
Rectangle r = new Rectangle();
[Link] = 10.5;
[Link] = 20.0;

AreaCalculator a = new AreaCalculator();


[Link]([Link](r));

Circle c = new Circle();


[Link] = 1.0;
[Link]([Link](c));
}
}

- 2023

P a g e 29 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

Output:-
210.0
3.142857142857143

- 2023

P a g e 30 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

WEEK - 9
1. Code, execute and debug programs in java that uses
a. static binding
b. dynamic binding
Static binding
a) Wap for static binding
class Dog

{
private void eat ( )
{

[Link]("dog is eating...");
}

public static void main(String args[])


{

Dog d1=new Dog( );


[Link] ();
}
}

OUTPUT:
dog is eating...

- 2023

P a g e 31 |
- 2023

P a g e 32 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

Dynamic binding
Wap for dynamic binding

class Animal {
void eat() {
[Link]("Eating...");
}
}

class Dog extends Animal {


void bark() {
[Link]("Barking...");
}
}

public class Main {


public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
}
}
Output :-
dog is eating...

- 2023

P a g e 33 |
- 2023

P a g e 34 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

WEEK - 10
1. Code, execute and debug programs in java that uses
2. abstract class to achieve abstraction
[Link] to achieve abstraction
[Link] whether the given code snippet is correct according to abstraction
or not
Wap to execute Interface

public class Main {

interface Printable {
void print();
}

static class A implements


Printable {
public void print() {

[Link]("Hello");
}
}

public static void main(String[] args) {


A obj = new A();
[Link]();
}
}

Output:-

Hello
- 2023

P a g e 35 |
- 2023

P a g e 36 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

b) Wap to show Abstract class that has an abstract method


abstract class Bike {
abstract void run();
}

public class Main extends Bike {

public void run() {


[Link]("running safely");
}

public static void main(String[] args) {


Bike obj = new Main();
[Link]();
}
}

output:-
running safely

- 2023

P a g e 37 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

c) Another example of Abstract class in java

abstract class Bank {

abstract int getRateOfInterest();

class SBI extends Bank {

int getRateOfInterest() {

return 7;

class PNB extends Bank {

int getRateOfInterest() {

return 8;

public class Main {

public static void main(String[] args) {

Bank b;

b = new SBI();

[Link]("Rate of interest is: " + [Link]() + "%");

- 2023

P a g e 38 |
b = new PNB();

[Link]("Rate of interest is: " + [Link]() + "%");

}
}

Output:-
Rate of interest is: 7%
Rate of Interest is: 8%

- 2023

P a g e 39 |
- 2023

P a g e 40 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

WEEK - 11
1. Code, execute and debug programs in java to
a. handles checked and unchecked exceptions
b. read the content of the file and write the content to another file
[Link] exception handling in calculator program

a) Wap to show checked exception


import [Link];

import [Link];

public class Test{

public static void main(String args[]){

[Link]("Hello");

try{

File file = new File("my file");

FileInputStream fis = new FileInputStream(file);

catch(Exception e){

[Link]("Given file path is not found");

Output:-
Hello

Given file path is not found

- 2023

P a g e 41 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

b) Wap to show unchecked exception

unchecked

public class ExceptionExample{

public static void main(String[] args){

int inpuArray[] = new int[5];

inpuArray[0] = 41;

inpuArray[1] = 98;

inpuArray[2] = 43;

inpuArray[3] = 26;

inpuArray[4] = 79;

[Link](inpuArray[6]);

Output:
[Link]: Index 6 out of bounds for length 5

at [Link]([Link])

- 2023

P a g e 42 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

Wap to write the content of the file to another file


import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class CopyContent {
public static void main(String[] args) throws IOException {
//Instantiating a file class
File file = new File("D:\\[Link]");
//Instantiate an FileInputStream class
FileInputStream inputStream = new FileInputStream(file);
//Instantiating the Scanner class
Scanner sc = new Scanner(inputStream);
//StringBuffer to store the contents
StringBuffer buffer = new StringBuffer();
//Appending each line to the buffer
while([Link]()) {
[Link](" "+[Link]());
}
[Link]("Contents of the file: "+buffer);
//Creating a File object to hold the destination file
File dest = new File("D:\\[Link]");
//Instantiating an FileWriter object
- 2023

P a g e 43 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

FileWriter writer = new FileWriter(dest);


//Writing content to the destination
[Link]([Link]());
[Link]();
[Link]("File copied successfully....... ");
}
}

WEEK - 12
[Link] an interface & Implement & check compliance with ISP
// Interface

interface Animal

public void animalSound(); // interface method (does not have a body)

public void sleep(); // interface method (does not have a body)

// Pig "implements" the Animal interface

class Pig implements Animal {

public void animalSound() {

// The body of animalSound() is provided here

[Link]("The pig says: wee wee");

public void sleep() {

// The body of sleep() is provided here

[Link]("Zzz");

- 2023

P a g e 44 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

class Main {

public static void main(String[] args) {

Pig myPig = new Pig(); // Create a Pig object

[Link]();

[Link](); }}

WEEK - 13
1. Code, execute and debug programs in java to connect to JDBC and perform
basic DB operations

Problem Description
How to connect to a database using JDBC?
Assume that database name is testDb and it has table named employee which has 2
records.

Solution
Following example uses getConnection, createStatement & executeQuery methods
to connect to a database & execute queries.
import [Link].*;

public class jdbcConn {


public static void main(String[] args) {
try {
[Link]("[Link]");
} catch(ClassNotFoundException e) {
[Link]("Class not found "+ e);
}
[Link]("JDBC Class found");
int no_of_rows = 0;

try {
Connection con = [Link] (
"jdbc:derby://localhost:1527/testDb","username", "password");
Statement stmt = [Link]();
ResultSet rs = [Link] ("SELECT * FROM employee");
while ([Link]()) {

- 2023

P a g e 45 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

no_of_rows++;
}
[Link]("There are "+ no_of_rows + " record in the table");
} catch(SQLException e){
[Link]("SQL exception occured" + e);
}
}
}

Copy and paste the following example in [Link], compile and run as
follows −
import [Link].*;

public class FirstExample {


static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Employees";

public static void main(String[] args) {


// Open a connection
try(Connection conn = [Link](DB_URL, USER, PASS);
Statement stmt = [Link]();
ResultSet rs = [Link](QUERY);) {
// Extract data from result set
while ([Link]()) {
// Retrieve by column name
[Link]("ID: " + [Link]("id"));
[Link](", Age: " + [Link]("age"));
[Link](", First: " + [Link]("first"));
[Link](", Last: " + [Link]("last"));
}
} catch (SQLException e) {
[Link]();
}
}
}

Now let us compile the above example as follows −

- 2023

P a g e 46 |
Object
Object Oriented
Oriented Programming
Programming and Using
and Design Design Using Java
Java 4 SEM 20CS43P

C:\>javac [Link]

Result
The above code sample will produce the following result. The result may vary. You
will get ClassNotfound exception if your JDBC driver is not installed properly.
JDBC Class found
There are 2 record in the table

- 2023

P a g e 47 |

You might also like