Object Oriented Programming in Java Practicals
Object Oriented Programming in Java Practicals
Object Oriented Programming in Java Practicals
C++ Java
Extends C with object-oriented programming and
generic programming. C code can most properly be Strongly influenced by C++/C syntax.
used.
Compatible with C source code, except for a few Provides the Java Native Interface and recently Java
corner cases. Native Access as a way to directly call C/C++ code.
Write once, run anywhere/everywhere
Write once, compile anywhere (WOCA).
(WORA/WORE).
Allows procedural programming, functional
Allows procedural programming, functional programming (since Java 8) and generic
programming, object-oriented programming, programming (since Java 5), but strongly
generic programming, and template encourages the object-oriented programming
metaprogramming. Favors a mix of paradigms. paradigm. Includes support for creating scripting
languages.
Runs as native executable machine code for the
Runs on a virtual machine.
target instruction set(s).
Provides object types and type names. Allows Is reflective, allowing metaprogramming and
reflection via run-time type information (RTTI). dynamic code generation at runtime.
Has multiple binary compatibility standards
Has one binary compatibility standard, cross-
(commonly Microsoft (for MSVC compiler) and
platform for OS and compiler.
Itanium/GNU (for almost all other compilers)).
Optional automated bounds checking (e.g., the All operations are required to be bound-checked by
at() method in vector and string all compliant distributions of Java. HotSpot can
containers). remove bounds checking.
Native unsigned arithmetic unsupported. Java 8
Native unsigned arithmetic support.
changes some of this, but aspects are unclear.[1]
Standardized minimum limits for all numerical
types, but the actual sizes are implementation- Standardized limits and sizes of all primitive types
defined. Standardized types are available via the on all platforms.
standard library <cstdint>.
Pointers, references, and pass-by-value are All types (primitive types and reference types) are
supported for all types (primitive or user-defined). always passed by value.[2]
Memory management can be done manually via
new / delete, automatically by scope, or by
Automatic garbage collection. Supports a non-
smart pointers. Supports deterministic destruction of
deterministic finalize() method use of which is not
objects. Garbage collection ABI standardized in C+
recommended.[3]
+11, though compilers are not required to
implement garbage collection.
Resource management can be done manually or by Resource management must generally be done
Java Runtime Environment (JRE) is a software package that contains what is required to run a Java program. It
includes a Java Virtual Machine implementation together with an implementation of the Java Class Library. The
Oracle Corporation, which owns the Java trademark, distributes a Java Runtime environment with their Java
Virtual Machine called HotSpot.
A Java virtual machine (JVM) is an abstract computing machine that enables a computer to run a Java program.
There are three notions of the JVM: specification, implementation, and instance. The specification is a document
that formally describes what is required of a JVM implementation. Having a single specification ensures all
implementations are interoperable. A JVM implementation is a computer program that meets the requirements of
the JVM specification. An instance of a JVM is an implementation running in a process that executes a computer
program compiled into Java bytecode.
The "doc comments" format[3] used by Javadoc is the de facto industry standard for documenting Java classes.
Some IDEs,[4] like Netbeans and Eclipse, automatically generate Javadoc HTML. Many file editors assist the user
in producing Javadoc source and use the Javadoc info as internal references for the programmer.
Javadoc also provides an API for creating doclets and taglets, which allows users to analyze the structure of a Java
application. This is how JDiff can generate reports of what changed between two versions of an API.
package jainil;
import java.util.Scanner;
public class Jainil {
3 Implement following task using Array. Return an array that contains exactly the same numbers as the
given array, but rearranged so that every 3 is immediately followed by a 4. Do not move the 3's, but
every other number may move. The array contains the same number of 3's and 4's, every 3 has a number
after it that is not a 3 or 4, and a 3 appears in the array before any 4.public int[] fix34(int[] nums)
Program
package pra3;
import java.util.Scanner;
public class Pra3 {
public static int[] fic34(int a[])
{
if(a.length==2)
{
if(a[0]==4&&a[1]==3)
{
a[0]=3;a[1]=4;
}
if(a[0]==3&&a[1]==4)
{
a[0]=3;a[1]=4;
}
}
else{
int i=0,j=0,k=0;
for(i=0;i<a.length-1;i++)
{
if(a[i]==3)
{
if(i==0||a[i+1]!=4||i==a.length)
{
for(k=0;j<a.length;k++)
{
if(a[k]==4)
{
import java.util.Scanner;
public class Pra4 {
public static void main(String[] args) {
// TODO code application logic here
int n;
int i;
int j;
int k;
Scanner sc=new Scanner(System.in);
System.out.println("enter no of rows");
n=sc.nextInt();
for(i=0;i<n;i++)
{
for(j=n-i;j>0;j--)
System.out.print(" ");
for(j=0;j<i;j++)
{
System.out.printf("%7d",(int)Math.pow(2,j));
}
for(k=j;k>=0;k--)
{
System.out.printf("%7d",(int)Math.pow(2,k));
}
System.out.print("\n");
}
5 The problem is to write a program that will grade multiple-choice tests. Assume there are eight students
and ten questions, and the answers are stored in a two dimensional array. Each row records a student’s
answers to the questions, as shown in the following array. Students’ Answers to the
questions: 0 1 2 3 4 5 6 7 8 9
Student 0 A B A C C D E E A D
Student 1 D B A B C A E E A D
Student 2 E D D A C B E E A D
Student 3 C B A E D C E E A D
Student 4 A B D C C D E E A D
Student 5 B B E C C D E E A D
Student 6 B B A C C D E E A D
Student 7 E B E C C D E E A D
The key is stored in a one-dimensional array: Key to the Questions:
012 3 4 5 6 7 8 9
Key D B D C C D A E A D
Your program grades the test and displays the result. It compares each student’s answers with the key,
counts the number of correct answers, and displays it.
Program:
package pra5;
import java.util.Scanner;
public class Pra5 {
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
// TODO Auto-generated method stub
String a[]=new String[8];
for(int i=0;i<8;i++)
{
a[i]=sc.next();
}
String answerkey="DBDCCDAEAD";
int marks[]=new int[8];
for(int i=0;i<8;i++)
{
marks[i]=0;
}
}
OUTPUT
import java.util.Scanner;
public class Sudoku {
}
}
}
if(flag==0)
{
System.out.println("Congrats your answer is correct");
}
else
{
System.out.println("sorry do you want to see answer");
{
System.out.println("your wrong input");
printGrid(a);
System.out.println("your correct answer is");
printGrid(ans);
} } }
}
OUTPUT
import java.util.Scanner;
/**
*
* @author jainil
*/
public class Pra7 {
import java.util.Scanner;
/**
*
* @author jainil
*/
public class Pra9 {
public static void main(String[] args) {
// TODO code application logic here
String s1;
String s2=new String();
int key;
System.out.println("Enter data");
Scanner sc=new Scanner(System.in);
s1=sc.nextLine();
System.out.println("Enter key");
key=sc.nextInt();
char a[]=new char[s1.length()];
a=s1.toCharArray();
int b[]=new int[s1.length()];
for(int i=0;i<s1.length();i++)
{
b[i]=(int)a[i];
}
for(int i=0;i<s1.length();i++)
{
b[i]=(b[i]+key);
}
for(int i=0;i<s1.length();i++)
{
System.out.print((char)b[i]);
}
System.out.println("\nNow reversing");
for(int i=0;i<s1.length();i++)
{
}
OUTPUT
8 Given an array of strings, return a new array without the strings that are equal to the target string. One
approach is to count the occurrences of the target string, make a new array of the correct length, and then
copy over the correct strings.
wordsWithout(["a", "b", "c", "a"], "a") → ["b", "c"] wordsWithout(["a", "b", "c", "a"], "b") → ["a", "c",
"a"] wordsWithout(["a", "b", "c", "a"], "c") → ["a", "b", "a"]
Program:
package pra8;
public class Pra8 {
}
OUTPUT
package pra9;
import java.util.Scanner;
}
OUTPUT
PART-II
Object Oriented Programming: Classes, Methods, Inheritance
1 Design a class named Circle containing following attributes and behavior. One double data field
named radius. The default value is 1. A no-argument constructor that creates a default circle. A
Single argument constructor that creates a Circle with the specified radius. A method named getArea()
that returns area of the Circle. A method named getPerimeter() that returns perimeter of it
Program:
package circle;
import java.util.Scanner;
/**
*
* @author jainil
*/
public class Circle {
double radius;
Circle()
{
radius=1;
}
Circle(double d)
}
}
OUTPUT
2 ) Design a class named Account that contains: A private int data field named id for the account
(default 0). A private double data field named balance for the account (default 500₹). A private
double data field named annualInterestRate that stores the current interest rate (default 7%). Assume
all accounts have the same interest rate. A private Date data field named dateCreated that stores
the date when the account was created. A no-arg constructor that creates a default account. A
constructor that creates an account with the specified id and initial balance. The accessor and
mutator methods for id, balance, and annualInterestRate. The accessor method for dateCreated.
A method named getMonthlyInterestRate() that returns the monthly interest rate. A method named
getMonthlyInterest() that returns the monthly interest. A method named withdraw that withdraws
a specified amount from the account. A method named deposit that deposits a specified amount to
the account.
Program:
package account;
CE219.01 OOPJ 16CE068 Page 18
import static java.lang.System.exit;
import java.util.Date;
import java.util.Scanner;
/**
*
* @author jainil
*/
public class Account {
/**
* @param args the command line arguments
*/
static int count=0;
private int id=0;
private double balance=0;
private double annualInterestRate=7;
private Date dateCreated=new Date();
Account()
{
id=count;
balance=0;
annualInterestRate=7;
count++;
}
Account (int idd,double balancee)
{
id=idd;
balance=balancee;
}
aa:
while (true) {
}
}
OUTPUT
}
Account (int idd,double balancee)
{
id=idd;
balance=balancee;
}
public class Demo
{
public static void main(String[] args) {
b.getdata();
System.out.println("enter withdawing amount");
double w;
b.setLimit(-5000);
w=sc.nextInt();
b.withdraw(w);
b.printdata();
System.out.println("monthly rate"+b.getMonthlyInterest()+" "+b.getLimit());
}
}
OUTPUT
package practical5;
import java.util.Scanner;
int radius;
double area()
{
return (3.14*radius*radius);
}
double area(int r)
{
return (3.14*r*r);
}
double area(double r)
{
return (3.14*r*r);
}
void area(double ...a)
{
for (double d : a) {
System.out.println("Area is "+(3.14*d*d));
}
}
void area(int ...a)
{
for (int d : a) {
System.out.println("Area is "+(3.14*d*d));
OUTPUT
3 Use the Account class created as above to simulate an ATM machine. Create 10 accounts with id
/**
*
* @author jainil
*/
class Automatictellermachine
{
float balance=0;
public void balanceinquiry()
{
System.out.println(balance);
}
public void withdraw(float a)
{
balance=balance-a;
if(balance<300)
{
System.out.println("you cannot withdraw rs "+a +" maintain 300 rs");
balance=balance+a;
}
else
{
System.out.println(a+ " withdrawn ");
}
}
public void deposit(float a)
{
balance=balance+a;
}
public float transfer(float a)
public Automatictellermachine() {
}
}
public class Atm {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int i;
int q;
ArrayList<Automatictellermachine> a = new ArrayList<Automatictellermachine> (100);
while(true){
System.out.println("1. Balance inquiry ");
System.out.println("2. Withdraw money [Maintain minimum balance 300₹] ");
System.out.println("3. Deposit money ");
System.out.println("4. Money Transfer ");
float o;
if(q<a.size()){
System.out.println("enter money");
o=sc.nextFloat();
a.get(q).withdraw(o);
}
else
{
System.out.println("invalid id");
}
break;
case 3:
System.out.println("enter id for deposit");
q=sc.nextInt();
float oo;
if(q<a.size()){
System.out.println("enter money");
oo=sc.nextFloat();
a.get(q).deposit(oo);
}
else
{
break;
case 4:
int payer;
int getter;
float amount;
System.out.println("enter id who want to trasfer(payer)");
payer=sc.nextInt();
System.out.println("enter id of receivant (money getter)");
getter=sc.nextInt();
if((payer<a.size())&&(getter<a.size()))
{
System.out.println("enter amount");
amount=sc.nextFloat();
a.get(getter).deposit(a.get(payer).transfer(amount));
}
else
{
System.out.println(a.size());
System.out.println("invalid id");
}
break;
case 5:
a.add(new Automatictellermachine());
break;
case 6:
System.out.println("enter id to remove");
q=sc.nextInt();
if(q<a.size())
{a.remove(q);}
else
{
System.out.println("invalid id");
}
break;
case 7:
exit(1);
break;
default:
System.out.println("enter valid choice please!!");
interface LuminousObject
{
default void lighton()
{
System.out.println("Light on in interface");
}
default void lightoff()
{
System.out.println("Light off in interface");
}
}
class Solid
{
}
class cube extends Solid
{
}
class cone extends Solid
{
}
class LuminiousCone extends cone implements LuminousObject
{
public void reference()
{
LuminousObject.super.lighton();
LuminousObject.super.lightoff();
}
public void lighton()
{
System.out.println("light is on in cone");
}
public void lightoff()
{
System.out.println("Light is off in cone");
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
LuminiousCone lCone = new LuminiousCone();
LuminousCube lCube = new LuminousCube();
lCone.reference();
lCone.lighton();
lCone.lightoff();
lCube.reference();
lCube.lighton();
lCube.lightoff();
} }
OUTPUT
2 WAP that illustrate the interface inheritance. Interface P is extended by P1 and P2 interfaces. Interface
CE219.01 OOPJ 16CE068 Page 36
P12 extends both P1 and P2. Each interface declares one method and one constant. Create one class that
implemetns P12. By using the object of the class invokes each of its method and displays constant.
PROGRAM:
package pract2;
import java.awt.PointerInfo;
interface p
{ int a=1;
void a();}
interface p1 extends p
{ int b=2;
void b();}
interface p2 extends p
{ int c=3;
void c();}
interface p12 extends p1,p2
{}
public class Pract2 implements p12{
public void a()
{ System.out.println("a = " + a); }
public void b()
{ System.out.println("b = " + b); }
public void c()
{
System.out.println("c = " + c);
}
public static void main(String[] args) {
// TODO code application logic here
Pract2 pract2 = new Pract2();
pract2.a();
pract2.b();
pract2.c();
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
OUTPUT
3 Create an abstract class Robot that has the concretre subclasses , RobotA, RobotB, RobotC. Class
public RobotB() {
}
}
class RobotC extends Robot implements Motion,Sound
{
public RobotC() {
}
public void beep()
{
System.out.println("beep in Robot C");
}
public void forward() {
System.out.println("forward C"); position++;
}
5 Write a java program which shows importing of classes from other user define packages.
}
Program demo.java:
package pakages;
import pack1.pack1;
import pakages.pack2;
public class demo {
void defaultmethod()
{
System.out.println("Hello from packages default method");
}
public void method()
{
System.out.println("Hello from packages public method");
}
private void privatemethod()
{
System.out.println("Hello from packages private method");
}
protected void protectedmethod()
{
}
Program pack2.java:
package pakages;
public class pack2 {
void defaultmethod()
{
System.out.println("Hello from packages.pack2 default method");
}
public void method()
{
System.out.println("Hello from packages.pack2 public method");
}
private void privatemethod()
{
System.out.println("Hello from packages.pack2 private method");
}
protected void protectedmethod()
{
System.out.println("Hello from packages.pack2 protected method");
}
}
OUTPUT
}
Program demo.java:
package pakages;
import pack1.pack1;
import pakages.pack2;
public class demo {
void defaultmethod()
{
System.out.println("Hello from packages default method");
}
public void method()
{
System.out.println("Hello from packages public method");
}
private void privatemethod()
{
System.out.println("Hello from packages private method");
}
protected void protectedmethod()
{
System.out.println("Hello from packages protected method");
}
Program pack2.java:
package pakages;
public class pack2 {
void defaultmethod()
{
System.out.println("Hello from packages.pack2 default method");
}
public void method()
{
System.out.println("Hello from packages.pack2 public method");
}
private void privatemethod()
{
System.out.println("Hello from packages.pack2 private method");
}
protected void protectedmethod()
{
System.out.println("Hello from packages.pack2 protected method");
}
}
OUTPUT
}
OUTPUT
try {
a[2] = a[10] / 0 + 2;
} catch(ArrayIndexOutOfBoundsException aioe)
{
System.out.println("Access of invalid index in array - index out of range...");
}
catch(ArithmeticException ae)
{
System.out.println("Enter valid denominator..");
}finally {
System.out.println("Within Inner finally block.....");
}
} catch(Exception e)
{
System.out.println("Unexpected exception occured... :::"+e);
} finally {
System.out.println("Finally block executed.....");
}
System.out.println("After fially block .......");
try
{
Class c = Class.forName("p1.ExceptionDemo3");
System.out.println("2nd line");
}
catch(ClassNotFoundException e)
{
System.out.println("Class not found..");
}
try
{
FileInputStream fis = new FileInputStream("C:\\Arithmetic.java");
DataInputStream ds = new DataInputStream(fis);
}
2 WAP to generate user defined exception using “throw” and “throws” keyword.
3 Write a program that raises two exceptions. Specify two ‘catch’ clauses for the two exceptions. Each
finally
{
//finally block is executed compulsorily irrespective of the occurrence of an error
System.out.println("finally block executes after arithmetic exception occured and array out
of bound occured");
}
}
}
OUTPUT
PART-V
}}
OUTPUT
2 Write a program to show a tree view of files and directories under a specified drive/volume.
3 Write a program to transfer data from one file to another file so that if the destination file does not exist,
5 WAP to read console input and write them into a file. (BufferedReader /BufferedWriter).
int i=a;
System.out.println(i);
int j=a.intValue();
byte b=a.byteValue();
float f=a.floatValue();
short s=a.shortValue();
long l=a.longValue();
System.out.println(j);
System.out.println(b);
System.out.println(f);
System.out.println(s);
System.out.println(l);
String str=a.toString();
System.out.println(str);
Integer n=Integer.valueOf(str);
System.out.println(n);
int c=Integer.parseInt(str);
System.out.println(c);
}
}
OUTPUT
PART-VI
}
}
public class Wel {
public static void main(String[] args) {
// TODO code application logic here
a obj = new a();
obj.start();
b objb = new b();
new Thread(objb).start();
}
}
OUTPUT
2 Write a program which takes N and number of threads as an argument. Program should distribute the
public class a {
public static void main(String args[]) throws InterruptedException
{
int sum = 0;
int N, n, i, j, k;
Scanner sc = new Scanner(System.in);
System.out.println("Enter N to find sum:");
N = sc.nextInt();
System.out.println("Enter number of threads:");
n = sc.nextInt();
Multi3[] m = new Multi3[n];
k = N / n;
j = 1;
m[i].join();
System.out.println("Sum=" + sum);
}
}
OUTPUT:
3 Write a program to increment the value of one variable by one and display it after one second using
}}
}
}
public class Inc {
public static void main(String[] args) {
a obj = new a();
obj.start();
}
OUTPUT:
4 Write a program to create three threads ‘FIRST’, ‘SECOND’, ‘THIRD’. Set the priority of the ‘FIRST’
package thr;
class a extends Thread
{
public void run()
{
System.out.println("thread "+this.getName()+this.getPriority());
}
}
public class Thr {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
a obj = new a();
a obj1 = new a();
a obj2 = new a();
obj.setName("FIRST");
obj1.setName("SECOND");
obj2.setName("Third");
obj.setPriority(3);
obj1.setPriority(5);
obj2.setPriority(7);
obj.start();
obj1.start();
obj2.start();
}
}
OUTPUT:
}
System.out.println("Got:"+n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n){
if(valueSet)
try{
wait();
}catch(InterruptedException ie){
}
this.n = n;
valueSet = true;
System.out.println("Put:"+n);
notify();
}
}
class Producer implements Runnable{
Q q;
Producer(Q q){
this.q =q;
new Thread(this, "Producer").start();
}
while(true){
q.put(i++);
}
}
}
while(true){
q.get();
}
}
}
2 Write a program that counts the occurrences of words in a text and displays the words and their
occurrences in alphabetical order of the words. Using Map and Set Classes.
Program:
package word;
import java.util.Scanner;
import java.util.*;
public class Word {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str;
str=sc.nextLine();
StringTokenizer s = new StringTokenizer(str);
int count=s.countTokens();
String k[]=new String[s.countTokens()];
int i=0;
while(s.countTokens()!=0)
{
k[i]=s.nextToken();
i++;
}
System.out.println("SORTING USING TREESET ");
TreeSet<String> treeset =new TreeSet<String>();
3 Write a code which counts the number of the keywords in a Java source file. Store all the keywords in a
CE219.01 OOPJ 16CE068 Page 70
HashSet and use the contains method to test if a word is in the keyword set.
Program:
package keywords;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.HashSet;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Keywords {
public static void main(String[] args) {
String
s[]={"abstract","assert","boolean","break","byte","case","catch","char","class","continue","default","do",
"double","else","enum","extends","final","finally","float","for","if","implements","import","instanceof",
"int","interface","long","native","new,package","private","protected","public","return","short","static",
"super","switch","synchronized","this","throw","throws","transient","try","void","volatile","while"};
HashSet<String> h=new HashSet<String>();
for (String string : s) {
h.add(string);
}
String a;
int count=0;
System.out.println("ENTER FILE PATH:");
Scanner sc = new Scanner(System.in);
a=sc.next();