0% found this document useful (0 votes)
6 views

Java Answer Key Big Qn

The document outlines key Object-Oriented Programming (OOP) concepts in Java, including abstraction, encapsulation, inheritance, and polymorphism, along with Java's conditional statements and array structures. It also discusses wrapper classes, thread priority in multithreading, and the importance of thread synchronization. Additionally, it introduces the Class class in Java and highlights the significance of the Java Development Kit (JDK) and Java Runtime Environment (JRE) for Java application development.

Uploaded by

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

Java Answer Key Big Qn

The document outlines key Object-Oriented Programming (OOP) concepts in Java, including abstraction, encapsulation, inheritance, and polymorphism, along with Java's conditional statements and array structures. It also discusses wrapper classes, thread priority in multithreading, and the importance of thread synchronization. Additionally, it introduces the Class class in Java and highlights the significance of the Java Development Kit (JDK) and Java Runtime Environment (JRE) for Java application development.

Uploaded by

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

OOPS concepts are as follows:

Class
Object
Method and method passing
Pillars of OOPs
Abstraction
Encapsulation
Inheritance
Polymorphism
Compile-time polymorphism
Runtime polymorphis
● Abstraction. Using simple things to represent complexity. We all know how to
turn the TV on, but we don’t need to know how it works in order to enjoy it. In
Java, abstraction means simple things like objects, classes and variables
represent more complex underlying code and data. This is important because it
lets you avoid repeating the same work multiple times.
● Encapsulation. The practice of keeping fields within a class private, then
providing access to those fields via public methods. Encapsulation is a protective
barrier that keeps the data and code safe within the class itself. We can then
reuse objects like code components or variables without allowing open access to
the data system-wide.
● Inheritance. A special feature of Object-Oriented Programming in Java,
Inheritance lets programmers create new classes that share some of the
attributes of existing classes. Using Inheritance lets us build on previous work
without reinventing the wheel.
● Polymorphism. Allows programmers to use the same word in Java to mean
different things in different contexts. One form of polymorphism is method
overloading. That’s when the code itself implies different meanings. The other
form is method overriding. That’s when the values of the supplied variables
imply different meanings. Let’s delve a little further.

Java Conditions and If Statements


You already know that Java supports the usual logical conditions from mathematics:

Less than: a < b


Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
You can use these conditions to perform different actions for different decisions.
Java has the following conditional statements:

Use if to specify a block of code to be executed, if a specified condition is true


Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed

if (condition) {
// block of code to be executed if the condition is true
}

if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}

int time = 22;


if (time < 10) {
System.out.println("Good morning.");
} else if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening.

Normally, an array is a collection of similar type of elements which has contiguous


memory location.

Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java
array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C++,
we need to use the sizeof operator.
In Java, array is an object of a dynamically generated class. Java array inherits the
Object class, and implements the Serializable as well as Cloneable interfaces. We can
store primitive values or objects in an array in Java. Like C/C++, we can also create
single dimentional or multidimentional arrays in Java.

Moreover, Java provides the feature of anonymous arrays which is not available in C/C+
+.There are two types of array.

Single Dimensional Array


Multidimensional Array

dataType[] arr; (or)


dataType []arr; (or)
dataType arr[];
Instantiation of an Array in Java

arrayRefVar=new datatype[size];

class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

Wrapper Classes in Java


A Wrapper class in Java is a class whose object wraps or contains primitive data types.
When we create an object to a wrapper class, it contains a field and in this field, we can
store primitive data types. In other words, we can wrap a primitive value into a wrapper
class object. Let’s check on the wrapper classes in Java with examples:

Need of Wrapper Classes


There are certain needs for using the Wrapper class in Java as mentioned below:

They convert primitive data types into objects. Objects are needed if we wish to modify
the arguments passed into a method (because primitive types are passed by value).
The classes in java.util package handles only objects and hence wrapper classes help
in this case also.
Data structures in the Collection framework, such as ArrayList and Vector, store only
objects (reference types) and not primitive types.
An object is needed to support synchronization in multithreading.
Advantages of Wrapper Classes
Collections allowed only object data.
On object data we can call multiple methods compareTo(), equals(), toString()
Cloning process only objects
Object data allowed null values.
Serialization can allow only object data.

Java Thread Priority in Multithreading


As we already know java being completely object-oriented works within a multithreading
environment in which thread scheduler assigns the processor to a thread based on the
priority of thread. Whenever we create a thread in Java, it always has some priority
assigned to it. Priority can either be given by JVM while creating the thread or it can be
given by the programmer explicitly.

Priorities in threads is a concept where each thread is having a priority which in


layman’s language one can say every object is having priority here which is represented
by numbers ranging from 1 to 10.

The default priority is set to 5 as excepted.


Minimum priority is set to 1.
Maximum priority is set to 10.
Here 3 constants are defined in it namely as follows:

public static int NORM_PRIORITY


public static int MIN_PRIORITY
public static int MAX_PRIORITY
Let us discuss it with an example to get how internally the work is getting executed.
Here we will be using the knowledge gathered above as follows:

We will use currentThread() method to get the name of the current thread. User can
also use setName() method if he/she wants to make names of thread as per choice for
understanding purposes.
getName() method will be used to get the name of the thread.
The accepted value of priority for a thread is in the range of 1 to 10.

Let us do discuss how to get and set priority of a thread in java.

public final int getPriority(): java.lang.Thread.getPriority() method returns priority of


given thread.
public final void setPriority(int newPriority): java.lang.Thread.setPriority() method
changes the priority of thread to the value newPriority. This method throws
IllegalArgumentException if value of parameter newPriority goes beyond minimum(1)
and maximum(10) limit

Menu
Search tutorials, courses and ebooks...
HTML
CSS
Javascript
SQL
Python
Java
C
C++
PHP
Scala
C#
Node.Js
MySQL
MongoDB
PL/SQL
Swift
Bootstrap
R
Machine Learning
Blockchain
Angular
React Native
Computer Fundamentals
Compiler Design
Operating System
Data Structure And Algorithms
Computer Network
DBMS
Excel
Java Tutorial
Java - Home
Java - Overview
Java - History
Java - Features
Java vs C++
Java Virtual Machine(JVM)
Java - JDK vs JRE vs JVM
Java - Hello World Program
Java - Environment Setup
Java - Basic Syntax
Java - Variable Types
Java - Data Types
Java - Type Casting
Java - Unicode System
Java - Basic Operators
Java - Comments
Java Control Statements
Java - Loop Control
Java - Decision Making
Java - If-else
Java - Switch
Java - For Loops
Java - For-Each Loops
Java - While Loops
Java - do-while Loops
Java - Break
Java - Continue
Object Oriented Programming
Java - OOPs Concepts
Java - Object & Classes
Java - Class Attributes
Java - Class Methods
Java - Methods
Java - Variables Scope
Java - Constructors
Java - Access Modifiers
Java - Inheritance
Java - Aggregation
Java - Polymorphism
Java - Overriding
Java - Method Overloading
Java - Dynamic Binding
Java - Static Binding
Java - Instance Initializer Block
Java - Abstraction
Java - Encapsulation
Java - Interfaces
Java - Packages
Java - Inner Classes
Java - Static Class
Java - Anonymous Class
Java - Singleton Class
Java - Wrapper Classes
Java - Enums
Java Built-in Classes
Java - Number
Java - Boolean
Java - Characters
Java - Arrays
Java - Math Class
Java File Handling
Java - Files
Java - Create a File
Java - Write to File
Java - Read Files
Java - Delete Files
Java - Directories
Java - I/O Streams
Java Error & Exceptions
Java - Exceptions
Java - try-catch Block
Java - try-with-resources
Java - Multi-catch Block
Java - Nested try Block
Java - Finally Block
Java - throw Exception
Java - Exception Propagation
Java - Built-in Exceptions
Java - Custom Exception
Java Multithreading
Java - Multithreading
Java - Thread Life Cycle
Java - Creating a Thread
Java - Starting a Thread
Java - Joining Threads
Java - Naming Thread
Java - Thread Scheduler
Java - Thread Pools
Java - Main Thread
Java - Thread Priority
Java - Daemon Threads
Java - Thread Group
Java - Shutdown Hook
Java Synchronization
Java - Synchronization
Java - Block Synchronization
Java - Static Synchronization
Java - Inter-thread Communication
Java - Thread Deadlock
Java - Interrupting a Thread
Java - Thread Control
Java - Reentrant Monitor
Java Networking
Java - Networking
Java - Socket Programming
Java - URL Processing
Java - URL Class
Java - URLConnection Class
Java - HttpURLConnection Class
Java - Socket Class
Java - Generics
Java Collections
Java - Collections
Java - Collection Interface
Java List Interface
Java - List Interface
Java - ArrayList
Java Queue Interface
Java - Queue Interface
Java - ArrayDeque
Java Map Interface
Java - Map Interface
Java - SortedMap Interface
Java Set Interface
Java - Set Interface
Java - SortedSet Interface
Java Data Structures
Java - Data Structures
Java - Enumeration
Java - BitSet Class
Java Collections Algorithms
Java - Iterators
Java - Comparators
Java - Comparable Interface in Java
Java Miscellaneous
Java - Recursion
Java - Regular Expressions
Java - Serialization
Java - Strings
Java - Array Methods
Advanced Java
Java - Command-Line Arguments
Java - Lambda Expressions
Java - Sending Email
Java - Applet Basics
Java - Javadoc Comments
Java - Autoboxing and Unboxing
Java - File Mismatch Method
Java - REPL (JShell)
Java - Multi-Release Jar Files
Java - Private Interface Methods
Java - Inner Class Diamond Operator
Java - Multiresolution Image API
Java - Collection Factory Methods
Java - Module System
Java - Nashorn JavaScript
Java - Optional Class
Java - Method References
Java - Functional Interfaces
Java - Default Methods
Java - Base64 Encode Decode
Java APIs & Frameworks
JDBC Tutorial
SWING Tutorial
AWT Tutorial
Servlets Tutorial
JSP Tutorial
Java Useful Resources
Java Compiler
Java - Questions and Answers
Java - Quick Guide
Java - Useful Resources
Java - Discussion
Java - Examples
Selected Reading
UPSC IAS Exams Notes
Developer's Best Practices
Questions and Answers
Effective Resume Writing
HR Interview Questions
Computer Glossary
Who is Who
Java - Thread Synchronization

Previous
Next
Need of Thread Synchronization?
When we start two or more threads within a program, there may be a situation when
multiple threads try to access the same resource and finally they can produce
unforeseen result due to concurrency issues. For example, if multiple threads try to
write within a same file then they may corrupt the data because one of the threads can
override data or while one thread is opening the same file at the same time another
thread might be closing the same file.

So there is a need to synchronize the action of multiple threads and make sure that only
one thread can access the resource at a given point in time. This is implemented using
a concept called monitors. Each object in Java is associated with a monitor, which a
thread can lock or unlock. Only one thread at a time may hold a lock on a monitor.

Thread Synchronization in Java


Java programming language provides a very handy way of creating threads and
synchronizing their task by using synchronized blocks. You keep shared resources
within this block. Following is the general form of the synchronized statement −

Syntax
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
Here, the objectidentifier is a reference to an object whose lock associates with the
monitor that the synchronized statement represents. Now we are going to see two
examples, where we will print a counter using two different threads. When threads are
not synchronized, they print counter value which is not in sequence, but when we print
counter by putting inside synchronized() block, then it prints counter very much in
sequence for both the threads.

Java.lang.Class class in Java | Set 1


Java provides a class with name Class in java.lang package. Instances of the class
Class represent classes and interfaces in a running Java application. The primitive Java
types (boolean, byte, char, short, int, long, float, and double), and the keyword void are
also represented as Class objects. It has no public constructor. Class objects are
constructed automatically by the Java Virtual Machine(JVM). It is a final class, so we
cannot extend it. The Class class methods are widely used in Reflection API.

In Java, the java.lang.Class class is a built-in class that represents a class or interface
at runtime. It contains various methods that provide information about the class or
interface, such as its name, superclass, interfaces, fields, and methods.

Here are some commonly used methods of the Class class:


getName(): Returns the name of the class or interface represented by this Class object.
getSimpleName(): Returns the simple name of the class or interface represented by this
Class object.
getSuperclass(): Returns the superclass of the class represented by this Class object.
getInterfaces(): Returns an array of interfaces implemented by the class or interface
represented by this Class object.
getField(String name): Returns a Field object that represents the public field with the
specified name in the class or interface represented by this Class object.
getMethod(String name, Class<?>… parameterTypes): Returns a Method object that
represents the public method with the specified name and parameter types in the class
or interface represented by this Class object.
newInstance(): Creates a new instance of the class represented by this Class object
using its default constructor.
isInstance(Object obj): Returns true if the specified object is an instance of the class or
interface represented by this Class object, false otherwise.
isAssignableFrom(Class<?> cls): Returns true if this Class object is assignable from the
specified Class object, false otherwise.

PreviousNext
Tutorial Playlist
Table of Contents
What is Java?JDKWhat Are Java APIs? Who Uses Java APIs?The Need for Java
APIsView More
Java application programming interfaces (APIs) are predefined software tools that easily
enable interactivity between multiple applications.

What is Java?
Java is an object-oriented programming language that runs on almost all electronic
devices and is the most common language used by web developers. Java is platform-
independent because of Java virtual machines (JVMs). It follows the principle of "write
once, run everywhere.” When a JVM is installed on the host operating system, it
automatically adapts to the environment and executes the program’s functionalities.

To install Java on a computer, the developer must download the JDK and set up the
Java Runtime Environment (JRE). Java offers many benefits, which we will explore in
detail.

Want a Top Software Development Job? Start Here!


Full Stack Development-MEANEXPLORE PROGRAM
JDK
APIs-in-Java-JDK.

As previously noted, a Java download consists of two files:

JDK
JRE
Installing Java is usually simple. To learn more, please see the Simplilearn article “One-
Stop Solution for Java Installation in Windows.”

The JDK file is key to developing APIs in Java and consists of:

The compiler
The JVM
The Java API
Compiler
A Java compiler is a predefined program that converts the high-level, user-written code
language to low-level, computer-understandable, byte-code language during the
compile time.

JVM
A JVM processes the byte-code from the compiler and provides an output in a user-
readable format.

Java APIs
Java APIs are integrated pieces of software that come with JDKs. APIs in Java provides
the interface between two different applications and establish communication.

We will learn more about Java APIs in the next section.

What Are Java APIs?


APIs are important software components bundled with the JDK. APIs in Java include
classes, interfaces, and user Interfaces. They enable developers to integrate various
applications and websites and offer real-time information.

The following image depicts the fundamental components of the Java API.

APIs-in-Java-API-Architecture.

Now that we know the basics of the Java API and its components, let’s explore who
uses them.

Who Uses Java APIs?


Three types of developers use Java APIs based on their job or project:

Internal developers
Partner developers
Open developers
Internal Developers
Internal developers use internal APIs for a specific organization. Internal APIs are
accessible only by developers within one organization.

Applications that use internal APIs include:

B2B
B2C
A2A
B2E
Examples include Gmail, Google Cloud VM, and Instagram.

Want a Top Software Development Job? Start Here!


Full Stack Development-MEANEXPLORE PROGRAM
Partner Developers
Organizations that establish communications develop and use partner APIs. These
types of APIs are available to partner developers via API keys.

Applications that use partner APIs include:

B2B
B2C
Examples include Finextra and Microsoft (MS Open API Initiative),

Open Developers
Some leading companies provide access to their APIs to developers in the open-source
format. These businesses provide access to APIs via a key so that the company can
ensure that the API is not used illegally.

The application type that uses internal APIs is:

B2C
Examples include Twitter and Telnyx.

The next section explores the importance of Java APIs.

The Need for Java APIs


Java developers use APIs to:

Streamline Operating Procedures


Social media applications like Twitter, Facebook, LinkedIn, and Instagram provide users
with multiple options on one screen. Java APIs make this functionality possible.

Improve Business Techniques


Introducing APIs to the public leads many companies to release private data to
generate new ideas, fix existing bugs, and receive new ways to improve operations. The
Twitter developer account is an example of an API that gives programmers private API
keys to access Twitter data and develop applications.
Create Powerful Applications
Online banking has changed the industry forever, and APIs offer customers the ability to
manage their finances digitally with complete simplicity.

Below we discuss the various types of Java APIs.

Types of Java APIs


There are four types of APIs in Java:

Public
Private
Partner
Composite
APIs-in-Java-Types-of-API

Public
Public (or open) APIs are Java APIs that come with the JDK. They do not have strict
restrictions about how developers use them.

Private
Private (or internal) APIs are developed by a specific organization and are accessible to
only employees who work for that organization.

Partner
Partner APIs are considered to be third-party APIs and are developed by organizations
for strategic business operations.

Composite
Composite APIs are microservices, and developers build them by combining several
service APIs.

You might also like