COSC 1202 Object Oriented Programming Lab
COSC 1202 Object Oriented Programming Lab
Lab Objectives:
1. Compile and Run Java Program
2. Understand Java syntax
Software Required:
JDK / Text Pad/ Note Pad
BASIC SYNTAX
About Java programs, it is very important to keep in mind the following points.
Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have
different meaning in Java.
Class Names − For all class names the first letter should be in Upper Case. If several words
are used to form a name of the class, each inner word's first letter should be in Upper Case.
Example: class MyFirstJavaClass
Method Names − All method names should start with a Lower Case letter. If several words
are used to form the name of the method, then each inner word's first letter should be in
Upper Case.Example: public void myMethodName()
Program File Name − Name of the program file should exactly match the class name.When
saving the file, you should save it using the class name (Remember Java is case sensitive) and
append '.java' to the end of the name (if the file name and the class name do not match, your
program will not compile).Example: Assume 'MyFirstJavaProgram' is the class name. Then
the file should be saved as 'MyFirstJavaProgram.java'
public static void main(String args[]) − Java program processing starts from the main()
method which is a mandatory part of every Java program.
/*
This is a simple Java program.
Call this file "Example.java".
*/
Task 3: Write a Java program to print 'Hello' on screen and then print
your name on a separate line.
QUESTIONS
Please Fill the blank space with respective answers to following questions:
creation?
Question 2: Which command is responsible for the compilation of the java
code?
Question 3: What will be the name and the type of the file which will be
created if the following command is executed:
javac MyClass.java
Lab Objectives:
1. Understand Java variables declaration and initialization
2. Understanding java datatypes and their usage
3. Use of operators in java
Software Required:
JDK & Notepad
int result = 1 + 2;
System.out.println(result);
result = result - 1;
System.out.println(result);
result = result * 2;
System.out.println(result);
result = result / 2;
System.out.println(result);
}
}
if (expression) {
number = 10;
}
else {
number = -10;
}
The program should input all these facts as integers, calculate the new balance (= beginning
balance + charges – credits), display the new balance and determine whether the new balance
exceeds the customer’s credit limit. For those customers whose credit limit is exceeded, the
program should display the message "Credit limit exceeded".
Scanner Class
There are various ways to read input from the keyboard, the java.util.Scanner class is
one of them.
The Java Scanner class breaks the input into tokens using a delimiter that is
whitespace by default. It provides many methods to read and parse various primitive
values.
Java Scanner class is widely used to parse text for string and primitive types using
regular expression.
TASK 7: User Input Validation: For any input, if the value entered is other
than 1 or 2, keep looping until the user enters a correct value. Use Scanner
class for input.
QUESTIONS
Please Fill the blank space with respective answers to following questions:
Question 1: Fill the following table
TYPE DEFAULT VALUES
byte
short
int
long
float
double
char
boolean
code.
Question 4: What are the default values of java primitive datatypes. Fill the
following table.
TYPE DEFAULT VALUES
Software Required:
JDK & Notepad/ Textpad
TASK 1: Write a program which does following conversions and prints the
result. Observe the output.
int i = 3;
double d;
d = i; // OK, no explicit type casting required
// d = 3.0
d = (double) i; // Explicit type casting operator used here
double aDouble = 55; // Compiler auto-casts int 55 to double 55.0
double nought = 0; // Compiler auto-casts int 0 to double 0.0
// int 0 and double 0.0 are different.
Expected Output:
Body Mass Index is 61.30159143458721
TASK 7: Program Rock.java contains a skeleton for the game Rock, Paper,
Scissors. Open it and save it to your directory. Add statements to the
Use a switch statement to convert the randomly generated integer for the computer's
play to a string.
// ****************************************************************
// Rock.java
//
// Play Rock, Paper, Scissors with the user
//
// ****************************************************************
import java.util.Scanner;
import java.util.Random;
public class Rock
{
public static void main(String[] args)
{
String personPlay; //User's play -- "R", "P", or "S"
String computerPlay; //Computer's play -- "R", "P", or "S"
int computerInt; //Randomly generated number used to determine
//computer's play
Scanner scan = new Scanner(System.in);
Random generator = new Random();
//Get player's play -- note that this is stored as a string
//Make player's play uppercase for ease of comparison
//Generate computer's play (0,1,2)
QUESTIONS
Please Fill the blank space with respective answers to following questions:
Lab Objectives:
1. Understand Java loops and their usage
2. Implement all types of loops
3. Understand practical usage of loops
Software Required:
JDK & Notepad/ Textpad
Question 1: The exponent tells you how many times to multiply the number
by itself. For instance, three to the power of four, or 3^4, will be: 3 x 3 x 3 x
3 = 9 x 9 = 81. Write a program for calculating power of a number using
loop.
1 2 Coza 4 Loza Coza Woza 8 Coza Loza 11 Coza 13 Woza CozaLoza 16 17 Coza 19 Loza
CozaWoza 22 23 Coza Loza 26 Coza Woza 29 CozaLoza 31 32 Coza ......
*
**
***
****
*****
******
Question 5: Ask user input to input values and check if value is multiple of
3. If the given value is multiple of 3 then print “Yes! you reached end”
otherwise keep on looping and asking user to enter new number.
QUESTIONS
Please Fill the blank space with respective answers to following questions:
class ForSample
{
public static void main(String s[])
{
for(int i = 0; i <= 5; i++ )
{
}
Explain Here:
THE END
Lab Objectives:
1. Understanding arrays and their implementation in java
2. Manipulating arrays in java
Software Required:
JDK & Notepad/ Textpad
ARRAYS
An array is a container object that holds a fixed number of values of a single type. The length
of an array is established when the array is created.
Question 1:
Describe and explain what happens when you try to compile a program HugeArray.java with
the following statement:
int n = 1000;
int[] a = new int[n*n*n*n];
Question 2:
Set up an array to hold the following values, and in this order: 23, 6, 47, 35, 2, 14. Write a
program to get the average of all 6 numbers. Use foreach loop.
Question 3:
Using the above values in Question 5, have your program print out the highest and lowest
numbers in the array. Use foreach loop.
Question 4:
Use a one-dimensional array to solve the following problem: Write a program that inputs 5
numbers, each of which is between 10 and 100, inclusive. As each number is read, display it
Question 5:
Write a code which calculates transpose of 2x3 matrix.
->
QUESTIONS
Please Fill the blank space with respective answers to following questions:
Question 1: What will be the last element of an array whose size is 24?
JAVA METHODS,
CONSTRUCTORS AND
METHOD OVERLOADING
Lab-06
Lab Objectives:
1. Understand java methods, arguments passing and return
2. Understand the purpose and implementation of constructors
3. Understand and implement the mechanism of method overloading
Software Required:
JDK & Notepad/ Textpad
Introduction:
A simplified general form of a class definition is shown here:
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type m
ethodname1(parameter-list) {// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
Sample code:
/* Here, Box uses a parameterized constructor to initialize the dimensions of a box. */
class Box {
double width;
double height;
class BoxDemo7 {
Create two variable for holding values of x and y as 10 and 100 respectively.
Initialize using constructor.
Task 2: You will create a class that keeps track of the total cost, average
cost, and number of items in a shopping bag.
Create a class called ShoppingBag. Objects of this class represent a single shopping bag.
Attributes of such an object include the number of items in the bag and the total retail cost of
those items.
Provide a constructor that accepts a tax rate as a float parameter.
Provide a transformer method called place that accepts an int parameter indicating the
number of the particular items that are being placed in the bag and a float parameter that
indicates the cost of each of the items. For example, myBag.place (5, 10. 5); represents
placing 5 items that cost $10.50 each into myBag.
Provide getter methods for the number of items in the bag and their total retail cost. Provide a
totalCost method that returns the total cost with tax included.
Provide at oString method that returns a nicely formatted string that summarizes the current
status of the shopping bag.
Finally, provide a program, a “test driver,” that demonstrates that your ShoppingBag class
performs correctly.
Methods of the same name can be declared in the same class, as long as they have different
sets of parameters (determined by the number, types and order of the parameters)—this is
called method overloading.
Method named as test() which takes one integer parameter and return nothing.
Method named as test() which takes two integer parameters and returns nothing.
Method named as test() which takes two integer parameters and return their integer type sum.
Method test() which takes one double parameter and returns double type value.
Method test() which takes two argument first one is integer and second one is float and
returns nothing.
Method test() which takes two arguments, first one is float and second one is integer and
return nothing.
Now Create another class named as demo and call each method of class DemoOverloading,
one by one by passing appropriate parameters.
QUESTIONS
Please Fill the blank space with respective answers to following questions:
Question 2: Suppose there is a class name “MyClass”. How will its object
be created?
class Student
{
String name;
int marks;
char section;
}
overloaded?
THE END
Lab Objectives:
1. Understanding the use of this keyword
2. Understanding access modifiers
3. Understanding and implementing static keyword concept
Software Required:
Notepad ++ or Textpad
Access Modifiers
Access levels and their accessibility can be summarized as:
Task 1: Write another class in which you write main method and access the
this Keyword
There can be a lot of usage of java this keyword. In java, this is a reference variable that
refers to the current object.
o can be used to return the current class instance from the method.
Sample code
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
Task 4: this: to refer current class instance variable. Write a class in which
names of class data members are same as constructor arguments.
Definition of the constructor should be similar to following
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
Display rollno, name and fee values in display method
Now create two objects of this class and display their value
Observe output and identify problem
Now rewrite constructor function as follows
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
again run the code and see output
The this() constructor call can be used to invoke the current class constructor. It is used to
reuse the constructor. In other words, it is used for constructor chaining.
2. create a constructor of this class which takes rollno, course and name as parameter
and assign them to variables of rollno, course and name respectively
3. Create another constructor which takes arguments: rollno, course, name and fee.
Assign fee to fee variable and call first constructor to assign other three arguments.
static Keyword
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a class.
Static method can access static data member and can change the value of it.
If you declare any variable as static, it is known static variable.
The static variable can be used to refer the common property of all objects (that is not unique
for each object) e.g. company name of employees, college name of students etc.
The static variable gets memory only once in class area at the time of class loading.
Task 6:
A. Calculate cube using a method
Create a class named as calculate
Write a method, count in which returns cube of the given variable.
Write main method which calls the count method
QUESTIONS
Please Fill the blank space with respective answers to following questions:
class ClassConstructorOperations
{
public static void main(String s[])
{
Student student = new Student( "Lavanya", 501, 95.6 );
System.out.println(student.rollNumber + " is the roll number of " + student.name + "
and she secured " + student.percentage + " % in SSC" );
}
}
class Student
{
String name;
}
Question 5: What will be the output of the program?
public class Karbon {
static int i = 5;
public static void main(String[] args) {
Karbon test = null;
System.out.print("i = " + test.i + ", ");
System.out.print("i = " + Karbon.i);
}}
THE END
Lab Objectives:
1. Understanding the concept of garbage collection
2. Understanding and implementing Nested and Inner classes
3. Understanding and Implementing Encapsulation
Software Required:
JDK & Notepad/ Textpad
Sometimes an object will need to perform some action when it is destroyed. For example, if
an object is holding some non-Java resource such as a file handle or character font, then you
might want to make sure these resources are freed before an object is destroyed. To handle
such situations, Java provides a mechanism called finalization. By using finalization, you can
define specific actions that will occur when an object is just about to be reclaimed by the
garbage collector.
class A {
int i = 50;
@Overrideprotected void finalize() throws Throwable {
System.out.println("From Finalize Method"); }
//abandoned
System.gc();System.out.println("done");
final Keyword: The final keyword can be applied with the variables, a final variable that
has no value it is called blank final variable or uninitialized final variable. It can be initialized
in the constructor only.
TASK 2: Value of final variable cannot be changed once declared. Run the
following code and check output.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[])
{
Bike9obj=new Bike9(); obj.run();
}
}//end of class
TASK 4: Declare final variable as static and try to initialize its value in a
method. Then create a static block and initialize the static final variable
value.
Nested and Inner Classes
TASK 5: Run the following code and try to understand its working
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
} }
} }
} }
QUESTIONS
Please Fill the blank space with respective answers to following questions:
constructor?
THE END
Lab Objectives:
1. Understanding the concept of inheritance
2. Implementation of Inheritance in java
Software Required:
Netbeans IDE
Inheritance in Java
class SimpleInheritance {
public static void main(String args []) {
A superOb = new A();
B subOb = new B();
TASK 2: Create a class A which has two data members one is public and
other is private. Create another class B which extends class A. Try to
display values of both data members of class A in class B.
QUESTIONS
Please Fill the blank space with respective answers to following questions:
Question 1: What are different types of inheritance?
class DefineClassHierarchy
{ public static void main(String s[])
Lab Objectives:
1. Understanding the concept of polymorphism
2. Understand the super keyword in inheritance
Software Required:
Netbeans IDE
class DemoSuper {
We can use super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields. Perform following steps
The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class. In other words, it is used if method is
overridden. Perform following steps
• Create subclass of animal class with method bark() which prints "barking" and method eat()
same name as super class but it prints "eating meat"
• Write a print() method in subclass which call all the super and sub class methods.
The super keyword can also be used to invoke the parent class constructor. Create a scenario
in which above use of the super keyword is depicted.
Polymorphism in Java
Polymorphism in java is a concept by which we can perform a single action by different ways.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}
QUESTIONS
Please Fill the blank space with respective answers to following questions:
class Mobile {
String str = "";
Mobile() {
str += "Mobile is : ";
}
}
class Airtel extends Mobile {
Airtel() {
str += "Airtel";
}
Question 2: If parent class has a constructor animal which takes two
parameters integer and a string. How will it be called in child class using
java?
THE END
Lab Objectives:
1. Understanding the concept of polymorphism
2. Understand the super keyword
Software Required:
Netbeans IDE
Abstract Classes
Sample Code
// A Simple demonstration of abstract.
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println("This is a concrete method.");
}
}
class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
TASK 03: Create one superclass called Employee and two subclasses –
Contractor and FullTimeEmployee. Both subclasses have common
properties to share, like the name of the employee and the amount of
money the person will be paid per hour. There is one major difference
between contractors and full-time employees – the time they work for the
QUESTIONS
Please Fill the blank space with respective answers to following questions:
class CalculateAreas
{
public static void main(String arg[])
{
Square sq = new Square(5.25);
System.out.println("Area of Square is " + sq.getArea());
}
}
double getArea()
{
return side * side;
}
Question 3: What will be the output of the following program? Also explain
the reason behind the output.
THE END
Lab Objectives:
1. Understanding the concept of Encapsulation
2. Implementation of encapsulation using public functions
3. Understanding of real world scenarios and application of encapsulation
Software Required:
Netbeans IDE
Encapsulation
The whole idea behind encapsulation is to hide the implementation details from users. If a
data member is private it means it can only be accessed within the same class. No outside
class can access private data member (variable) of other class. However if we setup public
getter and setter methods to update (for example void setSSN(int ssn))and read (for example
int getSSN()) the private data fields then the outside class can access those private data fields
via public methods. This way data can only be accessed by public methods thus making the
private fields and their implementation hidden for outside classes. That’s why encapsulation
is known as data hiding.
return age;
return name;
return idNum;
age = newAge;
name = newName;
idNum = newId;
encap.setName("James");
encap.setIdNum("12343ms");
Task 02: Create a class Employee with age, name and ssn as private data
members.
Write set ad get methods for the private data members. Methods must apply following
conditions:
Age is not 0.
Try to set the values of the Employee class data members using another class and also display
the values of the data members.
Packages
Task 03: Create packages and try to access private, protected, public and
default data members in another package. Also create subclasses a class
outside its package and try to access private, protected, default and public
data members.
QUESTIONS
Please Fill the blank space with respective answers to following questions:
modifier?
Question 3: What will be the output of the following program? Assume that
we run LittleFlowerSchool class.
package com.mc.details;
import com.mc.Stud1.Student;
import com.mc.Stud2.StudentDetails;
public class LittleFlowerSchool {
public static void main(String[] args) {
Student std = new Student();
System.out.println("Rank is " + std.rank);
System.out.println("Marks is " + std.marks);
System.out.println(StudentDetails.address);
}
}
package com.mc.Stud1;
public class Student {
public int rank = 10;
public double marks = 89;
}
package com.mc.Stud2;
public class StudentDetails {
public static String address = "Hyderabad, Andhra Pradesh, India";
THE END
Lab Objectives:
1. Understanding the concept of Interfaces
2. Implementation and real world usage of Interfaces
Software Required:
Netbeans IDE
Interface
Sample Code
/* Animal.java */
interface Animal {
public void eat();
public void travel();
}
/*MammalInt.java */
public class MammalInt implements Animal {
public void eat() {
System.out.println("Mammal eats");
}
public void travel() {
Classes Invoice and Employee both represent things for which the company must be able to
calculate a payment amount. Both classes implement the Payable interface, so a program can
invoke method getPaymentAmount on Invoice objects and Employee objects alike.
The UML class diagram below shows the hierarchy used in our accounts payable application.
The hierarchy begins with interface Payable. The UML distinguishes an interface from other
classes by placing the word “interface” in (« and ») above the interface name. The UML
expresses the relationship between a class and an interface through a relationship known as
realization. A class is said to “realize,” or implement, the methods of an interface. A class
diagram models a realization as a dashed arrow with a hollow arrowhead pointing from the
implementing class to the interface. The diagram indicates that classes Invoice and Employee
each realize (i.e., implement) interface Payable. Class Employee appears in italics, indicating
that it’s an abstract class. Concrete class SalariedEmployee extends Employee and inherits its
superclass’s realization relationship with interface Payable.
Class Employee:
We now modify class Employee such that it implements interface Payable. It does not make
sense to implement method getPaymentAmount in class Employee because we cannot
calculate the getPaymentAmount owed to a general Employee—we must first know the
specific type of Employee. This forced each Employee concrete subclass to override
getPaymentAmount with an implementation. The Employee class will contain variables first
name, last name and SSN. SalariedEmployee class will contain variable Salary. Both class
will have get and set methods and constructors. toString method must also be implemented in
both parent and child classes which display the values of the class data members.
Main Method:
// PayableInterfaceTest.java
// Tests interface Payable.
public class PayableInterfaceTest
{
public static void main( String args[] )
System.out.println(
"Invoices and Employees processed polymorphically:\n" );
QUESTIONS
Please Fill the blank space with respective answers to following questions:
}
Question 3: What will be the output of the following program?
public class King {
public static void main(String[] args) {
King k = new King();
System.out.print("Output = " + k.new Elephant().step2(2, 3));
}
interface Queen {
float step2(int low, int high);
}
interface Pawn {
float step3(int a, int b, int c);
}
abstract class Knight implements Queen, Pawn {
}
class Elephant implements Queen {
public float step2(int x, int y) {
return (float)(x * 3);
}
}
THE END
Lab Objectives:
1. Understanding the concept of Exception Handling in Java
2. Implementing exception handling in java
3. Creating your own exceptions
Software Required:
Netbeans IDE
EXCEPTIONS:
Exception handling is a very important yet often neglected aspect of writing robust software.
When an error occurs in a Java program it usually results in an exception being thrown. How
you throw, catch and handle these exception matters. Runtime errors appear in Java as
exceptions, exception is a special type of classes that could be thrown to indicate a runtime
error and provide additional data about that error. If a method is declared to throw an
exception, any other method calls it should deal with this exception by throwing it (if it
appears) or handle it. Three categories of errors (syntax errors, runtime errors, and logic
errors):
• Syntax errors arise because the rules of the language have not been followed. They are
detected by the compiler.
• Exception handling to deal with runtime errors and using assertions to help ensure program
correctness.
import java.io.*;
this.amount = amount;
return amount;
}}
import java.io.*;
this.number = number;
balance += amount;
balance -= amount; }
else {
return balance;
return number;
}}
try {
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
} catch (InsufficientFundsException e) {
e.printStackTrace();
}}
TASK 04: Write a program that counts even numbers between minimum
and maximum values. Maximum and minimum values are provided by
user. If minimum value is greater than or equal to maximum value, the
QUESTIONS
Please Fill the blank space with respective answers to following questions:
THE END
Lab Objectives:
Software Required:
Netbeans IDE
Java I/O (Input and Output) is used to process the input and produce the output. Java uses
the concept of stream to make I/O operation fast. The java.io package contains all the classes
required for input and output operations. We can perform file handling in java by Java I/O
API. Stream
OutputStream class: OutputStream class is an abstract class. It is the super class of all
classes representing an output stream of bytes. An output stream accepts output bytes and
sends them to some sink.
Java FileOutputStream Class : Java FileOutputStream is an output stream used for writing
data to a file. If you have to write primitive values into a file, use FileOutputStream class.
You can write byte-oriented as well as character-oriented data through FileOutputStream
class. But, for character-oriented data, it is preferred to use FileWriter than FileOutputStream.
Hint:
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();//converting string into byte array
Java FileInputStream Class: Java FileInputStream class obtains input bytes from a file. It is
used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video
etc. You can also read character- stream data. But, for reading streams of characters, it is
recommended to use FileReader class.
Java Writer: It is an abstract class for writing to character streams. The methods that a
subclass must implement are write(char[], int, int), flush(), and close(). Most subclasses will
override some of the methods defined here to provide higher efficiency, functionality or both.
Task 03: Read following line from a file and calculate the sum of last two
digits
Hint: use function readline() of BufferredReader to read the line and then use
lineRead.split(“,”) to split the line read from file.
Task 04: Read following paragraph from a file and write it on another file
using Filewriter and Filereader.
Developing writers can often benefit from examining an essay, a paragraph, or even a
sentence to determine what makes it effective. On the following pages are several paragraphs
for you to evaluate on your own, along with the Writing Center's explanation.
Note: These passages are excerpted from actual student papers and retain the original
wording. Some of the sentences are imperfect, but we have chosen these passages to highlight
areas in which the author was successful.
QUESTIONS
Please Fill the blank space with respective answers to following questions:
import java.io.*;
import java.util.*;
public class FileTest {
public static void main(String args[]) throws IOException
{
FileWriter fw = new FileWriter("ScanText.txt");
fw.write("1 9.1 3 4 5.1 7.1 so on 2.6");
fw.close();
FileReader fr = new FileReader("ScanText.txt");
Scanner scanner = new Scanner(fr);
while (scanner.hasNext()) {
if (scanner.hasNextDouble()) {
System.out.print(scanner.nextDouble() + ",");
} else
break;
}
fr.close();
}
}
THE END