0% found this document useful (0 votes)
7 views

Java Unit 3B

Uploaded by

pandu mandala
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Java Unit 3B

Uploaded by

pandu mandala
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

JAVA UNIT - 3B:

1. Define package.Explain the process of compiling and running Java package program.
2. Define and discuss package concept in Java with an example.
Ans: In Java, a package is a way of organizing classes and interfaces into namespaces for easier
management and access control. Packages help in avoiding naming conflicts between classes,
provide better modularity, and facilitate code reuse.
Create the Package Structure:
• Decide on a package name (usually a reversed domain name like
com.example.mypackage).
• Create directories corresponding to the package name.
• Place your Java source files within these directories.
mypackage/ ── MyProgram.java
Write Java Classes within the Package:
Write your Java classes, making sure to include the package declaration at the beginning of each
source file.
package mypackage;
public class MyProgram {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
Compile the Java Program:
• Open a terminal/command prompt.
• Navigate to the directory containing your Java source files.
• Compile the source file using the ‘javac’ command, specifying the path to your main
source file.
javac mypackage/MyProgram.java
Run the Java Program:
While still in the same directory, execute the compiled Java program using the java command,
specifying the fully qualified name of the main class (including the package name).
java mypackage.MyProgram
3. List and explain the types of access modifiers in Java.
Ans: Public:
• The public access modifier allows unrestricted access to the class, method, or variable from
any other class or package.
• Public members can be accessed by any other class in the same package or from any other
package.
• It is the least restrictive access modifier.
public class MyClass {
public int myPublicVar;
public void myPublicMethod() {
// Method implementation
}
}
Private:
• The private access modifier restricts access to the class, method, or variable to within the
same class only.
• Private members cannot be accessed or referenced from outside the class in which they are
declared.
• It is the most restrictive access modifier.
public class MyClass {
private int myPrivateVar;
private void myPrivateMethod() {
// Method implementation
}
}
Protected:
• The protected access modifier allows access to the class, method, or variable within the
same package or by subclasses (whether they are in the same package or different package).
• Protected members are not accessible to non-subclasses outside the package.
package mypackage;
public class MyClass {
protected int myProtectedVar;
protected void myProtectedMethod() {
// Method implementation
}
}
Default (Package-Private):
• If no access modifier is specified, the default access modifier is applied.
• The default access modifier restricts access to within the same package only.
• Members with default access are not accessible outside the package, even by
subclasses.
package mypackage;
class MyClass {
int myDefaultVar;
void myDefaultMethod() {
// Method implementation
}
}

4. How to access package from another package? Explain with examples.


Ans: Import Specific Class from a Package: If you want to import a specific class from a
package, you can use the import statement followed by the fully qualified name of the class.
import com.example.otherpackage.OtherClass;
public class MyClass {
public static void main(String[] args) {
OtherClass obj = new OtherClass();
// Use obj and its methods
}
}
Import Entire Package: You can also import the entire package using the import statement
followed by the package name. This imports all classes and interfaces from that package, allowing
you to use them in your current package without specifying their full names.
// Importing the entire package
import com.example.otherpackage.*;
public class MyClass {
public static void main(String[] args) {
OtherClass obj = new OtherClass();
// Use obj and its methods
}
}
Accessing Default (Package-Private) Classes: If you need to access classes with default access
(package-private) from another package, they must be in the same package or you need to include
the class in a subpackage of the current package.
// Package structure
com
└── example
└── mypackage
├── MyClass.java
└── util
└── UtilClass.java
Using Fully Qualified Name:
If you don't want to import the package or if you have conflicts between class names, you can use
the fully qualified name of the class to reference it.
public class MyClass {
public static void main(String[] args) {
com.example.otherpackage.OtherClass obj = new com.example.otherpackage.OtherClass();
// Use obj and its methods
}
}
5. How to set CLASSPATH in Java?
Ans:
In Java, the CLASSPATH is a system environment variable that tells the Java Virtual Machine
(JVM) where to look for user-defined classes and packages.
( i )Setting CLASSPATH Temporarily: You can set the CLASSPATH temporarily for the current
session using the -cp or -classpath option when compiling or running Java programs.
For compiling:
javac -cp /path/to/your/directory YourJavaFile.java
For running:
java -cp /path/to/your/directory YourMainClass
Replace /path/to/your/directory with the actual path where your classes or JAR files are located.
( ii )Setting CLASSPATH Permanently: You can set the CLASSPATH permanently by defining
it as a system environment variable.
On Unix/Linux/macOS:
Edit your shell configuration file (like .bashrc, .bash_profile, or .profile) and add the following
line:
export CLASSPATH=/path/to/your/directory
On Windows:
• Right-click on "My Computer" or "This PC" and select "Properties".
• Go to "Advanced system settings" > "Environment Variables".
• Under "System variables" or "User variables", click on "New" and add a variable named
CLASSPATH with the value set to the directory where your classes or JAR files are located.
It's important to note that setting CLASSPATH permanently may affect other Java applications
running on your system.

( iii )Using Wildcards: You can use wildcards (*) to include all JAR files or class files within a
directory or subdirectories.
export CLASSPATH=/path/to/your/directory/*
This includes all JAR files or class files within the specified directory.

Remember that setting CLASSPATH permanently may affect other Java applications running on
your system. It's generally recommended to set CLASSPATH temporarily within your project's
build or execution scripts, or to use build tools like Maven or Gradle for managing dependencies.
6. What is an environment variable.Explain the process of understanding the path and
classpath in java
Ans:
An environment variable is a dynamic-named value that can affect the way running
processes will behave on a computer. It typically holds information such as paths to
directories containing executable programs or data, or configuration information for
applications. Environment variables are part of the environment in which a process runs.
PATH:

• The PATH environment variable specifies directories in which the operating system
should look for executable programs.
• When you type a command in the command prompt or terminal, the operating
system searches through the directories listed in the PATH variable to find the
executable corresponding to that command.
Understanding the PATH in Java:
• To understand the PATH in Java, you need to know where your Java executable
(java and javac) is located.
• On Unix/Linux/macOS, you can use the which command to find the location of the
java executable:
which java
• On Windows, you can use the where command
where java
• Once you know the location, you can add it to your PATH environment variable so
that you can run Java commands from any directory without specifying the full path
to the executables.
CLASSPATH:

• The CLASSPATH environment variable specifies directories and JAR files that the
Java Virtual Machine (JVM) should search for class files.
• When you compile or run a Java program, the JVM searches for the necessary
classes and resources in the directories and JAR files specified in the CLASSPATH.
Understanding the CLASSPATH in Java:
• To understand the CLASSPATH in Java, you need to know where your Java classes
or JAR files are located.
• By default, Java looks for classes in the current directory. If your classes are located
in a different directory or in JAR files, you need to specify the CLASSPATH.
• You can set the CLASSPATH environment variable temporarily using the -cp or -
classpath option when compiling or running Java programs, as mentioned in the
previous answer.
• You can also set the CLASSPATH permanently as an environment variable, as
described earlier.
7.How to import Java package?
Ans:

In Java, you can import packages using the import statement. This statement allows you to use
classes and interfaces from other packages in your Java code

( i )Importing a Specific Class or Interface:


To import a specific class or interface from a package, use the import statement followed by the
fully qualified name of the class or interface.
import java.util.ArrayList;
import java.util.HashMap;
This imports the ArrayList and HashMap classes from the java.util package.

( ii )Importing an Entire Package:


To import all classes and interfaces within a package, use the import statement followed by the
package name followed by .*.
import java.util.*;
This imports all classes and interfaces within the java.util package.

( iii )Using Imported Classes and Interfaces:


Once you have imported a class or interface, you can use it in your code without specifying its
fully qualified name.
import java.util.ArrayList;
import java.util.List;
public class MyClass {
public static void main(String[] args) {
List<String> myList = new ArrayList<>();
// Use myList and other methods from java.util.ArrayList
}
}
In this example, ArrayList and List are imported from the java.util package, and you can use
them directly in the MyClass without prefixing them with java.util..

( iv )Using Static Imports:


You can also import static members (fields and methods) of a class using the import static
statement.
import static java.lang.Math.PI;
import static java.lang.Math.sqrt;
public class Circle {
public double calculateArea(double radius) {
return PI * sqrt(radius);
}
}
This imports the PI and sqrt constants from the java.lang.Math class, allowing you to use them
directly without prefixing Math..
8. Explain the process of importing a specific or all classes using packages.
Ans:

Importing a Specific Class or Interface:


To import a specific class or interface from a package, use the import statement followed by the
fully qualified name of the class or interface.
import java.util.ArrayList;
This imports the ArrayList class from the java.util package. After importing, you can use
ArrayList directly in your code without specifying its fully qualified name.

Importing All Classes and Interfaces from a Package:


To import all classes and interfaces within a package, use the import statement followed by the
package name followed by .*.
import java.util.*;
This imports all classes and interfaces within the java.util package. After importing, you can use
any class or interface from the java.util package directly in your code without specifying their
fully qualified names.

Using Imported Classes and Interfaces:


Once you have imported classes or interfaces, you can use them in your code without prefixing
them with their package name.
import java.util.ArrayList;
import java.util.List;
public class MyClass {
public static void main(String[] args) {
List<String> myList = new ArrayList<>();
// Use myList and other methods from java.util.ArrayList
}
}
In this example, ArrayList and List are imported from the java.util package, and you can use
them directly in the MyClass without prefixing them with java.util..

Avoiding Name Conflicts:


If there are classes or interfaces with the same name in different packages, importing them directly
can cause name conflicts. In such cases, you can use fully qualified names to avoid conflicts.
import java.util.ArrayList;
import java.awt.List;
public class MyClass {
public static void main(String[] args) {
java.util.List<String> myList = new ArrayList<>();
// Use myList from java.util.ArrayList
}
}
In this example, there's a List class in both java.util and java.awt packages. By using fully
qualified names, you can specify which List you want to use.
9. Compare and contrast String and StringBuffer classes.
Ans:

Both String and StringBuffer are classes used for handling strings in Java, but they have
some differences in terms of mutability, performance, and usage.

( i )Mutability:

String: Objects of the String class are immutable, meaning once a String object is created,
its value cannot be changed. Any operation that appears to modify a String actually creates
a new String object.
StringBuffer: Objects of the StringBuffer class are mutable, meaning you can modify the
contents of a StringBuffer object without creating a new object.

( ii )Performance:

String: Since String objects are immutable, operations that involve modifying or
concatenating strings can be inefficient, especially when dealing with a large number of
strings. Each concatenation operation creates a new String object, leading to unnecessary
memory allocation and garbage collection.
StringBuffer: StringBuffer objects are mutable, which makes them more efficient for
concatenating and modifying strings. StringBuffer uses a resizable buffer to store the string
content, and the operations modify the existing buffer rather than creating new objects.

( iii )Synchronization:

String: String objects are immutable and thread-safe. Multiple threads can safely access
and share String objects without any risk of data corruption.
StringBuffer: StringBuffer is designed to be thread-safe, meaning it includes
synchronization mechanisms to ensure that multiple threads can safely manipulate
StringBuffer objects without causing inconsistencies or race conditions. However, this
synchronization comes at a performance cost, making StringBuffer slightly slower than
StringBuilder (which is similar to StringBuffer but not synchronized).

( iv )Usage:

String: Use String when you need an immutable sequence of characters. String objects are
suitable for situations where the value of the string will not change frequently, such as
storing constants or representing textual data.
StringBuffer: use StringBuffer when you need a mutable sequence of characters,
especially in multi-threaded environments where thread safety is required. StringBuffer is
commonly used in scenarios where strings need to be dynamically constructed or modified,
such as string concatenation within loops or when building complex strings.
10. List and describe string handling functions.Explain with examples.
Ans:
String handling functions in Java are methods provided by the String class to perform various
operations on strings.

( i )charAt(int index): Returns the character at the specified index within the string.
String str = "Hello";
char ch = str.charAt(1); // Returns 'e'

( ii )length(): Returns the length of the string


String str = "Hello";
int length = str.length(); // Returns 5

( iii )substring(int beginIndex) or substring(int beginIndex, int endIndex):


Returns a substring of the original string starting from the specified index (inclusive) to the end of
the string, or from the specified begin index to the specified end index (exclusive).
String str = "Hello World";
String sub1 = str.substring(6); // Returns "World"
String sub2 = str.substring(0, 5); // Returns "Hello"

( iv )toUpperCase() and toLowerCase():


Converts all characters of the string to upper or lower case.
String str = "Hello";
String upperCaseStr = str.toUpperCase(); // Returns "HELLO"
String lowerCaseStr = str.toLowerCase(); // Returns "hello"

( v )indexOf(String str) or indexOf(String str, int fromIndex):


Returns the index of the first occurrence of the specified substring within the string, or -1 if the
substring is not found. The second version of the method searches for the substring starting from
the specified index.
String str = "Hello World";
int index1 = str.indexOf("l"); // Returns 2
int index2 = str.indexOf("l", 3); // Returns 3

( vi )startsWith(String prefix) and endsWith(String suffix):


Checks if the string starts or ends with the specified prefix or suffix and returns a boolean value.
String str = "Hello World";
boolean startsWithHello = str.startsWith("Hello"); // Returns true
boolean endsWithWorld = str.endsWith("World"); // Returns true

( vii )replace(char oldChar, char newChar) or replace(CharSequence target, CharSequence


replacement):
Replaces occurrences of a specified character or substring with another character or substring.
String str = "Hello World";
String replacedStr1 = str.replace('l', 'x'); // Returns "Hexxo Worxd"
String replacedStr2 = str.replace("World", "Java"); // Returns "Hello Java"
11. List and explain the primitive type Wrapper classes from java.lang.
Ans: Integer:
-----Represents a wrapper class for the primitive type int.
-----Provides methods to parse integers from strings, convert integers to strings, and perform
arithmetic operations.
Integer intValue = 10;
int parsedInt = Integer.parseInt("20");

Long:
-----Represents a wrapper class for the primitive type long.
-----Provides methods similar to Integer for working with long integers.
Long longValue = 1000000000L;
long parsedLong = Long.parseLong("2000000000");

Float:
----Represents a wrapper class for the primitive type float.
Provides methods for converting floats to strings, parsing floats from strings, and performing
floating-point arithmetic.
Float floatValue = 3.14f;
float parsedFloat = Float.parseFloat("2.718");

Double:
----Represents a wrapper class for the primitive type double.
-----Provides methods similar to Float for working with double-precision floating-point numbers.
Double doubleValue = 3.141592653589793;
double parsedDouble = Double.parseDouble("2.718281828459045");

Boolean: ----Represents a wrapper class for the primitive type boolean.


----Provides methods for converting booleans to strings, parsing booleans from strings, and logical
operations.
Boolean boolValue = true;
boolean parsedBoolean = Boolean.parseBoolean("false");

Character: ----Represents a wrapper class for the primitive type char.


---Provides methods for converting characters to strings and performing character comparisons.
Character charValue = 'A';

Byte: ----Represents a wrapper class for the primitive type byte.


-----Provides methods for converting bytes to strings and parsing bytes from strings.
Byte byteValue = 127;
byte parsedByte = Byte.parseByte("100");

Short: ----Represents a wrapper class for the primitive type short.


----Provides methods for converting shorts to strings and parsing shorts from strings.
Short shortValue = 32767;
short parsedShort = Short.parseShort("20000");
12. Discuss the static methods and variables of java.lang.System class.
Ans:
public static void exit(int status):
• Terminates the currently running Java Virtual Machine (JVM) with the given status code.
• This method is typically used to terminate the application when an unrecoverable error
occurs.

public static void gc():


• Requests the JVM to run the garbage collector to reclaim unused memory.
• Note that calling this method does not guarantee immediate execution of the garbage
collector.
public static long currentTimeMillis():
• Returns the current time in milliseconds since the Unix epoch (January 1, 1970, 00:00:00
UTC).
• This method is often used for measuring elapsed time or scheduling tasks.
public static Properties getProperties():

• Returns a Properties object containing system properties.


• System properties include information about the Java runtime environment, such as
version, operating system, and user-defined properties.
public static String getProperty(String key):
• Returns the value of the system property specified by the given key.
• Commonly used system property keys include "java.version", "java.home", "os.name", and
"user.home".
public static void setProperty(String key, String value):
• Sets the value of the system property specified by the given key to the provided value.
• This method allows modifying system properties programmatically.
public static String getenv(String name):
• Returns the value of the environment variable specified by the given name.
• Environment variables are platform-specific variables that hold information about the
system environment.
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length):
• Copies an array from the specified source array to the specified destination array.
• This method is useful for efficiently copying elements between arrays.
public static Console console():
• Returns a Console object representing the console, if available.
• This method provides access to the system console for reading input and printing output.
public static SecurityManager getSecurityManager():
• Returns the security manager currently installed in the JVM.
• The security manager is responsible for enforcing security policies within the Java runtime
environment.
public static void setOut(PrintStream out) and public static void setErr(PrintStream err):
• Sets the standard output and error streams to the specified PrintStream objects,
respectively.
• These methods allow redirecting output and error messages to custom streams.
13. What are input and output streams? Explain any one input stream class with example
Ans:

In Java, input and output streams are mechanisms for reading data from and writing data to various
sources and destinations, such as files, network connections, or in-memory buffers. Streams
provide a consistent way to handle input and output operations regardless of the underlying data
source or destination.

Input Streams: Input streams are used for reading data from a source. They provide methods to
read bytes or characters sequentially from the source.

Output Streams: Output streams are used for writing data to a destination. They provide methods
to write bytes or characters sequentially to the destination.

here's a simpler example demonstrating the usage of FileInputStream to read a file and display
its contents:

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

public class ReadFileExample {


public static void main(String[] args) {
String filePath = "example.txt"; // Path to the file

try (FileInputStream inputStream = new FileInputStream(filePath)) {


int byteRead;
while ((byteRead = inputStream.read()) != -1) {
System.out.print((char) byteRead);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

This example:

• Opens a FileInputStream for the file "example.txt".


• Reads the file byte by byte using the read() method until the end of the file is
reached (-1).
• Converts each byte to a character and prints it to the console.
• Handles any IOException that may occur during file reading.
• Uses try-with-resources to automatically close the input stream when done,
ensuring proper resource management without the need for a finally block.
14. Explain FileInputStream and FileOutputStream classes in java.io package.
Ans:

The FileInputStream and FileOutputStream classes are part of the java.io package in Java, and
they are used for reading from and writing to files, respectively.

FileInputStream:

• FileInputStream is a subclass of InputStream and is used to read data from a file as a stream
of bytes.
• It is typically used to read binary data or text data that does not require any special
processing.
• It opens a connection to the specified file and allows you to read bytes from it.
• It provides several read() methods to read bytes from the file, which return -1 when the end
of the file is reached.
FileInputStream inputStream = new FileInputStream("example.txt");
int data;
while ((data = inputStream.read()) != -1) {
// Process the byte read from the file
}
inputStream.close(); // Close the input stream when done

FileOutputStream:

• FileOutputStream is a subclass of OutputStream and is used to write data to a file as a


stream of bytes.
• It is typically used to write binary data or text data to a file.
• It opens a connection to the specified file and allows you to write bytes to it.
• It provides several write() methods to write bytes to the file.
• If the file specified in the constructor does not exist, a new file is created. If the file already
exists, its contents are overwritten by default. However, you can specify whether to append
data to an existing file using another constructor.
FileOutputStream outputStream = new FileOutputStream("output.txt");
outputStream.write(byteArray); // Write a byte array to the file
outputStream.close(); // Close the output stream when done

Both FileInputStream and FileOutputStream are low-level classes and provide basic functionality
for reading from and writing to files. They deal with bytes and do not perform any character
encoding or decoding. For reading or writing text data, you may want to use higher-level classes
like BufferedReader and BufferedWriter, which provide character-based I/O and handle character
encoding automatically. Additionally, it's important to properly handle exceptions and close the
streams after use to prevent resource leaks.
15. Explain about Scanner class and any three methods of Scanner.
Ans: The Scanner class in Java, found in the java.util package, is used to read input from various
sources such as the keyboard, files, or strings. It provides methods to parse primitive types and
strings from the input source.

Constructor:
Scanner can be instantiated with different sources of input, including InputStream, File, String, or
Readable.
Scanner scanner = new Scanner(System.in); // Read input from the keyboard

next():
Reads and returns the next token (sequence of characters separated by whitespace) from the input.
System.out.println("Enter your name:");
String name = scanner.next();
System.out.println("Hello, " + name);

nextInt():

Reads and returns the next integer value from the input.
System.out.println("Enter your age:");
int age = scanner.nextInt();
System.out.println("You are " + age + " years old.");

nextLine():

• Reads and returns the next line of input.


• Unlike next(), nextLine() reads the input including any leading and trailing whitespace
(spaces, tabs, etc.), and returns the entire line as a string.
System.out.println("Enter a sentence:");
String sentence = scanner.nextLine();
System.out.println("You entered: " + sentence);

hasNext():

Returns true if there is another token available in the input, otherwise returns false.
if (scanner.hasNext()) {
String token = scanner.next();
// Process the token
}

The Scanner class provides many more methods for parsing different types of input, skipping
tokens, setting delimiters, and more. It's a versatile tool for reading and parsing input in Java
applications. Remember to close the Scanner object after use, especially when reading from file or
other external resources, to release system resources properly.
16. Explain about StringTokenizer class and any three methods of String Tokenizer
Ans:
The StringTokenizer class in Java, found in the java.util package, is used to break a string into
tokens (smaller parts) based on a delimiter or set of delimiters. It provides methods to retrieve
these tokens one by one or all at once.

Constructor:

StringTokenizer can be instantiated with a string to be tokenized and optionally one or more
delimiter characters.
StringTokenizer tokenizer = new StringTokenizer("Hello, world! Welcome to Java.");

hasMoreTokens():

Returns true if there are more tokens available in the string, otherwise returns false.
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
// Process the token
}
nextToken():

Returns the next token from the string.


String firstToken = tokenizer.nextToken();
countTokens():

Returns the number of tokens remaining in the tokenizer.


int tokenCount = tokenizer.countTokens();

nextToken(String delim):

Returns the next token from the string, using the provided delimiter string instead of the default
delimiters.
StringTokenizer customTokenizer = new StringTokenizer("Hello|world|Java", "|");
String firstToken = customTokenizer.nextToken();

nextElement():
Returns the next token from the string as an object of type Object. This method is part of the
Enumeration interface and is retained for compatibility.
while (tokenizer.hasMoreElements()) {
Object token = tokenizer.nextElement();
// Process the token
}

You might also like