Java Mid-1 Imp Queans
Java Mid-1 Imp Queans
Java Mid-1 Imp Queans
UNIT-1
1. Explain why Java Language is known as platform independent.
Ans) To explain why Java is platform independent, We should discuss the working
of the Java programming language, that can be summed up in three steps.
Let’s go through the steps given below:
1. Here for the first step, we need to have a java source code otherwise we won't
be able to run the program. you need to save it with the program.java extension.
2. Secondly, we need to use a compiler so that it compiles the source code which
in turn gives out the java bytecode and that needs to have a program.class
extension. The Java bytecode is a redesigned version of the java source codes,
and this bytecode can be run anywhere irrespective of the machine on which it
has been built.
3. Later on, we put the java bytecode through the Java Virtual Machine which is an
interpreter that reads all the statements thoroughly step by step from the java
bytecode which will further convert it to the machine-level language so that the
machine can execute the code. We get the output only after the conversion is
through.
Execution Process of Java Program:
2. Compilation: Once you have written your Java code, the next step is to
compile it. Compilation is the process of converting human-readable Java
code into bytecode, which is a low-level representation of the code that can
be executed only by the Java Virtual Machine (JVM).
If there are no errors in the code, this will generate a bytecode with a ‘.class’
extension (e.g., HelloWorld.class).
3. Execution:
Java Virtual Machine (JVM): The computer’s hardware does not execute the
generated bytecode directly. Instead, it runs on the Java Virtual Machine
(JVM). Java is platform-independent, allowing Java programs to run on any
machine with a compatible JVM.
2. List and Explain Java Buzzwords in detail.
Ans) Java Features (Java Buzzwords):
1. Simple: Java is designed to be easy to understand and use. Its syntax is clean
and straightforward, and it removes complex features like pointers (found in
other languages like C/C++), making it beginner-friendly.
2. Object-Oriented: Java follows the Object-Oriented Programming (OOP)
paradigm. It organizes code into classes and objects, which makes programs
easier to manage and scale. Everything in Java revolves around objects and
their interactions.
3. Portable: Java code can run on any machine, as long as it has the Java Virtual
Machine (JVM) installed. You can write Java programs on one system and run
them on another without needing to modify the code.
4. Platform Independent: Java programs are compiled into bytecode (not
machine-specific code). This bytecode can be executed on any platform that
has a JVM, making Java truly "write once, run anywhere."
5. Secured: Java provides a secure environment by limiting access to certain
resources and preventing common security issues (like memory corruption
through pointers). It has built-in security features like cryptography and
security policies.
6. Robust: Java is designed to be reliable and avoid common programming
errors. Features like automatic memory management (garbage collection),
exception handling, and strong type-checking make Java robust, meaning
programs are less likely to crash.
7. Architecture Neutral: Java bytecode is designed to be compatible with
different computer architectures. This means you don’t have to worry about
the underlying hardware when you write Java code.
8. Interpreted: Java programs are first compiled into bytecode, which is then
interpreted by the JVM. This makes it easier to execute the program on
different systems, as the JVM takes care of converting the bytecode into
machine-specific instructions.
9. High Performance: Although interpreted, Java achieves good performance
through the Just-In-Time (JIT) compiler, which converts bytecode into native
machine code during runtime, speeding up execution.
10.Multithreaded: Java supports multithreading, meaning it can execute
multiple tasks at the same time (in parallel). This is useful for tasks like
playing music while downloading a file.
11.Distributed: Java supports distributed computing, allowing programs to run
across multiple computers (nodes) on a network. Java has libraries like RMI
(Remote Method Invocation) and networking capabilities to make this
easier.
12.Dynamic: Java is dynamic because it can load classes at runtime. This allows
the code to adapt to evolving environments or handle new data types as
needed, making it flexible for developers.
3. Explain various data types in Java along with their size and
range.
Ans) Data Types
• A data type is a classification of data which tells the complier how the
programmer wants to use the data.
• Data types specify the different sizes and values that can be stored in the
variable.
Example:
public class PrimitiveDataTypesDemo {
Output:
Example:
public class Rectangle {
double length;
double breadth;
void calculateArea() {
double area = length * breadth;
System.out.println("area of the rectangle =" + area);
}
}
public class ClassDemo {
}
}
Output:
area of the rectangle =200.0
Interface:
• An interface is declared like a class (similar to class).
• The key difference is that the interface contains abstract methods by default.
They have no body.
Example:
interface printable {
void printMsg();
}
Output:
HELLO
String:
• String data type stores a sequence or array of characters.
• String value is enclosed in double quotes.
Example:
public class StringDemo {
public static void main(String[] args) {
String s = "Java Programming";
System.out.println(s);
}
}
Output:
Java Programming
Enum:
• Enum is similar to class.
• Unlike class, enum constants are public, static and final (unchangeable-
cannot be overridden).
• Enum cannot extend other classes. But enum can implement interfaces.
• According to the Java naming conventions, we should have all constants in
capital letters. So, we have enum constants in capital letters.
Example:
class EnumExample {
//defining the enum inside the class
public enum Season {
WINTER, SPRING, SUMMER, FALL
}
//main method
public static void main(String[] args) {
//traversing the enum
for (Season s : Season.values())
System.out.println(s);
}
}
Output:
WINTER
SPRING
SUMMER
FALL
2. if-else Statement:
The if-else statement allows you to execute one block of code if the condition is
true, and another block if the condition is false.
Syntax:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Example for if-else:
int number = 3;
if (number > 5) {
System.out.println("Number is greater than 5.");
} else {
System.out.println("Number is less than or equal to 5.");
}
Example:
int number = 15;
if (number < 0) {
System.out.println("Number is negative.");
} else if (number == 0) {
System.out.println("Number is zero.");
} else if (number > 0 && number <= 10) {
System.out.println("Number is between 1 and 10.");
} else {
System.out.println("Number is greater than 10.");
}
Switch:
• switch statement is used to execute one block of code out of many based on
the value of an expression.
• It is more readable and efficient than an if-else-if ladder when working with
multiple possible conditions of a single variable.
Syntax:
switch (expression) {
case value1:
// code block for value1
break; // optional
case value2:
// code block for value2
break; // optional
// you can have as many cases as needed
default:
// code block if none of the cases match
}
Example:
public class SwitchDemo {
public static void main(String args[]) {
int day = 3;
switch (day) {
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
case 4:
System.out.println("Wednesday");
break;
case 5:
System.out.println("Thursday");
break;
case 6:
System.out.println("Friday");
break;
case 7:
System.out.println("Saturday");
break;
default:
System.out.println("Invalid day");
}
}
}
Output:
Tuesday
Loop or Iterative Statements:
• For
• For-each
• While
• Do-while
1. for Loop:
The for loop is used when you know in advance how many times you want to
execute a statement or block of statements.
It consists of three parts: initialization, condition, and increment/decrement.
Syntax:
for (initialization; condition; increment/decrement) {
// code to be executed
}
Example:
for (int i = 0; i < 5; i++) {
System.out.println("i = " + i);
}
2. for-each Loop (Enhanced for Loop):
• The for-each loop is used to iterate over arrays or collections such as
ArrayList.
• It is simpler and more readable when you don't need to work with the
index of elements.
Syntax:
for (dataType variable : array/collection) {
// code to be executed
}
Example:
int[] numbers = {10, 20, 30, 40};
for (int num : numbers) {
System.out.println("Number: " + num);
}
3. while Loop:
The while loop is used when you want to execute a block of code repeatedly as
long as a given condition is true. The condition is checked before the loop's body
is executed.
Syntax:
while (condition) {
// code to be executed
}
Example:
int i = 0;
while (i < 5) {
System.out.println("i = " + i);
i++;
}
4. do-while Loop:
The do-while loop is similar to the while loop, but it guarantees that the loop's body
is executed at least once because the condition is checked after the loop's body.
Syntax:
do {
// code to be executed
} while (condition);
Example:
int i = 0;
do {
System.out.println("i = " + i);
i++;
} while (i < 5);
Example
Output:
5
9
6.0
Run-time Polymorphism (Method Overriding)
Method overriding allows a subclass to provide a specific implementation of a
method that is already defined in its superclass. It occurs when a subclass has a
method with the same signature as a method in the superclass.
Example:
Output:
This is a generic animal sound.
The dog barks.
The cat meows.
7. Explain type casting with examples.
Ans) Typecasting in Java is the process of converting a variable from one data type
to another. There are two types of typecasting:
Example:
// Explicit Typecasting
double pi = 3.14;
int intPi = (int) pi; // double to int
System.out.println("Explicit Typecasting: " + intPi); // Outputs: 3
}
}
• In the above implicit typecasting, an int is automatically converted to a double,
which is safe because a double can hold larger values.
• In the above explicit typecasting, a double is explicitly cast to an int, which
might lead to data loss (the decimal part is discarded).
8.Explain the use of setter and getter method.
Ans) In Java, setter and getter methods are used to control access to the private
fields of a class. These methods allow you to access and modify private variables
in a controlled manner, adhering to the principles of encapsulation.
• Getter Methods: These methods are used to retrieve or access the value of a
private field.
• Setter Methods: These methods are used to modify or update the value of a
private field.
1. Control the values assigned to fields (e.g., by adding validation in the setter).
2. Hide the internal representation of the class's data.
Example:
Ans) In Java, this and this() serve different purposes, and they are used in distinct
contexts:
1. this keyword
Example:
public class Person {
private String name;
Example:
public class Person {
private String name;
private int age;
• Key Purpose: Focus on "what" an object does rather than "how" it does it.
• Achieved By:
o Abstract Classes: Classes that cannot be instantiated and may have
abstract methods (methods without implementation).
o Interfaces: Define methods that must be implemented by any class
that implements the interface.
Example:
// Abstract class
abstract class Animal {
// Abstract method (no implementation)
public abstract void sound();
• Key Purpose: Control access to the internal state of the object to protect its
integrity and hide its implementation details from the outside world.
• Achieved By:
o Declaring fields as private and providing public getter and setter
methods to access or modify the fields.
Example:
public class Person {
// Private fields
private String name;
private int age;
Ans) 1. Error:
Definition:
Errors represent serious problems that are generally not meant to be caught or
handled by a program. These are problems that occur in the runtime environment
itself, and typically, the application cannot recover from them.
Examples of Errors:
`OutOfMemoryError`: Occurs when the JVM runs out of memory.
`StackOverflowError`: Happens when the stack for a thread overflows, typically
due to infinite recursion.
`VirtualMachineError`: Indicates that the Java Virtual Machine (JVM) has
encountered a problem.
Errors are usually not handled using `try-catch` blocks because they indicate
problems that are outside the control of the application (e.g., hardware or system-
level failures).
Example:
//Example of an Error (typically not handled)
public class ErrorDemo {
public static void main(String[] args) {
// This will eventually throw StackOverflowError due to
infinite recursion
main(args);
}
}
2. Exception:
Definition:
Exceptions are conditions that occur due to program errors or other unexpected
conditions that can be caught and handled within the program. Exceptions indicate
conditions that a program should be able to handle (for example, invalid input, file
not found, etc.).
Types of Exceptions:
1. Checked Exceptions (Compile time exceptions): These are exceptions that are
checked at compile-time. The programmer must handle them either by using a
`try-catch` block or by declaring them in the method signature using the
`throws` keyword.
Examples of Checked Exceptions:
`IOException`: Thrown when an input or output operation fails, such as when
trying to read from a file that doesn't exist.
`SQLException`: Thrown when a database access error occurs.
`FileNotFoundException`: Thrown when a file is not found.
`ClassNotFoundException`: Thrown when trying to load a class through
reflection, and the class cannot be located.
// Example of an Exception
public class UncheckedExceptionExample {
public static void main(String[] args) {
int[] arr = new int[5];
System.out.println(arr[10]);
// This will throw ArrayIndexOutOfBoundsException
}
}
Comparing Exception and Error:
Aspect Exception Error
Definition Represents the conditions a Represents serious system-
program should handle. level issues.
Recoverability Can often be caught and Typically, not recoverable
handled. by the program
Examples `IOException`, `OutOfMemoryError`,
`NullPointerException`, `StackOverflowError`
`ArithmeticException
Checked/Unchecked Includes both checked and Only unchecked (not meant
unchecked exceptions to be handled).
Output:
Array index is out of bounds!
Output:
Exception in thread "main" java.lang.IllegalArgumentException: Age must be 18 or
older.
5. `throws` Keyword:
The `throws` keyword is used in a method signature to declare that a method can
throw one or more exceptions. It is used for checked exceptions that the method
may not handle itself but leaves to be handled by the calling code.
Example:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
We can use the FileWriter or BufferedWriter class along with the File
class to write content to a file.
Here's an example of a program that writes some text to a file using the
FileWriter class:
Example:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
UNIT-3
16.Define a Package? What is its use in java?
Package
A package in Java is used to group related classes and interfaces, providing
modularity and reusability. Packages also help avoid name conflicts by categorizing
classes into namespaces.
Example:
//Define a package
package examples;
Output:
hey David ! Your height is 5.4 and age is 30
Scanner class:
Scanner allows you to take the input from the user when we run the java
program. Scanner allows us to handle different types of data as input in Java.
Example:
import java.util.Scanner;
}
}
18. Define CLASSPATH. What is its purpose?
CLASSPATH
CLASSPATH is an environment variable that tells the Java Virtual Machine (JVM)
where to look for user defined classes and packages. It's the path where Java
should search for compiled bytecode (i.e., .class files).
You can set it using: Command line:
`set CLASSPATH=path_to_directory`
Programmatically within Java:
System.out.println(System.getProperty("java.class.path"));
In Java, the `Random` class is part of the `java.util` package and is used to generate
random numbers of different types (int, long, double, etc.). Here’s a breakdown of the
constructors and common methods you mentioned, along with simple examples.
Example
import java.util.Random;
public class RandomExample1 {
public static void main(String[] args) {
Random random = new Random(); // Uses current time as seed
int randomInt = random.nextInt();
System.out.println("Random integer: " + randomInt);
}
}
Output: