Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 33

LAB MANUAL

Department of Computer Engineering

COMP 4.6 Java Programming


SE Computer Engineering (Semester IV), (RC 2016)

January 2020-May 2020

Faculty-In-Charge : Ms. Fiona Coutinho


Ms. Andrea

PADRE CONCEIÇÃO COLLEGE OF ENGINEERING


VERNA GOA, 403722
Course learning objectives (CLOs) :
The subject aims to provide the student with:

1. An understanding of how things work in the web world.

2. An understanding of the client-side implementation of web applications.

3. An ability to understand the generic principles of object oriented programming using


“Java”.

4. An understanding the use of Graphics programming in “Java”.

5. An ability to plan, design, execute and document sophisticated object oriented


programs to handle different computing problems using “Java”.

Course Outcomes (COs).


At the end of this course, the student will be able to:

1. Understand the principles of object oriented programming, operations of common


data structures and java collections, Packages and interfaces, concepts of Applet
and Graphics programming
2. Describe and Apply the different object oriented concepts in java to solve a given
problem
3. Compare and Analyze purpose of different concepts used in java
4. Develop standalone and web based java applications using the concepts of core
java, Applet and Graphics programming

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 2
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,
PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 3
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
List of Experiments

1. Write java programs to: CO1/2/3/4 CL4

a.Create classes and use different types of functions


b.show purpose of constructor.

c.Count the number of objects created for a class using static member function

2. Write programs on interfaces. CO1/2/3/4 CL4

3. Write programs on packages. CO1/2/3/4 CL4

4. Write programs using function overloading. CO1/2/3/4 CL4

5. Write Programs using inheritance. CO1/2/3/4 CL4

6. Write Programs using files. CO1/2/3/4 CL4

7. Write a program using exception handling mechanism. CO1/2/3/4 CL4

8. Write Programs using AWT. CO1/2/3/4 CL4

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 4
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
Exp1: Basic Java Programs Date:20th January 2020

Aim: Write the following java programs to understand the basics of java:

A.Create classes and use different types of functions


B.Show purpose of constructor

C.Count the number of objects created for a class using static member function

Theory:

Java Classes/Objects:

Java is an object-oriented programming language.Everything in Java is associated


with classes and objects, along with its attributes and methods. For example: in real
life, a car is an object. The car has attributes, such as weight and color, and
methods, such as drive and brake.

A. Create a Class

To create a class, use the keyword class:

So lets Create a class named "MyClass" with a variable x:

public class MyClass {


int x = 5;
}

Create an Object
To create an object of MyClass, specify the class name, followed by the object name,
and use the keyword new:

Create an object called "myObj" and print the value of x:


public class MyClass {
int x = 5;

public static void main(String[] args) {


MyClass myObj = new MyClass();
System.out.println(myObj.x);
}

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 5
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
}

Java Class Methods:

Static vs. Non-Static


You will often see Java programs that have either static or public attributes and
methods.

In the example above, we created a static method, which means that it can be
accessed without creating an object of the class, unlike public, which can only be
accessed by objects:

public class MyClass {


// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating
objects");
}

// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}

// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would compile an error

MyClass myObj = new MyClass(); // Create an object of MyClass


myObj.myPublicMethod(); // Call the public method on the object
}
}

B.Java Constructors

A constructor in Java is a special method that is used to initialize objects. The


constructor is called when an object of a class is created. It can be used to set initial
values for object attributes:

Create a constructor:

// Create a MyClass class

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 6
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
public class MyClass {
int x; // Create a class attribute

// Create a class constructor for the MyClass class


public MyClass() {
x = 5; // Set the initial value for the class attribute x
}

public static void main(String[] args) {


MyClass myObj = new MyClass(); // Create an object of class MyClass (This
will call the constructor)
System.out.println(myObj.x); // Print the value of x
}
}

// Outputs 5

Note that the constructor name must match the class name, and it cannot have a
return type (like void).

Also note that the constructor is called when the object is created.

All classes have constructors by default: if you do not create a class constructor
yourself, Java creates one for you. However, then you are not able to set initial values
for object attributes.

Constructor Parameters
Constructors can also take parameters, which is used to initialize attributes.

The following example adds an int y parameter to the constructor. Inside the
constructor we set x to y (x=y). When we call the constructor, we pass a parameter
to the constructor (5), which will set the value of x to 5:

public class MyClass {


int x;

public MyClass(int y) {
x = y;
}
public static void main(String[] args) {
MyClass myObj = new MyClass(5);
System.out.println(myObj.x);
}
}
LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,
PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 7
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
// Outputs 5

C. static member function:Count the number of objects created for a class using static
member function
Static variable example in Java

class VariableDemo
{
static int count=0;
public void increment()
{
count++;
}
public static void main(String args[])
{
VariableDemo obj1=new VariableDemo();
VariableDemo obj2=new VariableDemo();
obj1.increment();
obj2.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
}
}
Output:

Obj1: count is=2


Obj2: count is=2
Example 2: Static Variable can be accessed directly in a static method

class JavaExample{
static int age;
static String name;
//This is a Static Method
static void disp(){
System.out.println("Age is: "+age);
System.out.println("Name is: "+name);
}
// This is also a static method
public static void main(String args[])
{
age = 30;
name = "Steve";
disp();
}
}
Output: Age is: 30

Name is: Steve

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 8
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
Submission date: 3rd February 2020-For the Monday batch students (for others their
corresponding respective practical sessions)
Exp2: Function Overloading Date: 3rd February 2020

Aim: Write java program to implement function overloading


Theory:
function Overloading in Java with examples: is a feature that allows a class to have more than
one method having the same name, if their argument lists are different. It is similar to
constructor overloading in Java, that allows a class to have more than one
constructor having different argument lists.
Three ways to overload a method
In order to overload a method, the argument lists of the methods must differ
in either of these:
1. Number of parameters.
For example: This is a valid case of overloading

add(int, int)
add(int, int, int)
2. Data type of parameters.
For example:

add(int, int)
add(int, float)
3. Sequence of Data type of parameters.
For example:

add(int, float)
add(float, int)
Invalid case of method overloading:
When I say argument list, I am not talking about return type of the method,
for example if two methods have same name, same parameters and have
different return type, then this is not a valid method overloading example.
This will throw compilation error.

int add(int, int)


float add(int, int)

Method overloading is an example of Static Polymorphism

Points to Note:
1. Static Polymorphism is also known as compile time binding or early
binding.

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 9
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
2. Static binding happens at compile time. Method overloading is an
example of static binding where binding of method call to its definition
happens at Compile time.

Method Overloading examples


class DisplayOverloading
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(char c, int num)
{
System.out.println(c + " "+num);
}
}
class Sample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}
Output:

a
a 10

In the above example – method disp() is overloaded based on the number of


parameters – We have two methods with the name disp but the parameters they have
are different. Both are having different number of parameters.

Example 2: Overloading – Difference in data type of


parameters
In this example, method disp() is overloaded based on the data type of
parameters – We have two methods with the name disp(), one with
parameter of char type and another method with the parameter of int type.

class DisplayOverloading2
{
public void disp(char c)
{
System.out.println(c);

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 10
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
}
public void disp(int c)
{
System.out.println(c );
}
}

class Sample2
{
public static void main(String args[])
{
DisplayOverloading2 obj = new DisplayOverloading2();
obj.disp('a');
obj.disp(5);
}
}
Output:

a
5

Example3: Overloading – Sequence of data type of


arguments
Here method disp() is overloaded based on sequence of data type of
parameters – Both the methods have different sequence of data type in
argument list. First method is having argument list as (char, int) and second
is having (int, char). Since the sequence is different, the method can be
overloaded without any issues.

class DisplayOverloading3
{
public void disp(char c, int num)
{
System.out.println("I’m the first definition of method disp");
}
public void disp(int num, char c)
{
System.out.println("I’m the second definition of method disp" );
}
}
class Sample3
{
public static void main(String args[])
{
DisplayOverloading3 obj = new DisplayOverloading3();
obj.disp('x', 51 );
obj.disp(52, 'y');
}
}

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 11
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
Output:

I’m the first definition of method disp


I’m the second definition of method disp

Submission date: 10rd February 2020-For the Monday batch students (for others their
corresponding respective practical sessions)

Exp3: Packages Date: 10rd February 2020

Aim: Implement packages in java

Theory:

Java Packages & API


A package in Java is used to group related classes. Think of it as a folder in a file
directory. We use packages to avoid name conflicts, and to write a better
maintainable code. Packages are divided into two categories:

 Built-in Packages (packages from the Java API)


 User-defined Packages (create your own packages)

Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in the
Java Development Environment.

The library contains components for managing input, database programming, and
much much more. The complete list can be found at Oracles website:
https://docs.oracle.com/javase/8/docs/api/.

The library is divided into packages and classes. Meaning you can either import a
single class (along with its methods and attributes), or a whole package that contain
all the classes that belong to the specified package.

To use a class or a package from the library, you need to use the import keyword:

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 12
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
Syntax
import package.name.Class; // Import a single class

import package.name.*; // Import the whole package

Import a Class
If you find a class you want to use, for example, the Scanner class, which is used to
get user input, write the following code:

import java.util.Scanner;

In the example above, java.util is a package, while Scanner is a class of the


java.util package.

To use the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class documentation. In our example, we will use the
nextLine() method, which is used to read a complete line:

Example
Using the Scanner class to get user input:

import java.util.Scanner;

class MyClass {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in);

System.out.println("Enter username");

String userName = myObj.nextLine();

System.out.println("Username is: " + userName);

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 13
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
Import a Package
There are many packages to choose from. In the previous example, we used the
Scanner class from the java.util package. This package also contains date and
time facilities, random-number generator and other utility classes.

To import a whole package, end the sentence with an asterisk sign ( *). The following
example will import ALL the classes in the java.util package:

import java.util.*;

User-defined Packages
To create your own package, you need to understand that Java uses a file system
directory to store them. Just like folders on your computer:

Example
└── root
└── mypack
└── MyPackageClass.java

To create a package, use the package keyword:

MyPackageClass.java
package mypack;

class MyPackageClass {

public static void main(String[] args) {

System.out.println("This is my package!");

Save the file as MyPackageClass.java, and compile it:

C:\Users\Your Name>javac MyPackageClass.java

Then compile the package:

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 14
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
C:\Users\Your Name>javac -d . MyPackageClass.java
This forces the compiler to create the "mypack" package.

The -d keyword specifies the destination for where to save the class file. You can use
any directory name, like c:/user (windows), or, if you want to keep the package
within the same directory, you can use the dot sign ".", like in the example above.

Note: The package name should be written in lower case to avoid conflict with class
names.

When we compiled the package in the example above, a new folder was created,
called "mypack".

To run the MyPackageClass.java file, write the following:

C:\Users\Your Name>java mypack.MyPackageClass

The output will be:

This is my package!

Submission date: 17rd February 2020-For the Monday batch students (for others their
corresponding respective practical sessions)

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 15
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
Exp. No. 4) Inheritance Date: 17th February 2020

Aim: Implement inheritance using java programming

Theory:

Java Inheritance (Subclass and


Superclass)
In Java, it is possible to inherit attributes and methods from one class to another. We
group the "inheritance concept" into two categories:

 subclass (child) - the class that inherits from another class


 superclass (parent) - the class being inherited from

To inherit from a class, use the extends keyword.

In the example below, the Car class (subclass) inherits the attributes and methods
from the Vehicle class (superclass):

class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}

class Car extends Vehicle {


LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,
PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 16
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {

// Create a myCar object


Car myCar = new Car();

// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();

// Display the value of the brand attribute (from the Vehicle class) and
the value of the modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}

Did you notice the protected modifier in Vehicle?

We set the brand attribute in Vehicle to a protected access modifier. If it was set to
private, the Car class would not be able to access it.

Why And When To Use "Inheritance"?


- It is useful for code reusability: reuse attributes and methods of an existing class
when you create a new class.

The final Keyword


If you don't want other classes to inherit from a class, use the final keyword:

If you try to access a final class, Java will generate an error:

final class Vehicle {

...

class Car extends Vehicle {

...

The output will be something like this:

Car.java:8: error: cannot inherit from final Vehicle


class Car extends Vehicle {

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 17
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
                  ^
1 error)

Example with inheritance and polymorphism:

class Animal {

public void animalSound() {

System.out.println("The animal makes a sound");

class Pig extends Animal {

public void animalSound() {

System.out.println("The pig says: wee wee");

class Dog extends Animal {

public void animalSound() {

System.out.println("The dog says: bow wow");

class MyMainClass {

public static void main(String[] args) {

Animal myAnimal = new Animal(); // Create a Animal object

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

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 18
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
Animal myDog = new Dog(); // Create a Dog object

myAnimal.animalSound();

myPig.animalSound();

myDog.animalSound();

Submission date: 2nd March 2020-For the Monday batch students (for others their corresponding
respective practical sessions)

Exp. No. 5. Interfaces Date: 2nd March 2020


Aim:Implement interfaces using java programming

Theory:

Java Interface
Another way to achieve abstraction in Java, is with interfaces.

An interface is a completely "abstract class" that is used to group related methods


with empty bodies:

// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}
To access the interface methods, the interface must be "implemented" (kinda like
inherited) by another class with the implements keyword (instead of extends). The
body of the interface method is provided by the "implement" class:
// 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 {

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 19
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}

class MyMainClass {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}

Notes on Interfaces:

 Like abstract classes, interfaces cannot be used to create objects (in the
example above, it is not possible to create an "Animal" object in the
MyMainClass)
 Interface methods do not have a body - the body is provided by the
"implement" class
 On implementation of an interface, you must override all of its methods
 Interface methods are by default abstract and public
 Interface attributes are by default public, static and final
 An interface cannot contain a constructor (as it cannot be used to create
objects)

Why And When To Use Interfaces?


1) To achieve security - hide certain details and only show the important details of an
object (interface).

2) Java does not support "multiple inheritance" (a class can only inherit from one
superclass). However, it can be achieved with interfaces, because the class can
implement multiple interfaces. Note: To implement multiple interfaces, separate
them with a comma (see example below).

Multiple Interfaces
To implement multiple interfaces, separate them with a comma:

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 20
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
interface FirstInterface {
public void myMethod(); // interface method
}

interface SecondInterface {
public void myOtherMethod(); // interface method
}

class DemoClass implements FirstInterface, SecondInterface {


public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}

class MyMainClass {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}

Submission date: 16th March 2020-For the Monday batch students (for others their corresponding
respective practical sessions)

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 21
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
Exp. No. 6. Files Handling Date: 16th March 2020

Aim: Write programs to interact with files using java

Theory:

Java File Handling


The File class from the java.io package, allows us to work with files.

To use the File class, create an object of the class, and specify the filename or
directory name:

import java.io.File; // Import the File class

File myObj = new File("filename.txt"); // Specify the filename

Create a File
To create a file in Java, you can use the createNewFile() method. This method
returns a boolean value: true if the file was successfully created, and false if the file
already exists. Note that the method is enclosed in a try...catch block. This is
necessary because it throws an IOException if an error occurs (if the file cannot be
created for some reason):

import java.io.File; // Import the File class

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 22
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
import java.io.IOException; // Import the IOException class to handle errors

public class CreateFile {


public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

The output will be:

File created: filename.txt

To create a file in a specific directory (requires permission), specify the path of the file
and use double backslashes to escape the "\" character (for Windows). On Mac and
Linux you can just write the path, like: /Users/name/filename.txt

Example
File myObj = new File("C:\\Users\\MyName\\filename.txt");

Write To a File
In the following example, we use the FileWriter class together with its write()
method to write some text to the file we created in the example above. Note that
when you are done writing to the file, you should close it with the close() method:

import java.io.FileWriter; // Import the FileWriter class

import java.io.IOException; // Import the IOException class to handle


errors

public class WriteToFile {

public static void main(String[] args) {

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 23
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
try {

FileWriter myWriter = new FileWriter("filename.txt");

myWriter.write("Files in Java might be tricky, but it is fun


enough!");

myWriter.close();

System.out.println("Successfully wrote to the file.");

} catch (IOException e) {

System.out.println("An error occurred.");

e.printStackTrace();

The output will be:

Successfully wrote to the file.

Read a File
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files

public class ReadFile {


public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 24
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
The output will be:

Files in Java might be tricky, but it is fun enough!

Get File Information


To get more information about a file, use any of the File methods:

Example
import java.io.File; // Import the File class

public class GetFileInfo {


public static void main(String[] args) {

File myObj = new File("filename.txt");

if (myObj.exists()) {

System.out.println("File name: " + myObj.getName());

System.out.println("Absolute path: " + myObj.getAbsolutePath());

System.out.println("Writeable: " + myObj.canWrite());

System.out.println("Readable " + myObj.canRead());

System.out.println("File size in bytes " + myObj.length());

} else {

System.out.println("The file does not exist.");

The output will be:

File name: filename.txt


Absolute path: C:\Users\MyName\filename.txt
Writeable: true
Readable: true
File size in bytes: 0

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 25
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
Note: There are many available classes in the Java API that can be used to read and
write files in Java: FileReader, BufferedReader, Files, Scanner,
FileInputStream, FileWriter, BufferedWriter, FileOutputStream , etc. Which
one to use depends on the Java version you're working with and whether you need to
read bytes or characters, and the size of the file/lines etc.

Delete a File
To delete a file in Java, use the delete() method:

import java.io.File; // Import the File class

public class DeleteFile {

public static void main(String[] args) {

File myObj = new File("filename.txt");

if (myObj.delete()) {

System.out.println("Deleted the file: " + myObj.getName());

} else {

System.out.println("Failed to delete the file.");

The output will be:

Deleted the file: filename.txt

Submission date: 30th March 2020-For the Monday batch students (for others their corresponding
respective practical sessions)

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 26
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
Exp. No. 7. Exception handling Date: 30th March 2020

Aim: Implement Exception handling using java.


Theory:

Java Exceptions
When executing Java code, different errors can occur: coding errors made by the
programmer, errors due to wrong input, or other unforeseeable things.

When an error occurs, Java will normally stop and generate an error message. The
technical term for this is: Java will throw an exception (throw an error).

Java try and catch


The try statement allows you to define a block of code to be tested for errors while it
is being executed.

The catch statement allows you to define a block of code to be executed, if an error
occurs in the try block.

The try and catch keywords come in pairs:

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 27
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}

This will generate an error, because myNumbers[10] does not exist.

public class MyClass {

public static void main(String[ ] args) {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[10]); // error!

The output will be something like this:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10


        at MyClass.main(MyClass.java:4)

The finally statement lets you execute code, after try...catch, regardless of the
result:

public class MyClass {

public static void main(String[] args) {

try {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[10]);

} catch (Exception e) {

System.out.println("Something went wrong.");

} finally {

System.out.println("The 'try catch' is finished.");

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 28
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
}

The output will be:

Something went wrong.


The 'try catch' is finished.

Submission date: April 6th 2020-For the Monday batch students (for others their corresponding
respective practical sessions)

Exp. No. 8. AWT Date: April 6th 2020

Aim: Create a Applet using awt package in java

Theory:

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based


applications in java.

Java AWT components are platform-dependent i.e. components are displayed according to the view
of operating system. AWT is heavyweight i.e. its components are using the resources of OS.

The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

Figure below shows hierarchy of java AWT classes:

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 29
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.

Window
The window is the container that have no borders and menu bars. You must use frame, dialog or
another window for creating a window.

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 30
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.

Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.

Useful Methods of Component class


Method Description

public void add(Component c) inserts a component on this component.

public void setSize(int width,int sets the size (width and height) of the
height) component.

public void setLayout(LayoutManager defines the layout manager for the component.
m)

public void setVisible(boolean status) changes the visibility of the component, by


default false.

Java AWT Example


To create simple awt example, you need a frame. There are two ways to create a frame in AWT.

o By extending Frame class (inheritance)


o By creating the object of Frame class (association)

AWT Example by Inheritance


Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing
Button component on the Frame.

import java.awt.*;
class First extends Frame{
First(){

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 31
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}}

AWT Example by Association


Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are
showing Button component on the Frame.

import java.awt.*;  
class First2{  
First2(){  
Frame f=new Frame();  
Button b=new Button("click me");  
b.setBounds(30,50,80,30);  
f.add(b);  
f.setSize(300,300);  
f.setLayout(null);  
f.setVisible(true);  
}  

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 32
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE
public static void main(String args[]){  
First2 f=new First2();  
}}  

Submission date: April 20th 2020-For the


Monday batch students (for others their corresponding respective practical sessions)

File Certification : Will be done on the Last practical of the


semester -27th April 2020 Monday from 9am-11am in the lab
Note :No files will be certified after the above mentioned date
/time

LAB MANUAL – JAVA PROGRAMMING, SE COMPUTER ENGINEERING (SEM IV), 2019-20,


PADRE CONCEICAO COLLEE OF ENGINEERING, VERNA GOA. 33
STAFF IN CHARGE : MS. FIONA COUTINHO / MR.AMOGH/MR.LANCE

You might also like