0% found this document useful (0 votes)
17 views8 pages

Unit-2 in Simple Way

Java unit 2

Uploaded by

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

Unit-2 in Simple Way

Java unit 2

Uploaded by

Sarika Punna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Unit-2

1. What is meant by data abstraction? How to achieve data abstraction(abstract classes and
interfaces) in java. How to inherit an extend interface to another?(V.imp) (or)
2. What is interface? Write a java program to illustrate the use of interface(V.imp)

Abstraction

Abstraction in Java is a process of hiding the implementation details from the user and showing
only the functionality to the user.
Abstraction in Java can be achieved using
a. Abstract classes
 In Java a class preceded by abstract keyword is called abstract class.
 An abstract class may or may not have abstract methods.
 We cannot create object for abstract class.
 It is used to achieve abstraction but it does not provide 100% abstraction because it can have
concrete methods.
 It can have abstract and non-abstract methods.
 Abstract methods should be present inside abstract class only.
 Abstract class need to be inherited by other class (extended) and its abstract methods need to
be overridden. Hence in abstract class only the abstract methods are overridden.
 Abstract class can contain constructors and static methods too but they are not declared
abstract.
 Note : Remember that abstract class cannot be instantiated , i.e. we can’t create an object of an
abstract class , but can only create a reference variable to refer to other class object which is
helpful in run-time polymorphism.
o Syntax : abstract class class_name {
}

AbstractClassExample

abstract class animal


{
// objects cannot be created
}
class Dog extends animal
{

class AbstractClassEx
{
public static void main(String[] args)
{
animal r=new Dog(); // superclass has capability of storing childclass objects
}
}
Abstract method
 Method that are declared without any body within an abstract class are called abstract method.
 Syntax: abstract return_type function_name (); //No definition
 The method body will be defined by its subclass.
 Abstract method can never be final and static. Any class that extends an abstract class must
implement all the abstract methods.

AbstractMethodExample

abstract class animal //abstract class


{
public abstract void sound(); //abstract method
}

class Dog extends animal


{
@override
public void sound()
{
System.out.println("Dog is Barking");
}
}

class Lion extends animal


{
@override
public void sound()
{
System.out.println("Lion is roaring");
}
}

class AbstractMethodEx
{
public static void main(String[] args)
{
Dog d=new Dog();
d.sound();
Lion l=new Lion();
l.sound();
}
}

b. Interfaces
 Interface in Java is the way to achieve complete abstraction. Also interface in Java is used to
achieve multiple inheritance by implementing interfaces.
 Interface is similar to class and contains only public, abstract methods and public, static and final
fields. Interfaces differ from class in the way that interface cannot contains constructors and non
– abstract methods. Also interfaces cannot be instantiated.
 Interfaces should be implemented by using implements The class that implements the interface
should define all the methods of interface and the method should be declared public.
 Interface only tells what a class contains and the behavior is defined in the class that implements
it. Advantages
Reduces complexity, Avoid code duplication, Eases the burden of maintenance,Increase security
and confidentiality

Interface Example

import java.util.Scanner;
interface client
{
void input(); //public and abstract methods
void output();
}
class Customer implements client
{
String name; double salary;
public void input()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter your name:");
name=s.nextLine();
System.out.println("Enter your salary:");
salary=s.nextInt();
}
public void output()
{
System.out.println("Enter your name:"+name);
System.out.println("Enter your salary:"+salary);
}
}
class InterfacesEx
{
public static void main(String[] args)
{
client c=new Customer();
c.input();
c.output();
}
}
3. Define a package. How to import packages? Explain with illustrations. (V.imp)
Packages in java are like container which keeps classes, interfaces and sub-packages in an
organized way. You can visualize packages as folders in your computer. Folder houses sub-folders
and other files.
Similarly, Java package contains collection of related classes, interfaces and sub-packages.
Advantages:
The main objectives of packages are:
a. To resolve name confects.
b. To improve modularity of the application.
c. To provide security.
d. Easy to locate the related classes
e. Reuse the existing classes in packages

Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Some of the existing packages in Java are −

1. java.lang: Contains language support classes(e.g classed which defines primitive data
types,math operations). This package is automatically imported.
2. java.io: Contains classed for supporting input / output operations.
3. java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support; for Date / Time operations.

Import statement

 import: This is the Java keyword used to indicate that you are importing a class or
package.
 packageName: This is the name of the package containing the class you want to import.
 ClassName: This is the name of the class (or other type) you want to import from the
specified package.
 the import statement is used to bring classes, interfaces, and other types defined in
other packages into the current file's scope.
 It simplifies the usage of classes from different packages by allowing you to refer to
them directly by their simple names, rather than their fully qualified names (which
include the package name).
 Syntax: import java.packageName.ClassName;

Compiling java Package file

package com.datasciencea;
class Packages
{
public static void main(String[] args)
{
System.out.println("Package demonstration");
}
}
 compiling Java programs Inside packages
 javac -d . Packages.java
Executing java Package file
 Fully qualified path we should write inorder to execute.
 java com/datasciencea/Packages

4. What is CLASSPATH? Discuss about CLASSPATH environment variables(V.imp)


The CLASSPATH is an environment variable in Java that specifies a set of directories or JAR files
where the Java Virtual Machine (JVM) should look for classes and resources when running Java
programs. It essentially defines the locations where the JVM should search for class files when
trying to load a class that is not part of the Java Standard Library or the current working
directory. The CLASSPATH is used to resolve dependencies for Java applications.
Here are some key points about the CLASSPATH environment variable:

a. Purpose: The primary purpose of CLASSPATH is to tell the JVM where to find user-
defined classes and resources that are not part of the standard Java library.
b. Search Order: When a Java program attempts to load a class, the JVM looks for it in the
directories and JAR files specified in the CLASSPATH. It searches for classes in the order
they are listed in the CLASSPATH.
c. Default Value: If you do not explicitly set the CLASSPATH, the JVM uses a default
classpath, which includes the current directory (.). However, it's considered a best
practice to set the CLASSPATH explicitly for your application to avoid unexpected
behavior.
d. Setting CLASSPATH: You can set the CLASSPATH in several ways:
 Environment Variable: You can set it as an environment variable on your system.

5. Demonstrate about File Input Stream and File Output Stream (V.imp)
In Java, FileInputStream and FileOutputStream are classes that allow you to read data from a file
(input) and write data to a file (output), respectively. They are part of the java.io package and are
commonly used for working with files. Below, I'll provide examples of how to use
FileInputStream and FileOutputStream to read from and write to a file.

a. FileInputStream (Reading from a File)

Here's an example of using FileInputStream to read data from a file:

import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamExample {


public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("example.txt");
int byteData;

// Read bytes from the file until the end is reached (-1 indicates end of file)
while ((byteData = fis.read()) != -1) {
System.out.print((char) byteData); // Convert byte to char and print
}

fis.close(); // Close the FileInputStream when done


} catch (IOException e) {
e.printStackTrace();
}
}
}

b. FileOutputStream (Writing to a File)

Now, let's see how to use FileOutputStream to write data to a file:

import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamExample {


public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("output.txt");
String data = "Hello, World!";

// Convert the string to bytes and write it to the file


byte[] byteData = data.getBytes();
fos.write(byteData);

fos.close(); // Close the FileOutputStream when done


System.out.println("Data has been written to output.txt.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

6. Explain about Random access file operations with an example(V.imp)


Random access file operations in Java allow you to read and write data at any position within a
file, rather than sequentially from the beginning to the end. This means you can jump to a
specific location within the file and perform read and write operations at that position. Java
provides the RandomAccessFile class to work with random access files.

Here's an explanation of random access file operations with an example:


import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessEx
{
public static void main(String[] args) throws IOException
{
RandomAccessFile raf = new RandomAccessFile("Random.txt","r");
raf.seek(4);
byte[] bytes = new byte[12];
raf.read(bytes);
raf.close();
//String dta=new String(bytes);
//System.out.println(data);
System.out.println(new String(bytes));
}
}
7. Wrire about a) Wrapper classes
a. All the primitive data types in java have defined using the class concept, these classes known
as wrapper classes.
b. In java, every primitive type has its corresponding wrapper class defined in the java.lang
package.
The following table shows the primitive type and its corresponding wrapper class.

b) Auto Boxing
The process of converting a primitive type value into its corresponding wrapper class object is
called autoboxing or simply boxing. For example, converting an int value to an Integer class
object.
The compiler automatically performs the autoboxing when a primitive type value has assigned to
an object of the corresponding wrapper class.

8. Write java program to copy content of one file to another file.


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopyExample {


public static void main(String[] args) {
// Define the source and destination file names
String sourceFileName = "source.txt";
String destinationFileName = "destination.txt";

try {
// Create a FileInputStream for the source file
FileInputStream fis = new FileInputStream(sourceFileName);

// Create a FileOutputStream for the destination file


FileOutputStream fos = new FileOutputStream(destinationFileName);

// Define a buffer to hold the data being copied


byte[] buffer = new byte[1024];
int bytesRead;

// Read data from the source file and write it to the destination file
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}

// Close the FileInputStream and FileOutputStream


fis.close();
fos.close();

System.out.println("File copied successfully.");


} catch (IOException e) {
e.printStackTrace();
}
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy