Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

java ans

The document provides an overview of key concepts in Java and Object-Oriented Programming, including inheritance, encapsulation, polymorphism, and exception handling. It explains the differences between classes and objects, the use of keywords like 'final' and 'static', and the functionality of constructors and methods. Additionally, it highlights the distinctions between Java applications and applets, as well as the importance of the Java Virtual Machine (JVM) in executing Java programs.

Uploaded by

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

java ans

The document provides an overview of key concepts in Java and Object-Oriented Programming, including inheritance, encapsulation, polymorphism, and exception handling. It explains the differences between classes and objects, the use of keywords like 'final' and 'static', and the functionality of constructors and methods. Additionally, it highlights the distinctions between Java applications and applets, as well as the importance of the Java Virtual Machine (JVM) in executing Java programs.

Uploaded by

binoydeyparasia
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

In Object-Oriented programming, new classes can be defined by extending existing example of inheritance.

A destructor is used to delete or destroy the objects when they are no longer in use.
Java does not support pointer due to security reason.
Yes, we can execute a java program without a main method by using a static block.
The Actual parameters are the variables that are transferred to the function when it is requested. The Formal
Parameters are the values determined by the function that accepts values when the function is declared. In
actual parameters, only the variable is mentioned, not the data types.
Objects are real world entities while classes are not real. ... Explanation - classes are basically the blueprint of
the objects. They doesnot have physical existence.
Bytecode in Java is a set of instructions for the Java Virtual Machine. Bytecode is a platform-independent code.
Overriding occurs when the method signature is the same in the superclass and the child class. Overloading
occurs when two or more methods in the same class have the same name but different parameters.
In Java, the final keyword is used to denote constants.
Synchronization in java is the capability to control the access of multiple threads to any shared resource.
Collections in Java is a framework that stores and manipulates a group of objects.
The super keyword can be used to invoke the parent class methods and constructors. The this keyword is used
to represent the current instance of a class.
Any Java members such as class or methods or data members when not specified with any access modifier
they are by default considered as default access modifiers.
How to create package in Java
1. First create a directory within name of package.
2. Create a java file in newly created directory.
3. In this java file you must specify the package name with the help of package keyword.
4. Save this file with same name of public class. ...
5. Now you can use this package in your program.
Inter-thread communication in Java is a mechanism in which a thread is paused running in its critical section
and another thread is allowed to enter (or lock) in the same critical section to be executed.
Criteria Unchecked exception Checked exception

NullPointerException, ClassCastException, ClassNotFoundException, SocketException,


List of
ArithmeticException, DateTimeException, SQLException, IOException,
examples
ArrayStoreException FileNotFoundExceptio
Error occur only when system resources are deficient whereas, an exception is caused if a code has some
problem.
Wrapper classes in Java provide a way to wrap or represent the value of primitive data types as an object. By
creating an object to the wrapper class, a data field is created and in this field we can store the value of a
primitive data type.
StringBuffer is a peer class of String that provides much of the functionality of strings. The string represents
fixed-length, immutable character sequences while StringBuffer represents growable and writable character
sequences.
A Java application can accept any number of arguments from the command line. This allows the user to
specify configuration information when the application is launched. When an application is launched, the
runtime system passes the command-line arguments to the application's main method via an array of String s.
Parameterized constructors in java are the programmer written constructors in a class which have one or more
than one arguments.
when implimenting inheritence we use protected access specifier in java.
Inheritance in Java is the method to create a hierarchy between classes by inheriting from other classes.
The CLASSPATH variable is an environment variable, meaning it's part of the operating system (e.g., Windows).
It contains the list of directories. These directories contain any class you created, plus the delivered Java class
file, called the Java Archive (JAR).
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from
another class). Abstract method: can only be used in an abstract class, and it does not have a body.
C++ supports features like operator overloading, Goto statements, structures, pointers, unions, etc. Java does
not support features like operator overloading, Goto statements, structures, pointers, unions, etc. C ++ is only
compiled and cannot be interpreted. Java can be both compiled and interpreted.
The Java Virtual Machine, or JVM, is an abstract computer that runs compiled Java programs.
Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces. Packages are
used for: Preventing naming conflicts.
Java is called Platform Independent because programs written in Java can be run on multiple platforms without
re-writing them individually for a particular platform,
A variable that is declared as a final variable is a constant throughout the program and its value cannot be
changed whatsoever. Method that is declared final cannot be overridden by any other subclasses. A class that
is declared final cannot be inherited by any other class.
OOps in java is to improve code readability and reusability by defining a Java program efficiently. The main
principles of object-oriented programming are abstraction, encapsulation, inheritance, and polymorphism.
An infinite loop in Java is a sequence of instructions that loops indefinitely unless the system crashes.
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the
program's instructions.
Polymorphism means "many forms", and it occurs when we have many classes that are related to each other
by inheritance.
Constructor overloading in Java refers to the use of more than one constructor in an instance class. However,
each overloaded constructor must have different signatures.
Java is strongly associated with the internet because of the first application program is written in Java was hot
Java. Web browsers to run applets on the internet. Internet users can use Java to create applet programs & run
then locally using a Java-enabled browser such as hot Java.
Type casting is a way of converting data from one data type to another data type. This process of data
conversion is also known as type conversion or type coercion. In Java, we can cast both reference and primitive
data types. By using casting, data can not be changed but only the data type is changed.
We can declare a class static by using the static keyword. A class can be declared static only if it is a nested
class. It does not require any reference of the outer class. The property of the static class is that it does not
allows us to access the non-static members of the outer class.
It is an Access modifier, which specifies from where and who can access the method. Making the main()
method public makes it globally available. It is made public so that JVM can invoke it from outside the class as it
is not present in the current class. As the main() method doesn't return anything, its return type is void.
Java tokens are the basic building blocks of a Java program. They are the smallest unit of a program, and they
include keywords, identifiers, operators, literals, separators, and comments. Separators are symbols that
separate different parts of a program.
Java command-line argument is an argument i.e. passed at the time of running the Java program. In Java, the
command line arguments passed from the console can be received in the Java program and they can be used
as input.
To implement single inheritance in Java, you use the “extends” keyword to create a subclass that inherits from
a single superclass. The subclass then gains access to all of the properties and methods of the superclass, which
it can either use directly or override.
public : it is a access specifier that means it will be accessed by publically. static : it is access modifier that
means when the java program is load then it will create the space in memory automatically. void : it is a return
type i.e it does not return any value. main() : it is a method or a function name.
In the String constant pool, a String object is likely to have one or many references. If several references point
to the same String without even knowing it, it would be bad if one of the references modified that String value.
That's why String objects are immutable.
How infinite loop is declared in java? Some of the common codes that will result in infinite loop are: use of
for(;;){//your code} in the code. use of while(true){//your code} in the code.
A constructor is similar to method and it is invoked at the time creating an object of the class, it is generally
used to initialize the instance variables of a class.
In object-oriented programming, the immutable string or objects that cannot be modified once it is created.
But we can only change the reference to the object. We restrict to change the object itself. The String is
immutable in Java because of the security, synchronization and concurrency, caching, and class loading.
In Java, Multithreading refers to a process of executing two or more threads simultaneously for maximum
utilization of the CPU. A thread in Java is a lightweight process requiring fewer resources to create and share
the process resources.
The garbage collector uses a mark-and-sweep algorithm to mark all unreachable objects as garbage collection,
then scans through live objects to find objects that are still reachable.
If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default
parameterless constructor A::A() . This constructor is an inline public member of its class.
Java finally block is always executed whether an exception is handled or not. Therefore, it contains all the
necessary statements that need to be printed regardless of the exception occurs or not. The finally block
follows the try-catch block.
The protected access modifier is accessible within package and outside the package but through inheritance
only. The protected access modifier can be applied on the data member, method and constructor. It can't be
applied on the class. It provides more accessibility than the default modifer.
Java applications are programs that run on a system without any web browser. Java Applets are the programs
that need a Java-supported web browser for their execution. Java applets are implemented in HTML.
The following features make Java a secure language: No use of explicit pointers. Java Program runs inside a
virtual sandbox (Java Virtual Machine or JVM). Classloader: The Java Runtime Environment (JRE) includes a
classloader that is used to dynamically load Java classes into the Java Virtual Machine.
An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in
an interface are declared with the empty body, and all the fields are public, static and final by default. A class
that implements an interface must implement all the methods declared in the interface.
The break statement is used to terminate the loop immediately. The continue statement is used to skip the
current iteration of the loop. break keyword is used to indicate break statements in java programming.
An abstract class is mostly used to provide a base for subclasses to extend and implement the abstract
methods and override or use the implemented methods in abstract class.
If you import a package, all the classes and interface of that package will be imported excluding the classes and
interfaces of the subpackages. Hence, you need to import the subpackage as well.
we can declare the main method as private in Java. It compiles successfully without any errors but at the
runtime, it says that the main method is not public.
The C++ preprocessor instruction "include iostream>" includes the iostream header file. This directive enables
you to access features like input and output stream objects (cin and cout) offered by the iostream library.
The super keyword refers to superclass (parent) objects. It is used to call superclass methods, and to access
the superclass constructor. The most common use of the super keyword is to eliminate the confusion between
superclasses and subclasses that have methods with the same name.
A static class is a class that is created inside a class, is called a static nested class in Java. It cannot access non-
static data members and methods. It can be accessed by outer class name.
Encapsulation in Java refers to integrating data (variables) and code (methods) into a single unit. In
encapsulation, a class's variables are hidden from other classes and can only be accessed by the methods of
the class in which they are found.
A base class is also called parent class or superclass. Derived Class: A class that is created from an existing
class. The derived class inherits all members and member functions of a base class. The derived class can have
more functionality with respect to the Base class and can easily access the Base class.
Object-oriented languages do not have the inbuilt objects whereas Object-based languages have the inbuilt
objects, for example, JavaScript has window object. Examples of object-oriented programming are Java, C#.
The most important use of inheritance in Java is code reusability. The code that is present in the parent class
can be directly used by the child class.
java doesn't support pointers directly. But it is used internally in java. Java do not use pointers because using
pointer the memory area can be directly accessed, which is a security issue.
Java application programs have full access to the local file system and network. Applets don't have local disk
and network access. Applications can access all kinds of resources available on the system. Applets can only
access browser-specific services.
1. In type casting, a data type is converted into another data type by a programmer using casting
operator. Whereas in type conversion, a data type is converted into another data type by a compiler.
delete() is an inbuilt method in Java which is used to remove or delete the characters in a substring of this
sequence.
The throw keyword is used inside a function. It is used when it is required to throw an Exception logically. The
throws keyword is used in the function signature. It is used when the function has some statements that can
lead to exceptions.
Java programming language uses both the compiler and an interpreter because the source programming code
is first transformed into binary programming code. And, this code is run by the JVM, which is usually a
software-based interpreter. By using compiled byte code, the interpreter can be small and useful.
Abstract classes are similar to normal classes, with the difference that they can include abstract methods,
which are methods without a body. Abstract classes cannot be instantiated.
The difference between Multiple and Multilevel inheritances is that Multiple Inheritance is when a class
inherits from many base classes while Multilevel is when a class inherits from a derived class,

S.No. Abstract Class Interface

1. An abstract class can contain both abstract and non-abstract Interface contains only abstract methods.
methods.

2. An abstract class can have all four; static, non-static and Only final and static variables are used.
final, non-final variables.

3. To declare abstract class abstract keywords are used. The interface can be declared with the
interface keyword.

4. It supports multiple inheritance. It does not support multiple inheritance.

5. The keyword ‘extend’ is used to extend an abstract class The keyword implement is used to implement
the interface.
Sr. Key final finally finalize
no.

1. Definition final is the keyword and access finally is the block in Java finalize is the method in Java
modifier which is used to apply Exception Handling to execute which is used to perform clean
restrictions on a class, method the important code whether the up processing just before object
or variable. exception occurs or not. is garbage collected.

2. Applicable Final keyword is used with the Finally block is always related to finalize() method is used with the
to classes, methods and the try and catch block in objects.
variables. exception handling.

3. Functionality (1) Once declared, final (1) finally block runs the finalize method performs the
variable becomes constant and important code even if cleaning activities with respect to
cannot be modified. exception occurs or not. the object before its destruction.
(2) final method cannot be (2) finally block cleans up all the
overridden by sub class. resources used in try block
(3) final class cannot be
inherited.

4. Execution Final method is executed only Finally block is executed as soon finalize method is executed just
when we call it. as the try-catch block is before the object is destroyed.
executed.
It's execution is not dependant
on the exception.

Constructors Methods

A Constructor is a block of code that initializes a A Method is a collection of statements which returns
newly created object. a value upon its execution.

A Constructor can be used to initialize an object. A Method consists of Java code to be executed.

A Constructor is invoked implicitly by the system. A Method is invoked by the programmer.

A Constructor is invoked when a object is created


A Method is invoked through method calls.
using the keyword new.

A Constructor doesn’t have a return type. A Method must have a return type.

A Constructor initializes a object that doesn’t A Method does operations on an already created
exist. object.

A Constructor’s name must be same as the name


A Method’s name can be anything.
of the class.

A Constructor cannot be inherited by subclasses. A Method can be inherited by subclasses.


Parameters Java Application Java Applet

Applications are just like a Java Applets are small Java programs that are
program that can be executed designed to be included with the HTML web
Definition
independently without using the web document. They require a Java-enabled web
browser. browser for execution.

The applet does not require the main() method


main () The application program requires a
for its execution instead init() method is
method main() method for its execution.
required.

Java application programs have full


Applets don’t have local disk and network
File access access to the local file system and
access.
network.

Applets can only access browser-specific


Applications can access all kinds of
Access level services. They don’t have access to the local
resources available on the system.
system.

First and foremost, the installation of


The Java applet does not need to be installed
Installation a Java application on the local
beforehand.
computer is required.

Applications can execute the Applets cannot execute programs from the
Execution
programs from the local system. local machine.

It cannot run on its own; it needs JRE It cannot start on its own, but it can be
Run
to execute. executed using a Java-enabled web browser.

Connection Connectivity with other servers is


It is unable to connect to other servers.
with servers possible.

A try block is the block of code (contains a set of statements) in which exceptions can occur; it's used to
enclose the code that might throw an exception. The try block is always followed by a catch block, which
handles the exception that occurs in the associated try block.
The catch block catches and handles the try block exceptions by declaring the type of exception within the
parameter. The catch block includes the code and it is executed if an exception inside the try block occurs. The
catch block is where you handle the exceptions; so this block must be follow the try block.
The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the
connection. The finally block executes whether exception rise or not and whether exception handled or not. A
finally contains all the crucial statements regardless of the exception occurs or not.
Input/Output (I/O) streams in Java are essential for handling the flow of data between a program and its
external environment, such as files, network connections, user input, and output devices like the console or a
printer. Java I/O streams facilitate data transfer and communication, making it possible for Java programs to
interact with the outside world.
Here are some key reasons why I/O streams are important in Java:
File Handling: Java I/O streams allow reading from and writing to files on the local file system. They provide
classes like FileInputStream, FileOutputStream, FileReader, and FileWriter to work with files in a platform-
independent manner.
Console Input/Output: I/O streams enable Java programs to interact with users through the console. The
System.in stream reads input from the user, and System.out and System.err streams display output and error
messages, respectively.
Network Communication: Java I/O streams are used for communication over networks. Java provides classes
like Socket, ServerSocket, InputStream, and OutputStream to create network connections and transfer data
between client and server applications.
The lifecycle of an applet in Java follows a predefined sequence of events from its initialization to its eventual
destruction. Here are the main stages of an applet's lifecycle:
Initiation (init): The init method is the first one to be called when an applet is created. It is used to initialize the
applet and perform any necessary setup. This method is typically used to set up the initial state, load resources,
and prepare the applet for display.
Starting (start): After the init method, the applet's start method is called. It is invoked whenever the user visits
the web page containing the applet or when the browser determines that the applet should start running. The
start method is responsible for starting or resuming any applet activities or animations.
Display (paint): The paint method is one of the most crucial methods in the applet's lifecycle. It is called after
the init and start methods and whenever the applet needs to be redrawn on the screen. The paint method is
responsible for rendering the visual representation of the applet on the screen.
User Interaction (mouse and keyboard events): While the applet is running, it can respond to user interactions
such as mouse clicks or keyboard inputs. When these events occur, the corresponding methods, such as
mouseClicked, mousePressed, keyPressed, etc., are called.
Stopping (stop): If the applet loses focus or the user navigates away from the web page containing the applet,
the stop method is called. This method allows the applet to stop any ongoing processes, animations, or other
activities that may be running.
De-initialization (destroy): When the applet is no longer needed, the destroy method is called. This happens
when the web page is closed, or the applet is explicitly removed from the page. The destroy method is used to
release any resources or clean up tasks associated with the applet.
Termination (end): The end method is the last method called in the applet's lifecycle. It is used to perform final
cleanup and is typically used to release any remaining resources that were not handled in the destroy method.
InputStream.read() and OutputStream.write():
int read(): This method is used to read a single byte of data from the input stream.
void write(int b): This method is used to write a single byte of data to the output stream.
InputStream.read(byte[] buffer) and OutputStream.write(byte[] buffer):
int read(byte[] buffer): This method reads up to buffer.length bytes of data from the input stream into the
provided buffer array.
void write(byte[] buffer): This method writes the entire content of the buffer array to the output stream.
InputStream.available():It is a useful method for checking how much data is available before reading from the
stream.
BufferedReader.readLine():his method is used to read a line of text from the input stream.
BufferedWriter.write(String str):This method writes a string to the output stream.
Characteristics of Java Constructors
An interface cannot have the constructor. Constructors cannot be private. A constructor cannot be
abstract, static, final, native, strictfp, or synchronized. A constructor can be overloaded. Constructors
cannot return a value. Constructors do not have a return type; not even void. Constructors have the
same name as the class they belong to. Constructors are called automatically when an object of the class
is created using the new keyword. Constructors can have access modifiers (e.g., public, private, protected, or
package-private) to control their visibility and accessibility from other classes. Constructors can call other
constructors using this() for constructor chaining.
In Java, strings are handled using the String class, which is immutable and provides methods for manipulation,
comparison, and formatting.
In Java, there are different parameter passing mechanisms when calling methods. The three main mechanisms
are: Pass-by-Value:
Java uses pass-by-value for all primitive data types (int, double, char, etc.) and also for object references.
When a method is called with a primitive data type, a copy of the value is passed to the method, so changes to
the parameter inside the method do not affect the original value.
Pass-by-Reference (Misconception):
In Java, some people mistakenly refer to it as pass-by-reference because when objects are passed as
parameters, the method can modify the object's state.
Pass-by-Value (for object reference):
Since the reference itself is passed by value, if you reassign the reference to a different object inside the
method, it won't affect the original reference outside the method.
For example, if you pass an object reference to a method and set it to null, it won't change the original object
reference outside the method.
Java Code (Applet Class):
Inside your applet class, you can access the parameters using the getParameter() method.
This method takes the name of the parameter as an argument and returns the corresponding value as a String.
public class MyApplet extends Applet {
public void init() {
String param1 = getParameter("parameter1");
String param2 = getParameter("parameter2");
// Use the parameters as needed in your applet
}
}
JRE (Java Runtime
Aspect JVM (Java Virtual Machine) Environment) JDK (Java Development Kit)
Comprehensive development
Purpose Executes Java bytecode Provides runtime environment package
Executes Java programs;
Translates bytecode into includes JVM along with Includes JRE and development tools
machine-specific instructions necessary libraries and for writing, compiling, and debugging
Functionality and executes Java programs components Java programs
End-users don't directly interact End-users use JRE to run Java Mainly used by Java developers for
End-User with JVM; it's transparent to applications without creating, compiling, and debugging
Usage them developing Java applications
Provides the runtime libraries, Contains JRE components, plus
Key Responsible for interpreting and JVM, and other components to development tools like Java compiler
Components executing Java bytecode run Java applications (javac) and debugger
Not directly used by developers; Developers may use JRE during Essential for Java developers as it
Developer developers target a specific JVM testing and deployment of includes all tools needed for creating
Usage implementation their Java applications Java applications
Multiple applications on End-users download and install Java developers download and use
Example different platforms share the JRE to run Java applications on JDK to write and compile Java code
Usage same JVM their systems on their development machines

You might also like