Java Lab Manual - Final
Java Lab Manual - Final
Java Lab Manual - Final
c.Count the number of objects created for a class using static member function
Aim: Write the following java programs to understand the basics of java:
C.Count the number of objects created for a class using static member function
Theory:
Java Classes/Objects:
A. Create a Class
Create an Object
To create an object of MyClass, specify the class name, followed by the object name,
and use the keyword new:
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 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
B.Java Constructors
Create a constructor:
// 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 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:
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
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.
Points to Note:
1. Static Polymorphism is also known as compile time binding or early
binding.
a
a 10
class DisplayOverloading2
{
public void disp(char 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
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');
}
}
Submission date: 10rd February 2020-For the Monday batch students (for others their
corresponding respective practical sessions)
Theory:
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:
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;
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 {
System.out.println("Enter username");
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
MyPackageClass.java
package mypack;
class MyPackageClass {
System.out.println("This is my 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".
This is my package!
Submission date: 17rd February 2020-For the Monday batch students (for others their
corresponding respective practical sessions)
Theory:
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!");
}
}
// 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);
}
}
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.
...
...
class Animal {
class MyMainClass {
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
Submission date: 2nd March 2020-For the Monday batch students (for others their corresponding
respective practical sessions)
Theory:
Java Interface
Another way to achieve abstraction in Java, is with interfaces.
// 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)
}
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)
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:
interface SecondInterface {
public void myOtherMethod(); // interface method
}
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)
Theory:
To use the File class, create an object of the class, and specify the filename or
directory name:
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):
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:
myWriter.close();
} catch (IOException e) {
e.printStackTrace();
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
Example
import java.io.File; // Import the File class
if (myObj.exists()) {
} else {
Delete a File
To delete a file in Java, use the delete() method:
if (myObj.delete()) {
} else {
Submission date: 30th March 2020-For the Monday batch students (for others their corresponding
respective practical sessions)
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).
The catch statement allows you to define a block of code to be executed, if an error
occurs in the try block.
System.out.println(myNumbers[10]); // error!
The finally statement lets you execute code, after try...catch, regardless of the
result:
try {
System.out.println(myNumbers[10]);
} catch (Exception e) {
} finally {
Submission date: April 6th 2020-For the Monday batch students (for others their corresponding
respective practical sessions)
Theory:
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.
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.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
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)
import java.awt.*;
class First extends Frame{
First(){
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);
}