Java Unit 3B
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
}
}
( 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
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'
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");
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;
This example:
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:
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():
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():
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
}