Java Programming

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

1) Whats is Java? Explain about java history, features of java ?

A) Java is a programming language used for creating software that makes it compatible with many
different operating environments. It is a two-stage programming language, meaning that it is a
compiled language and an interpreted one. However, it differs from most other compiled
languages because it does not compile directly to an executable file.

In Java, the code is first compiled and then translated into a binary form called Java Byte Code.
Finally, the JBC gets compiled and interpreted into the native language needed to run in the
target operating environment. This contrasting behavior is a significant benefit for developers as
it means they can write code once and run it anywhere.

This feature became a popular concept, highly sought after by developers; it is known as the
“Write Once, Run Anywhere” (WORA) philosophy. The WORA philosophy was brought to
popularity as Sun Microsystems' slogan in 1995.

History of java:

The birth of Java happened in 1991 when James Gosling and his team began work on creating
the language at Sun Microsystems. Shortly after, the team switched their focus to developing
the language for the newest niche market known as the World Wide Web. By 1995, Java was
released to the public for use in various applications, from the internet to computer
programming.

Java stood alone as a programming language because it handles code translation differently
than other languages. Unlike other programming languages, it goes through two major steps
before running in its environment. Most programming languages only translate one time, either
by compiling the code or interpreting it. This difference made a significant impact on the rapid
growth and popularity of the language.

Java began as a project for connecting systems, such as connecting office devices on a network
and creating interactive television. However, the switch to using Java for the internet came on a
heel-turn and led to Java taking the lead as the number one programming language for the
interactive web or — web 2.0 as developers commonly refer to it in discussions.

JavaScript served the same purpose and, at first, was not very popular; however, as a marketing
ploy to build on the popularity of Java, the language took the name JavaScript. This marketing
ploy came after testing out several other names first, and the change to JavaScript helped push
its popularity and growth.

We have discussed Java’s history through the years and where it is today. Now let’s look at the
current role it plays in today's technology and some of the industries that use it, and what that
means for you.
Java is still very popular and has expanded its reach into several industries. Today Java is used
for programming complex technologies from mobile applications to AI programming and more.
For the rest of this section, we will dive into the various fields of technology that use Java as a
programming language.

Features Of Java:

 Simple
 Portable
 Object-Oriented
 Two-Stage Execution
 Secure
 Dynamic
 Distributed
 Multithreaded

Simple

Java tends to be easier to use than many languages it is similar to, as it takes a
simplistic approach to handle pointers and operator overloading.

Portable

Java is not platform-dependent; developers can write code once and run it anywhere
needed.

Object-Oriented

Everything in Java is considered to be an object. This means that everything has its
behavior and or state and adds structure to the language.

Two-Stage Execution

The Java language has two stages in its execution process. First, it is compiled and
then interpreted into a format usable by its target operating system.

Secure

The security of the Java code is strong thanks to the two-stage execution process.
Because the code runs through two steps, it is more secure and safer from attempts to
hack or modify the code in malicious ways.
Dynamic

Java is built to adapt to changes as necessary to help reduce memory waste and
increase performance speed. This makes for a very robust programming language with
the ability to check for errors or tampering on compilation. With the JIT (just-in-time)
compiler, the code gets translated into bytecode which is then interpreted by the target
machine.

Distributed

Java is a language built with distributed operation in mind. It can connect devices over
the internet and prompt them for specific program functions. This means that many
devices — such as computers — can run the same program and tap into each other for
resources and information.

Multithreaded

Java is a multithreaded language with its own set of synchronization primitive objects.
These objects make using the multiple threads in unison more manageable, resulting in
simpler use and better performance.

2) Write about JDK and JRE.

Answer)

JDK and JRE are the core concepts in Java programming and their differences are some of the
most popular interview questions. We don’t use these concepts while programming but if we
want to become a Java developer, we must know about these concepts.

JDK:

JDK stands for Java Development Kit. It is a software development environment used to develop Java
applications and applets. It is a platform-specific software i.e there are separate installers for Windows,
Mac, and Unix systems. Java developers can use it on their Windows, macOS, Solaris, and Linux to code
and run Java programs. It contains Java Runtime Environment(JRE) and other development tools like an
interpreter, compiler, archiver, and a document generator. We can possibly install more than one JDK
version on the same computer.

JRE:
JRE stands for Java Runtime Environment. It is the implementation of JVM (Java Virtual Machine) and it
is specially designed to provide an environment to execute Java programs. It is also platform dependent
like JDK. It consists of JVM, Java binaries, and other classes for the smooth execution of the program. It
doesn’t contain any development tools like a compiler, debugger, etc. If we only want to execute a
program, we just need to install JRE and not JDK, since there is no development or compilation of the
code required.

3) Explain about java primitive types.

Answer: Primitive data types in Java are predefined by the Java language and named as the reserved
keywords. A primitive data type does not share a state with other primitive values. Java programming
language supports the following eight primitive data types.

 Boolean data type


 byte data type
 int data type
 long data type
 float data type
 double data type
 char data type
 short data type

1) Boolean Data Type

A boolean data type can have two types of values, which are true and false. It is used to add a simple
flag that displays true/false conditions. It represents one bit of information. It's is not a specific size data
type. So, we can not precisely define its size.

2) Byte Data Type


It is an 8-bit signed 2's complement integer. It can have a value of (-128) to 127 ( inclusive). Below are
the benefits of using the byte data type:

It is useful for saving memory in large Arrays.

It can be used instead of int to clarify our code using its limits.

It saves memory, too, because it is 4 times smaller than an integer.

3) Int Data Type

The int stands for Integer; it is a 32-bit signed two's complement integer. It's value can be from -2^31 to
(2^31-1), which is -32,768 to 32,767 (inclusive). Its default value is zero. It represents an unsigned 32-bit
integer, which has a value range from 0 to 32,767.

4) Long Data Type

It is a 64-bit 2's complement integer with a value range of (-2^63) to (2^63 -1) inclusive. It is used for the
higher values that can not be handled by the int data type.

5) Float Data Type

The Float data type is used to declare the floating values ( fractional numbers). It is a single-precision 32-
bit IEEE 754 floating-point data type.

It is useful for saving memory in large arrays of floating-point numbers. It is recommended to use float
data type instead of double while saving the floating numbers in large arrays, and not use it with precise
numbers such as currency.

6) Double Data Type

The double data type is also used for the floating-point ( Fractional values) number. It is much similar to
the float data type. But, generally, it is used for decimal values. Like the float data type, its value range is
infinite and also can not be used for precise values such as currency.

The default value of the double data type is 0.0d. While declaring the double type values, we must end
the value with a d.
7) Char Data Type

The char data type is also an essential primitive data type in Java. It is used to declare the character
values. It is a single 16-bit Unicode Character with a value range of 0 to 65,535 (inclusive).

While declaring a character variable, its value must be surrounded by a single quote ('').

8) Short Data Type

The short data type is also used to store the integer values. It is a 16-bit signed 2's complement integer
with a value range of -32,768 to 32,767 (inclusive). It is also used to save memory, just like the byte data
type.

It is recommended to use the short data type in a large array when memory saving is essential.

4) what are the difference between String and String Buffer classes ?

Answer)
S. No. String StringBuffer

1 String is immutable. It is mutable.

2 It is slow in terms of executing the It is fast in terms of executing the concatenation


concatenation task. task.

3 Here the length of the string class is static. Here the length can be modified whenever
required, as it is dynamic in behaviour.

4 It is less efficient. It is more efficient in nature as compared to the


string class.

5 String consumes more as compared to the StringBuffer uses less memory as compared to the
stringbuffer. string.

5 It utilises a string constant pool to store the It prefers heap memory to store the objects.
values.

6 It overrides both equal() and hashcode() It cannot override equal() and hashcode() methods.
techniques of object class.

5)Write about try, catch, throw, throws clauses.


Answer:

1. try in Java

The try block contains a set of statements where an exception can occur.

try

// statement(s) that might cause exception

2. catch in Java

The catch block is used to handle the uncertain condition of a try block. A try block is always followed by
a catch block, which handles the exception that occurs in the associated try block.

catch

// statement(s) that handle an exception

// examples, closing a connection, closing

// file, exiting the process after writing

// details to a log file.

3. throw in Java

The throw keyword is used to transfer control from the try block to the catch block.
Below is the implementation of the above approach:

// Java program that demonstrates the use of throw

class ThrowExcep {

static void help()

try {

throw new NullPointerException("error_unknown");

catch (NullPointerException e) {

System.out.println("Caught inside help().");

// rethrowing the exception

throw e;

public static void main(String args[])

try {

help();

catch (NullPointerException e) {

System.out.println(

"Caught in main error name given below:");


System.out.println(e);

Output

Caught inside help().

Caught in main error name given below:

java.lang.NullPointerException: error_unknown

4. throws in Java

The throws keyword is used for exception handling without try & catch block. It specifies the exceptions
that a method can throw to the caller and does not handle itself.

Below is the implementation of the above approach:

// Java program to demonstrate working of throws

class ThrowsExecp {

// This method throws an exception

// to be handled

// by caller or caller

// of caller and so on.


static void fun() throws IllegalAccessException

System.out.println("Inside fun(). ");

throw new IllegalAccessException("demo");

// This is a caller function

public static void main(String args[])

try {

fun();

catch (IllegalAccessException e) {

System.out.println("caught in main.");

Output

Inside fun().

caught in main.

6) What is deadlock ? how to avoid deadlock ?


Answer: In the thread, each object has a lock. To acquire a lock, Java provides synchronization to lock a
method or code block. It allows that at a time only one thread can access that method.

Nevertheless, if a thread wants to execute a synchronized method it first tries to acquire a lock. It is
possible that another thread has already acquired that lock then the thread (that wants to acquire the
lock) will have to wait until the previous thread does not release the lock.

Example

Suppose, there are two threads A and B. The thread A and B acquired the lock of Object-A and Object-B,
respectively. Assume that thread A executing method A and wants to acquire the lock on Object-B, while
thread B is already acquired a lock on Object-B.

On the other hand, thread B also tries to acquire a lock on Object-A, while thread A is acquired a lock on
Object-A. In such a situation both threads will not complete their execution and wait for releasing the
lock. The situation is known as, deadlock.

public void methodA()

{
//...

synchronized(lockA)

//...

synchronized(lockB)

//...

public void methodB()

//...

synchronized(lockB)

//...

synchronized(lockA)

//...

Although it is not possible to avoid deadlock condition but we can avoid it by using the following ways:
Avoid Unnecessary Locks: We should use locks only for those members on which it is required.
Unnecessary use of locks leads to a deadlock situation. We recommend you to use a lock-free data
structure. If possible, keep your code free form locks. For example, instead of using synchronized
ArrayList use the ConcurrentLinkedQueue.

Avoid Nested Locks: Another way to avoid deadlock is to avoid giving a lock to multiple threads if we
have already provided a lock to one thread. Since we must avoid allocating a lock to multiple threads.

Using Thread.join() Method: You can get a deadlock if two threads are waiting for each other to finish
indefinitely using thread join. If your thread has to wait for another thread to finish, it's always best to
use join with the maximum time you want to wait for the thread to finish.

Use Lock Ordering: Always assign a numeric value to each lock. Before acquiring the lock with a higher
numeric value, acquire the locks with a lower numeric value.

Lock Time-out: We can also specify the time for a thread to acquire a lock. If a thread does not acquire a
lock, the thread must wait for a specific time before retrying to acquire a lock.

7) Difference between checked and unchecked exceptions.

Answer:
Checked Exception Unchecked Exception

Checked exceptions occur at compile time. Unchecked exceptions occur at runtime.

The compiler checks a checked exception. The compiler does not check these types
of exceptions.

These types of exceptions can be handled at the time of These types of exceptions cannot be a
compilation. catch or handle at the time of
compilation, because they get generated
by the mistakes in the program.

They are the sub-class of the exception class. They are runtime exceptions and hence
are not a part of the Exception class.

Here, the JVM needs the exception to catch and handle. Here, the JVM does not require the
exception to catch and handle.

Examples of Checked exceptions: Examples of Unchecked Exceptions:

 File Not Found Exception  No Such Element


Exception
No Such Field Exception
 Undeclared Throwable
 Interrupted Exception Exception

 No Such Method Exception  Empty Stack Exception

 Class Not Found Exception  Arithmetic Exception

 Null Pointer Exception

 Array Index Out of


Bounds Exception

 Security Exception
8) Explain about Thread and its Life cycle.

Answer)

A Thread is a very light-weighted process, or we can say the smallest part of the process that allows a
program to operate more efficiently by running multiple tasks simultaneously.

In order to perform complicated tasks in the background, we used the Thread concept in Java. All the
tasks are executed without affecting the main program. In a program or process, all the threads have
their own separate path for execution, so each thread of a process is independent.

Another benefit of using thread is that if a thread gets an exception or an error at the time of its
execution, it doesn't affect the execution of the other threads. All the threads share a common memory
and have their own stack, local variables and program counter. When multiple threads are executed in
parallel at the same time, this process is known as Multithreading.

Life Cycle of a Thread

There are multiple states of the thread in a lifecycle as mentioned below:

New Thread: When a new thread is created, it is in the new state. The thread has not yet started to run
when the thread is in this state. When a thread lies in the new state, its code is yet to be run and hasn’t
started to execute.

Runnable State: A thread that is ready to run is moved to a runnable state. In this state, a thread might
actually be running or it might be ready to run at any instant of time. It is the responsibility of the thread
scheduler to give the thread, time to run.

A multi-threaded program allocates a fixed amount of time to each individual thread. Each and every
thread runs for a short while and then pauses and relinquishes the CPU to another thread so that other
threads can get a chance to run. When this happens, all such threads that are ready to run, waiting for
the CPU and the currently running thread lie in a runnable state.
Blocked: The thread will be in blocked state when it is trying to acquire a lock but currently the lock is
acquired by the other thread. The thread will move from the blocked state to runnable state when it
acquires the lock.

Waiting state: The thread will be in waiting state when it calls wait() method or join() method. It will
move to the runnable state when other thread will notify or that thread will be terminated.

Timed Waiting: A thread lies in a timed waiting state when it calls a method with a time-out parameter.
A thread lies in this state until the timeout is completed or until a notification is received. For example,
when a thread calls sleep or a conditional wait, it is moved to a timed waiting state.

Terminated State: A thread terminates because of either of the following reasons:

Because it exits normally. This happens when the code of the thread has been entirely executed by the
program.

Because there occurred some unusual erroneous event, like a segmentation fault or an unhandled
exception.

9) Explain about Applets, Running Applets.

Answer:

An applet is a Java program that can be embedded into a web page. It runs inside the web browser and
works at client side. An applet is embedded in an HTML page using the APPLET or OBJECT tag and hosted
on a web server.

Applets are used to make the website more dynamic and entertaining.

Applets are tiny Java programs that can be installed and run automatically as part of a web page. They
can be viewed on an Internet server, transmitted over the Internet, and installed and run automatically
as part of a web document or desktop application.

1.By using Web Browser

2.By using Applet Viewer

Let’s understand each technique one by one


1. Executing the applet within a Java-compatible Web browser:

Suppose we have a GfgApplet.java file in which we have our java code.

// Java program to run the applet

// using the web browser

import java.awt.*;

import java.applet.*;

public class GfgApplet extends Applet

String msg="";

public void init()

msg="Hello Geeks";

public void start()

msg=msg+",Welcome to GeeksForGeeks";

public void paint(Graphics g)

g.drawString(msg,20,20);

}
}

Compiling: javac GfgApplet.java

10) Write about error Vs Excepion.

Answer:

In Java, errors and exceptions are both types of throwable objects, but they represent different types of
problems that can occur during the execution of a program.

Errors are usually caused by serious problems that are outside the control of the program, such as
running out of memory or a system crash. Errors are represented by the Error class and its subclasses.
Some common examples of errors in Java include:

 OutOfMemoryError: Thrown when the Java Virtual Machine (JVM) runs out of memory.
 StackOverflowError: Thrown when the call stack overflows due to too many method
invocations.
 NoClassDefFoundError: Thrown when a required class cannot be found.

Since errors are generally caused by problems that cannot be recovered from, it’s usually not
appropriate for a program to catch errors. Instead, the best course of action is usually to log the error
and exit the program.

Exceptions, on the other hand, are used to handle errors that can be recovered from within the
program. Exceptions are represented by the Exception class and its subclasses. Some common examples
of exceptions in Java include:

 NullPointerException: Thrown when a null reference is accessed.


 IllegalArgumentException: Thrown when an illegal argument is passed to a method.
 IOException: Thrown when an I/O operation fails.
Since exceptions can be caught and handled within a program, it’s common to include code to catch and
handle exceptions in Java programs. By handling exceptions, you can provide more informative error
messages to users and prevent the program from crashing.

In summary, errors and exceptions represent different types of problems that can occur during program
execution. Errors are usually caused by serious problems that cannot be recovered from, while
exceptions are used to handle recoverable errors within a program.

In java, both Errors and Exceptions are the subclasses of java.lang.Throwable class. Error refers to an
illegal operation performed by the user which results in the abnormal working of the program.
Programming errors often remain undetected until the program is compiled or executed. Some of the
errors inhibit the program from getting compiled or executed. Thus errors should be removed before
compiling and executing. It is of three types:

 Compile-time
 Run-time
 Logical

Basis of Comparison Exception Error

Recoverable/ Exception can be recovered by using the try-catch block. An error cannot be recovered.
Irrecoverable

Type It can be classified into two categories i.e. checked and unchecked. All errors in Java are unchecked.

Occurrence It occurs at compile time or run time. It occurs at run time.

Package It belongs to java.lang.Exception package. It belongs to java.lang.Error package.

Known or unknown Only checked exceptions are known to the compiler. Errors will not be known to the compiler.

Causes It is mainly caused by the application itself. It is mostly caused by the environment in which the application is
running.

Example Checked Exceptions: SQLException, IOException Java.lang.StackOverFlow, java.lang.OutOfMemoryErro


Unchecked Exceptions: ArrayIndexOutOfBoundException, NullPointerException,
ArithmaticException

You might also like