Java Programming
Java Programming
Java Programming
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.
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.
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.
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.
It can be used instead of int to clarify our code using its limits.
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.
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.
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.
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 ('').
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
3 Here the length of the string class is static. Here the length can be modified whenever
required, as it is dynamic in behaviour.
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.
1. try in Java
The try block contains a set of statements where an exception can occur.
try
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
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:
class ThrowExcep {
try {
catch (NullPointerException e) {
throw e;
try {
help();
catch (NullPointerException e) {
System.out.println(
Output
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.
class ThrowsExecp {
// to be handled
// by caller or caller
try {
fun();
catch (IllegalAccessException e) {
System.out.println("caught in main.");
Output
Inside fun().
caught in main.
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.
{
//...
synchronized(lockA)
//...
synchronized(lockB)
//...
//...
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.
Answer:
Checked Exception Unchecked Exception
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.
Exception
No Such Field Exception
Undeclared Throwable
Interrupted Exception 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.
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.
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.
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.
import java.awt.*;
import java.applet.*;
String msg="";
msg="Hello Geeks";
msg=msg+",Welcome to GeeksForGeeks";
g.drawString(msg,20,20);
}
}
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:
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
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.
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.