You are on page 1of 6

Q 1 What is Java?

Discuss the Features of Java in Detail Ans Java is a programming language and a platform Java is a high level, robust, object-oriented and secure
programming language Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995 James Gosling is known as the father of Java
Before Java, its name was Oak Since Oak was already a company, so James Gosling and his team changed the Oak name to Java Platform: Any hardware or software
environment in which a program runs, is known as a platform Since Java has a run-time environment (JRE) and API, it is called a platform registered Features of Java-
The primary objective of Java programming language creation was to make it portable, simple and secure programming language Apart from this, there are also some
excellent features which play an important role in the popularity of this language The features of Java are also known as Java buzzwords A list of most important
features of Java language is given below Simple Java is very easy to learn and its syntax is simple, clean and easy to understand According to Sun, Java language is a
simple programming 12language because, e C, C++, etc Distributed-Java is distributed because it facilitates users to create distributed applications in Java RMI and EJB
are used for creating distributed applications This feature of Java makes us able to access files by calling the methods from any machine on the internet Multi-threaded-
A thread is like a separate program, executing concurrently We can write Java programs that deal with many tasks at onceby defining multiple threads The main
advantage of multi-threading is tait doesn't occupy memory for each thread It shares a common memory area Threads are important for Multi-media, Web applications,
etc Dynamic-Java is a dynamic language It supports dynamic loading of classes It means classes are loaded on demand It also supports functionsfrom its native
languages, i e , C and C++ Java supports dynamic compilation and automatic memory management(garbage collection) Q 2 Explain in brief Types of Java Application
and also Discuss its Platform Ans Types of Java Applications-There are mainly 4 types of applications that can be created using Java programming:(1) Standalone
Application-Standalone applications are also know as desktop applications or window-based applications These are traditional software that we need to install on every
machine Examples of standalone application are Media player, Antivirus, etc AWT and Swing are used in Java for creating standalone applications (2) Web Application-
An application that runs on the server side and creates a dynamic page is called a web application Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc
technologinare used for creating web applications in Java (3) Enterprise Application-An application that is distributed in nature, such as banking applications, etc , is
called enterprise application? has advantages of the high-level security, load balancing and clustering In Java, EJB is used for creating enterprise applications (4) Mobile
Application-An application which is created for mobiledevices is called a mobile application Currently, Android and Java ME areused for creating mobile applications
There are 4 platforms or editions of Java :(1) Java SE (Java Standard Edition)-It is a Java programming platform It includes Java programming APIs such as java lang, java
java net, java util, java sql, Java math etc It includes core topics like OOPS, String Regex, Exception, Inner classes, Multithreading, 1/0 Streat Networking, AWT, Swing,
Reflection, Collection, etc (2) Java EE (Java Enterprise Edition)-It is an enterprise platformwhich is mainly used to develop web and enterprise applications It is bullon the
top of the Java SE platform It includes topics like Survlet[18:44,(3) Java ME (Java Micro Edition)-It is a micro platform which is mainly used to develop mobile
applications (4) JavaFX-It is used to develop rich internet applications It uses a light-weight user interface API CTCcesa Q 3 What are the Difference between Java and C
and Java and Ans C vs C++ vs Java : C++? The languages are based on each other but still, they are different inxecungdesign and philosophy The following table
describes the major differencesorybetween C, C++ and Java adingSN Basis1 OriginPattern Programming3 ApproachDes d5 Code 4 Dynamic or StatictionCC++JavaThe C
language is based on BCPL The C++ language is based on theThe Java programming language is based on both C and C++ C language It is an object- It is a pure object-
oriented programmingIt is a procedural language oriented programming language It also uses the bottom-language It uses the bottom-up approach It uses the top-
down approach up approach It is a dynamic progra- mming language It is a static progra- mming language The code is executed directly It is platform depen- dent It is
also a static pro- gramming language The code is executed The code is executed byExecution 6 Platform Dependencydirectly It is platform depen- dent the JVM It is
platform-indepen- dent because of bytecode It uses a compiler It also uses a compiler Java uses both com-7Translatoronly to translate the code into machine language
only to translate the code into machine language It generates the exe, It generates exe file It generates class file piler and interpreter and it is also konw as an
interpreted language 8 20 Array Sizehandling It uses new anddelete operator tomanage the memory, the memory It supports exception It also supports exception
handling It uses a garbage collector to manageIt does not support the overloadingconcept It supports the goto statement It also supports the goto statement It is widely
used for system programming Method and opeater overloading can be achieved Only method over loading can be achieved It does not support the goto statements It
is used to develop web applications, mobile applications and windows applications, An array can be decla red without declaring the size For example, int num] An array
should be declared with size For example, int num[10) An array should be declared with size Q 4 Java is Object-Oriented What are the Advantages of Object
Oriented Programming compared to Procedural Oriented Programming?Ans Java is Objected-Oriented Although influenced by its predecessors, Java was not designed
to be source-code compatible with any other language This allowed the Java team the freedom to design with a blank state Once outcome of this was a clean, usable,
pragmatic approach to objects Borrowing liberally from many seminal object-software environment of the last few decades Java manages to strike a balance between
the purist's 'everything is an object' paradigm and the pragmatist's 'stay out of my way' model The object model in Java is simple and easy to extend, while simple types,
such as integers are kept as high-performance non objects Procedural languages are the languages where each statement in the language tells the computer to do
something Get some input add these numbers, divided by 6, display that output A program in a procedural language is a list of instructions For very small programs no
other organising principle (often called aparadigm) is needed The programmer creates the list of instructions and thecomputer carries them out Pascal, C, BASIC,
Fortran and similar languagesare easily Being able to create your own types called extensibility; you can extend the capabilities of t language Traditional languages are
not usually extensible Without unnatur data If you want to read a data item in object, you call only way to access its data If you want to read a data in an object, you
call a member function in the object It will read the ite and return the value to you it can't access the data directly The data » hidden, so it is safe to accidental
alterations Data and its functions are sa to be encapsulated into a single entity, data encapsulation and data hidingare key terms in the description of object-oriented
languages No other functions can access the data This simplifies writing debugging and maintaining the program [18:46,A Java program typically consist of a number of
objects, which municates with each other by calling one another's member functions items are referred to as instance variables Calling an object's member is referred
to as sending a message to the object action Example [2013, 2014, 2020] Q 5What are the Data Types in Java? Explain in brief List the Basic Data Types used in Java
Explain with Suitable Ans Data types in Java-Data types defines a set of permitted valuesBwhich-analyzees of theccess totype, Like: int: pedal = fig of one This
statement exists a field named 'pedal' that holds the numerical valoe as figure of one The value assigned to a variable determines its data in which the legal operations
of Java are performed This behaviour specifies that, Java is a strongly-typed programming language Data types are divided into two groups:of yourme way,ation tohide
itsimplifythe legal operations can be performed In Java, all the variablesweds to be declared first i e before using a particular variable it must beaclared in the program
for the memory allocation process Primitive Data Types -A primitive data type specifies the size and types of variable values and it has no additional methods There are
eight primitive data types in Java :Data TypeSize 1 byteDescriptionbyteStores whole numbers from -128 to 127 Stores whole numbers from -32,768 to 32,767short2
bytesint4 bytes Stores whole numbers from -2,147,483,648 to2,147,483,647 Stores whole numbers from -9,223,372,036,8 bytes854,775,808 to
9,223,372,036,854,775,807 Stores fractional numbers Sufficient for4 bytesstoring 6 to 7 decimal digits8 bytesStores fractional numbers Sufficient for storing 15 decimal
digits1 bit Stores true or false values2 bytesStores a single character/letter or ASCII valuesNon-primitive Data Types/Reference Data Type: Reference variables are
created using defined constructors of the classes They are used to access objects These variables are declared to be of a specific type tha ot be changed For example
Employee, Puppy, etc he is thely haveOrk withties thetypes isof thenaturallongfloat5 into ae resultdoublelems-boolean charhe bothlled anly pro-min anta iteme
itemdata isre saidReference TypeDescriptionhidingClassriting It is a set of instructions It describes the content of theobject [18:46,ArrayAnnotationsIt provides the fixed-
size data structure that stores the elements of the same type It provides a way to associate metadata with p programInterfaceEverything in Java is associated with
classes and objects, along with isattributes and methods For example: in real life, a car is an object The carhas attributes, such as weight and colour and methods, such
as drive andbrake elements It is implemented by Java classes Enumeration It is a special kind of class thatis type-safe, element inside the enum is an instance of that
enum Each Q 6 What is Class? How to Define Class and Create Objects in Java Ans Java is an object-oriented programming language (2011)A class is a user defined
blueprint or prototype from which objects a created It represents the set of properties or methods that are common to all objects of one type In general, class
declarations can include these components, in order:1 Modifiers-A class can be public or has default access (Refer this for details) 2 Class keyword-Class keyword is
used to create a class 3 Class name The name should begin with an initial letter (capitalized by convention) 4 Super-class (if any) The name of the class's parent (super-
class), if any, preceded by the keyword extends A class can only extend(sub-class) one parent 5 Interfaces (if any)-A comma-separated list of interfacesimplemented by
the class, if any, preceded by the keywoimplements A class can implement more than one interface 6 Body-The class body surrounded by braces ( ) Constructors are
used for initializing new objects Fields are variables that provides the state of the class and its objects and methods are used to implement the behaviour of the class
and its objects There are various types of classes that are used in real time applications such as nested classes anonymous classes, lambda expressions Classes defined
in the following way: class MyClass (//field, constructor and // method declarationsThis is a class declaration The class body (the area between the braces) contains all
the code that provides for the life-cycle of the objects created from the class; constructors for initializing new objects, , an object is created from a class In Java, the new
keyword is used create new objects Object :There are three steps when creating an object from a class- Declaration-A variable declaration with a variable name
withobject type • Instantiation-The 'new' keyword is used to create the object an• Initialization-The 'new' keyword is followed by a call to a constructor This call
initializes the new object Following is an example of creating an object-Example: public class Puppy {public Puppy (String name) (// This constructor has one parameter,
name System out println("Passed Name is ":" + name);public static void main(String[] args) {// Following statement would create an object myPuppy Puppy myPuppy
new Puppy( "tommy"); =compile and run the above program, then it will produce the Mosing resul OutputIf we2 Q 7 Explain the Concept of Class, Object and method
in Java Also Passed Name is tommy write a Program to Explain the Concept of Overloading Methods -door, name, breed as well as behaviours-wagging the tail,
barking [18:47,eating An object is an instance of a class dogs, humans, etc All these objects have a state and a behaviour, Iv consider a dog, then its state is-name,
breed, colour and the behaviour If you compare the software object with a real-world object, they ha barking, wagging the tail, running very similar characteristics
Software objects also have a state and a behaviour A software obje state is stored in fields and behaviour is shown via methods So in software development, methods
operate on the internal state of a object and the object-to-object communication is done via methods Classes in Java : A class is a blueprint from which individual objects
are created Following is a sample of a class Example :public class Dog [ String breed;int age; String colour:void barking () {void hungry () {void sleeping (){}Methods in
Java: A Java method is a collection of statements thatgrouped together to perform an operation When yon call the System ou println() method, for example, the system
actually executes sever statements in order to display a message on the console Now you will learn how to create your own methods with or wither return values,
invoke a method with or public static void main(String[] args) {int a = 11; int b = 6;double c = 7 3;double d = 9 4;int result figure of one (1) minFunction(a, b); // same
function name with different parametersdouble result2= minFunction(c, d); System out println("Minimum Value = " + result fig of one); System out println("Minimum
Value=" + result2);for integer public static int minFunction(int n fig of one int n2) (int min;if (n fig one > n2) min = n2;elsemin = n one: return min;for doublepublic static
double minFunction{ double n one, double n2) {double min:if (n one > n2)min = n2:min = n one; return min;This will produce the following result-Output:Minimum Value
= 6 Minimum Value = 7 3 [18:48,Overloading methods makes program readable Here, two methods aregiven by the same name but with different parameters The
minimum number from integer and double types is the result Q 8 Explain the Term Inheritance and its Types Along with Example Also Explain Why we use Virtual
class What do you mean by Inheritance? Describe the Various Types Or, of Inherence with Example Define Inheritance Describe Various Types of Inheritance
withExamplesAns Inheritance in Java is a mechanism in which one object acquiresall the properties and behaviours of a parent object It is an important par of OOPS
(Object Oriented Programming System) The idea behind inheritance in Java is that you can create new classes that are built upon existing classes When you inherit from
an existing class you can reuse methods and fields of the parent class Moreover, you can addnew methods and fields in your current class also Inheritance represents
the IS-A relationship which is also known as aparent-child relationship Why use inheritance in Java?• For Method Overriding (so run-time polymorphism can be
achieved) For Code Reusability The syntax of Java Inheritance : 1 class Subclass-name extends Superclass-name2 13 //methods and fields4 1The extends keyword
indicates that you are making a new class that derives from an existing class The meaning of "extends" is to increase the functionality In the terminology of Java, a class
which is inherited is called a parentor super class and the new class is called child or sub-class Types of inheritance in Java : On the basis of class, there a base class, it
must override the virtual inner classes it inherited from the base class An obje of the child class may be referred to by a reference or pointer of the par class type or the
child class type When the reference or pointer i virtual inner classes, the derived class's implementation will be called[18:48,e of the inner virtual class 107A method
with an object argument has access to the object's virtual method can use the virtual classes of its arguments to create ces and declare variables Virtual classes of
different instances are not The Lovex tible Q 9 Why Multiple Inheritance is not Supported in Java ? To reduce the complexity and simplify the language, multiple is not
supported in Java Consider a scenario where A, B and C are three classes The C class entance A and B classes If A and B classes have the same method and you from
child class object, there will be ambiguity to call the method of B class 0 9 Since compile-time errors are better than run-time errors, Java renders ple-time error if you
inherit 2 classes So whether you have same thod or different, there will be compile-time error 1 class A{ 2 void msg0(System out println("Hello");}3 1 5 void msg)
(System out println("Welcome");}4class B7 class C extends A,B (//suppose if it were 8 9 peblic static void main(String args[]){ 10 C obj=new C(); 11 obj msg(): //Now
which msg() method would be invoked?12 113 1 Q 10 What is Virtual Function? Explain with Example why we useVirtual Function Ans Being an Object-oriented
Programming Language, Java supports tures like inheritance, polymorphism, upcasting, etc, Therefore, OOPs in la deals with objects, classes and functions A virtual
function is one of the member function that facilitates run-time polymorphism in Java In this cle, we will discuss the virtual function in Java Definition: It is a member
function that facilitates the method iding mechanism That means, in OOPS, a virtual function of the Pet class is a function that can be overridden by a child class that has
the e type but with different functionality Syntaxtax of Java with annotations To implement the overriding mechanism for the virtual function, @Override annotation
may be used here to specifically Pint out which virtual function we want to override, although it is not andatory [18:49,When we call an overridden method of child class
through its p type reference, then the type or reference of the object indicates w method will he invoked The conclusion of this decision occurs during re time after the
compilation So, the virtual function's functionality overridden by the inherited child class of the same type Some Points Regarding Virtual Function:Functions of child
and parent class must have the same name have the same parameter IS-A relationship is mandatory (inheritance) A virtual function cannot be Private as we cannot
override the pare A virtual function cannot be stated as Final, as we cannot overclass's Private it will be the default Example :class Demoint i: (Default)There are many
non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc Here, we are going to learn the access modifiers only The differences between
public, private, protected and no modifier/default in Java In short, following image summarizes the differences :VisibilityDefaultPublic Protected PrivateSame classClass
in same packageSub-class in same packageYesNoSub-class outside the same package Non sub-class outside thesame packageYesYesYes Yes Yes YesYesYesNoNoYes
YesNo Yes NoDifferences:iq opengenus org22222 Yes NoFirst and important difference is the accessibility i e anything ab is accessible to anywhere, anything private is
only accessible in the class they are declared, anything protected is accessible outside the package but only to child classes and default is accessible oinside the package
Another difference betweenpublicEncapsulation Public[15:23, 15/03/2023]Q 11 What is Access Control Specifier? Explain the Difference among Private, Protected
and Public Access Control Specifiers Or Discuss the Different Acess Modifiers in Java Ans The access modifiers/access control specifier in Java specifies the
accessibility or scope of a field, method, constructor or class We can changethe access level of fields, constructors, methods, and class by applying the access modifier
on it There are four types of Java access modifiers :Public Specifiers: Public Specifiers achieves the highest level of accessibility Classes methods and fields declared as
public can be accessed from any class in theJava program, whether these classes are in the same package or in anotherpackage In short the access level of a public
modifier is everywhere It can be accessed from within the class, outside the class, within the package andoutside the package public class Demo { // public
classExample:public x y size; // public instance variablesPrivate specifiers: Private Specifiers achieves the lowest level of accessibility Private methods and fields can
only be accessed within the same class to which the methods and fields belong Private methods and fields are not visible within sub-classes and are not inherited by
sub-classes So, the private access specifier is opposite to the public access specifier 2023]Encapsulation and Private modifier provides higher level of111Encapsulation
in Java Another difference is that you can use public modifier with top level class but you cannot make a top level class private in Java You can make inner class private
Another difference is that default is package level accessibility i e if you don't provide any access modifier to a class, method or variable then Java by default make them
accessible inside the package Another difference between protected and default modifier is that protected modifier provides more accessibility than default modifier
You can access a protected member outside the package, but onlyinside sub-classes That's all about difference between public, private, protected and no modifier in
Java Q 12 What is Interface? How to Extend and Implement it? Explainwith Suitable Example Ans An interface is a reference type in Java It is similar to class It is a
collection of abstract methods A class implements an interface, thereby inheriting the abstract methods of the interface Along with abstract methods, an interface may
also contain constants, default methods, static methods and nested types Method bodies exist only for default methods and static methods Writing an interface is
similar to writing a class But a class describesre going to the attributes and behaviours of an object And an interface contains behaviours that a class implements as
static,d and no mes:Protected PUnless the class that implements the interface is abstract, all themethods of the interface need to be defined in the class Implementation
of Interfaces :When a class implements an interface, we can think of the class assigning a contract, agreeing to perform the specific behaviours of the Yes interface If a
class does not perform all the behaviours of the interface, the Yes class must declare itself as abstract A class uses the implements keyword to implement an interface
The Yes implements keyword appears in the class declaration following the extendsYesNo portion of the declaration Example:/* Filename: MammalInt Java */public
class MammalInt implements Animal public);// Filename: Football javapublic interface Football extends Sports {public void homeTeamScored(int points);public void
visiting TeamScored(int points); public void endOfQuarter(int quarter);} // Filename: Hockey Javapublic interface Hockey extends Sports { public void homeGoalScored();
public void visitingGoalScored();public void endOfPeriod(int period); public void overtime Period(int ot);[15:24, 15/03/2023]The Hockey interface has four methods, but
it inherits two from Sports: thus, a class that implements Hockey needs to implement all six methods Similarly, a class that implements Football needs to define the
three methods from Football and the two methods from Sports Q 13 What is Interface? How are Interfaces Created and implemented in java?Ans Interface looks like
a class but it is not a class An interface can have methods and variables just like the class but the methods declared in interface are by default abstract (only method
signature, no body ) Also, the variables declared in an interface are public, static and final by default The use of Interface in Java : As mentioned above they are used for
full abstraction Since methodsin interfaces do not have body, they have to be implemented by the class before you can access them The class that implements interface
must implement all the methods of that interface Also, Java Programming language does not allow us to extend more than one class However you can implement more
than one interfaces in our class Syntax : Interfaces are declared by specifying a keyword "interface" E g :interface MyInterfaceAll the methods are public abstract by
default As you see they have no bodypublic void methodone(): public void method2();Example of Implementation of an Interface in Java :This is how a class implements
an interface It has to provide the body of all the methods that are declared in interface or in other words we can say that class has to implement all the methods of
interface Class implements interface but an interface extends another interface interface MyInterface/* compiler will treat them as; I public abstract void methodone();
public abstract void method2();*/public void methodone(): public void method2():class Demo implements MyInterface/*This class must have to implement both the
abstract methods:[15:25, 15/03/2023]else you will get compilation error;public void method 10)System out println("implementation of method figure ofpublic void
method20)System out println("implementation of method2");public static void main(String arg[])MyInterface obj = new Demo(): obj method 10);Output:implementation
of methodQ 14 What is an interface? Explain the Implementation of Multiple Inheritance using Interfaces with the help of some Program? Ans An interface in Java is
a blueprint of a class It has static constantsand abstract methods The interface in Java is a mechanism to achieve abstraction There can be only abstract method in the
Java interface, not method body It is usedto achieve abstraction and multiple inheritance in Java In other words, you can say that interfaces can have abstract methods
and variables It cannot have a method body Java Interface also represents the IS-A relationship It cannot be instantiated just like the abstract class Since Java 8, we can
have default and static methods in an interface Multiple inheritance in Java by interface:If a class implements multiple interfaces, or an interface extends multiple
interfaces, it is known as multiple inheritance interfaceinterfaceinterfaceinterfaceimplementsextendsclassinterface1 interface Printable{Multiple Inheritance In
Javaone")2 void print ():3 ) 4 interface Showable(5 void show();[15:25, 15/03/2023]6 )7 class A7 implements Printable, Showable(8 public void print() (System out
println("Hello");) 9 public void show() (System out println("Welcome");)10 11 public static void main(String args[]){12 A7obj newA7();13 obj print(): obj show():14 15
116 Output:HelloWelcomeMultiple inheritance is not supported through class in Java, but it is possible by an interface, multiple inheritance is not supported in the case
of class because of ambiguity However, it is supported in case of an interface because there is no ambiguity It is because its implementation is provided by the
implementation class 1 interface Printable(2 3 )void print():4 interface Showable(5 void print():6 ) 7 8 class TestInterface3 implements Printable, Showable(9 public
void print()(System out println("Hello");) 10 public static void main(String args[]){ 11 Test Interfaces3 obj = new TestInterface3();12 obj print();13 )14 )Test it
nowOutput:HelloAs we can see in the above example, Printable and Showable interface have same methods but its implementation is provided by class TestInterfacel,
so there is no ambiguity Q 15 What is Applet? Discuss the Life Cycle of Applet Or, What is the Purpose of Applet Programming in Java? Explain the Life Cycle of an
Applet in Details Or, Explain the Life Cycle of Java Applets Also Create an Applet in which a String Moves from Left to Right Ans 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 web site more dynamic and entertaining Important points :All applets are sub-classes (either directly or indirectly)
of Java applet Applet class Applets are not stand-alone programs Instead, they run within either a web browser or an applet viewer JDK provides a standard applet
viewer tool called applet viewer In general, execution of an applet does not begin at main() method,Output of an applet window is not performed by System out printin
() Rather it is handled with various AWT methods, such asdrawString() Applet Life Cycle:Varicus states, an applet, undergoes between its object creation and object
removal (when the job is over) is known as Applet Life Cycle Each state is represented by a method There exists 5 states represented by 5 methods That is, in its life of
execution, the applet exists (lives) in one of these 5 states These methods are known as "callback methods" as they are called automatically by the browser whenever
required for the smooth execution of the applet Programmer just write the methods with some code but never calls Following are the methods: init(): The applet's
voyage starts here In this method, the applet object is created by the browser Because this method is called before all the other methods, programmer can utilize this
method to instantiate objects, initialize variables, setting background and foreground colours in GUI etc ; the place of a constructor in an application It is equivalent to
born state of a thread inft() methodstart() methodpaint() methodstop() methoddestroy() methodLife cycle of AppletBrowser Responsibilities:The Applet Life Cycle
methods are called as callback methods as they are called implicitly by the browser for the smooth execution of the called applet Browser should provide an
environment known as container for the execution of the applet Following are the responsibilities of the browser:et is25sarythelike1 It should call the callback methods
at appropriate times for the smooth execution of the applet 2 It is responsible to maintain the Applet Life Cycle 3 It should have the capability to communicate
between applets, applet to JavaScript and HTML, applet to browser etc [15:26, 15/03/2023]Q 16 What is an Applet and Application? How do Applets Differ fromOr,
Application Programs Why do Applet Classes used to be Declared as Public? Explain the Applet Differentiate between Applet andApplication in Java Ans All Java
Programs are classified as Applications and Applets While applications are stand-alone Java programs that run directly machine, applets are specific programs that
require use of a browser and should be included in an HTML web document [2012, 2015 on yourIn simple terms, application programs run with the help of a machine
independent of any security restrictions, whereas an applet cannot run without the help of a browser and is subjected to more harsh security restrictions in terms of
network access You can say, applets are kind of an internet application that doesn't require any kind of deployment procedure or installation Let's study the difference
between the two in detail Java Applet : Applet is a special type of program that is embedded in virtualthe webpage to generate the dynamic content It runs inside the
browser andworks at client side Advantage of Applet :There are many advantages of applet They are as follows: It works at client side so less response time • Secured
It can be executed by browsers running under many platforms, including Linux, Windows, Mac Os etc An Application: It is a stand-alone Java program that runs with
the support of a virtual machine in a client or server side Also referred to as an application program, a Java application is designed to perform a specific function to
applet program is used touser It can access all kinds of It can only access the browser resources available on the system specific services The fundamental difference
between the two Java programs is that an application program is designed to run on a stand-alone machine whereas, an applet is a web-version of an application which
is used to run a program on a web browser While an application can access all the resources available on the system, an applet cannot have access to anything on the
machine except the browser specific services Q 17 Write an Applet Program to Pass the Parameter Ans Parameters specify extra information that can be passed to
anymenthe boLows:refemalform applet from the HTML page Parameters are specified using the HTML'sgarden param tag the useParam Tag :The <param> tag is a sub
tag of the <applet> tag The <param> tag Excontains two attributes: name and value which are used to specify the name of the parameter and the value of the
parameter respectively ationsmin Ication pon theun byled wation prhas aFor example, the param tags for passing name and age parameters looks as shown
below:<param name="name" value="Ramesh"/> <param name="age" value="25"/>Now, these two parameters can be accessed in the applet program using the
getParameter() method of the Applet class getParameter() Method :The get Parameter () method of the Applet class can be used to retrieve the parameters passed
from the HTML page The syntax of getParamiter() method is as follows:[15:27, 15/03/2023]String getParameter(String param-name) Let's look at a sample program
which demonstrates the <param> HTML tag and the getParameter() method:import java awt "; import Java applet "; 1 public class My Applet extends Applet2 1 3 4 3
6 7 8 11 12 13 14 ) 15 16 18 19 20 22 23 String n;String a; public void init()n = getParameter("name"); a = getParameter("age"):)9 10 public void paint(Graphics
g)(g drawString("Name is:" + n, 20, 20);g drawString("Age is:" + a, 20, 40);121 <applet code="MyApplet"height="300" width="500"><param name="name"
value="Ramesh" /><param name="age"value="25" /> </applet>Output of the above program is as follows:Applet Viewer MyAppletsarcongemate0CaAQ 18 Design an
Applet to Print Hello Java Also Write HTML Code toDisplay the Applet Ans Creating Hello World Applet : Let's begin with the Hello World applet :[2011]UNU// A Hello
World Applet// Save file as HelloWorld Java[15:27, 15/03/2023]import java applet Applet; import java awt Graphics;// Hello World class extends Appletpublic class
Hello World extends AppletOverriding paint () method @Override public void paint (Graphics g)g drawString("Hello World", 20, 20);Running the Hello World Applet
:After you enter the source code for Hello World: java, compile in the same way that you have been compiling java programs (using javac command) However, running
Hello World with the java command will generate an error because it is not an application Java Hello WorldError: Main method not found in class Hello World, please
define the main method as: public static void main(String[] args)To execute an applet in a web browser we have to write a short HTML text file that contains a tag that
loads the applet We can use APPLET or OBJECT tag for this purpose Using APPLET, here is the HTML file that executes Hello World:<applet code="Hello World"
width=200 height=60></applet>The width and height statements specify the dimensions of the displayarea used by the applet The APPLET tag contains several other
options Atter you create this HTML file, you can use it to execute the applet Q 19 What is Package? How do you Create a Package? How does a [2016, 2017)Package
Declaration affect a Class definition? Ans PACKAGE in Java is a collection of classes, sub-packages and interfaces It helps organise your classes into a folder structure
and make it easy to locate and use them More importantly, it helps improve codo reusability Each package in Java has its unique name and organises its classes
andinterfaces into a separate namespace or name group Although interfaces and classes with the same name cannot appear in the same package, they can appear in
different packages This is possible by assigning a separate namespace to each Java package Syntax :package nameofPackage:[15:28, 15/03/2023]Creating a
Package:While creating a package, we should choose a name for the package and include a package statement along with that name at the top of every source file that
contains the classes, interfaces, enumerations and annotation types that you want to include in the package The package statement should be the first line in the source
file There can be only one package statement in each source file and it applies to all types in the file If a package statement is not used then the class,
interfaces,enumerations and annotation types will be placed in the current default package To compile the Java programs with package statements, you haveto use-d
option as shown below: javac -d Destination_folder file_name javaThen a folder with the given package name is created in the specified destination, and the compiled
class files will be placed in that folder Example :Let us look at an example that creates a package called animals It is a good practice to use names of packages with
lower case letters to avoid any conflicts with the names of classes and interfaces Following package example contains interface named animals: File name: Animal java
*/package animals;interface Animal (public void eat(): public void travel();Now, let us implement the above interface in the same packageanimals:package animals:/*
File name: MammalInt java */public class MammalInt implements Animal public void eat() {System out println("Mammal eats");public void travel()) { System out print
Mammal I travels");public int noOfLegs (return 0:public static void main(String args[]) {[15:28, 15/03/2023]Mammal m = new MammalInt():m eat (): m travel():Now
compile the Java files as shown below-S javac -d Animal java S javac -d Mammal IntjavaNow a package/folder with the name animals will be created in thecurrent
directory and these class files will be placed in it Q 20 What is String? How can we handle String in Java? Write anApplication Program in Java to check Whether the
two Input Strings are Equal Ans String is an object that represents sequence of characters In Java,[2012]String is represented by String class which is located into java
lang package It is probably the most commonly used class in Java library InJava, every string that we create is actually an object of type String One important thing to
notice about string object is that string objects are immutable that means once a string object is created it cannot bechanged The Java String class implements
Serializable, Comparable and CharSequence interface that we have represented using the below image:serializablecomparablecharsequenceimplements stringIn Java,
CharSequence Interface is used for representing a sequence of characters CharSequence interface is implemented by String, StringBuffer and StringBuilder classes This
three classes can be used for creating strings in Java Creating a String Object:String can be created in number of ways, here are a few ways of creating string object :(1)
Using a String Literal-String literal is a simple string enclosed in double quotes" " A string literal is treated as a String Object (2) Using new Keyword-We can create a new
string object by using new operator that allocates memory for the object Each time we create a String Literal, the JVM checks the string pool first If the string literal
already exists in the pool, a reference to the pool instance is returned If string does not exist in the pool, a new string object is created and is placed in the pool String
objects are stored in a special[15:28, 15/03/2023]String Comparison:To compare string objects, Java provides methods and operators both So we can compare string in
following three ways:1 Using equals () method 2 Using operator3 By CompareTo() method Using equals() methodequals() method compares two strings for equality Its
general syntax is, boolean equals (Object str) It compares the content of the strings It will return true if stringExample:matches, else returns false 1 public class Demo{2
public static void main(String[] args) {3 String s= "Hell"; 4 String sl "Hello":5 String $2 "Hello";6 boolean b= s1 equals(s2); // true7 Systemout println(b); 8 b= s
equals(s1); //false9 System out println(b);10 ) 11 )OUTPUT:true falseQ 21 What is a Thread? How to Create Thread? Discuss the Life Cycle of a Thread in Detail Or,
What do you mean by the Life Cycle of Thread? Ans Threads can help us to do parallel processing Threads are usefulwhen we want to run multiple pieces of code in
parallel A thread can be defined as a lightweight process which can execute multiple codes in parallel However, the thread is different from a process In OS, for each
process, a separate memory will be allocated And the same is applicable for thread as well, it has separate memory All the threads will run in the same memory which
is allocated for the process A Thread can be created in Java in the following ways: 1 By Extending Thread Class Thread class:Thread class provide constructors and
methods to create and perform operations on a thread Thread class extends object class and implements Runnable interface causes the currently executing thread to
sleep (temporarily cease execution) for thespecified number of milliseconds public void join(): waits for a thread to die public into running state only from runnable
state 4 Blocked (Non-runnable state)- A thread is considered to be in theblocked state when it is suspended, sleeping or waiting for some time inorder to satisfy some
condition 5 Dead state-A thread dies or moves into dead state automatically when its run() method completes the execution of statements That is, thread is
terminated or dead when a thread comes out of run() method A thread can also be dead when the stop() method is called During life cycle of thread in Java, a thread
moves from one state toanother state in a variety of ways This is because in multithreading environment, when multiple threads are executing, only one thread can use
CPU at a time All other threads live in some other states, either waiting for their turn on CPU or waiting for satisfying some conditions Therefore, a thread isalways in
any of the five states Q 22 What do you mean by Multithreading? Compare with Multitasking Ans Multithreading:Multithreading is a system in GraphicResponding to
KeystrokesGrammar Checkwhich many threads are created from a process through which the computer power is increased In multithreading, CPU is provided in order
to execute many threads from a process at a time, and in multithreading, process creation is performed according to cost Unlike multithreading provides the same
memory and resources to the processes Muititasking, for execution ThrendThrendThrendWord ProcessorCPUMultithreadingMultitasking: Multitasking is when a CPU is
provided to execute tasks at a time Multitasking involves often CPU switching between the tasks, so that users can collaborate with each program together
UnlikeBrowserExcelVLCProcessOperating SystemCPUMultitasking[15:29, 15/03/2023]altithreading, in multitasking, the processes share memory and resources As
multitasking involves CPU switching between the tasks rapidly, so the little time is needed in order to switch from the one user to next Let's see the difference between
multitasking and multithreading:MultitaskingS No 1 23 MultithreadingIn multitasking, users allowed to perform many tasks by CPU are While in multithreading, many
threads are created from a process through which computer power is increased Multitasking involves often CPU switching between the tasks In multitasking, the
processesshare separate memory 4 Multitasking5 componentinvolves multiprocessing In multitasking, CPUWhile in multithreading also, CPU switching is often involved
between the threads While in multithreading, processes are allocated same memory While multithreading component does not involve multiprocessing is While in
multithreading also, CPU provided in order to execute is provided in order to execute many threads from a process at a time many tasks at a time Q 23 Illustrate the
Pros and Cons of Different Ways of Creating athread Ans There are two ways to create a new thread of execution One is to declare a class to be a sub-class of Thread
This sub-class should override the run method of class Thread An instance of the sub-class can then be allocated and started For example, a thread that computes
primes larger than a stated value could be written as follows:1 CLASS PRIMETHREAD EXTENDS THREAD{2 LONG MINPRIME;3 PRIMETHREAD(LONG MINPRIME){ 4 THIS
MINPRIME = MINPRIME5 )6 PUBLIC VOID RUN(){ 7 //COMPUTE PRIMSE LARGER THAN MINPRIME9 110 1The following code would then create a thread and start it
running : Prime Thread p = new Primse Thread(143);p start();the advantages and disadvantages of using the Thread class method [15:30, 15/03/2023]Advantages:need
to use the Thread currentThread() method You can use this to get the It is easy to write If you need to access the current thread, you don't current thread
Disadvantages: Because threads inherit the Thread class, they cannotinherit other parent classes Runnable interface the Runnable interface That class then implements
the run method An The other way to create a thread is to declare a class that implements instance of the class can then be allocated, passed as an argument when
creating Thread and started The same example in this other style looks likethe following:1 CLASS PRIMERUN IMPLEMENTS RUNNABLE( 2 LONG MINPRIME:3
PRIMERUN (LONG MINPRIME}{ 4 THIS MINPRIME = MINPRIME; 5 )6 PUBLIC VOID RUN(){ 7 //COMPUTE PRIMIE LARGER THAN MINPRIME8 9 )10 ]DessugGeExecuof the
madrun, the mto the JVNcode is eClasits classreferenceA cthat areThe following code would then create a thread and start it running:PrimeRun p = new PrimeRun(143);
new Thread(p) start();Advantages and disadvantages of creating maltithreading using the Runnable interface:Advantages:The thread class only implements the Runable
interface can continue to inherit other classes In this way, multiple threads can share a target object, so it is very suitable for multiple identical threads to handle the
same resource situation, so that CPU can be used Separate code and data, a clear- cut model that better reflects object-oriented thinking Disadvantages:Programming is
more complicated If you want to access the current thread, yon must use the Thread, current Thread() method Q 24 Explain the Process of Compiling and Running of
Java Programs in Detail Ans Being a platform independent programming language, doesn't work on one-step-compilation Instead, it involves a two-step execution,
first through an OS independent compiler; and second, in a virtual machine (JVM); which is custom-built for every operating system The two principle stages are
explained below:Tloadeprimoembedefaclassloadcustpripreclaby[15:30, 15/03/2023]Compilation:129First, the source 'java' file is passed through the compiler, which
then codes the source code into a machine independent encoding, known as Bytecode The content of each class contained in the source file is stored in separate class'
file While converting the source code into the bytecode, the compiler follows the following steps:Parse: Reads a set of java source files and maps the resulting token
sequence into AST (Abstract Syntax Tree)-Nodes Enter: Enters symbols for the definitions into the to be inspected by the bytecode verifier, whose job is to check that
the instructions don't perform damaging actions The followingare some of the checks carried out:• Variables are initialized before they are used Method calls match
the types of object references Rules for accessing private data and methods are not violated Local variable accesses fall within the run-time stack The run-time stack
does not overflow If any of the above checks fails, the verifier doesn't allow the class to be loaded Just-In-Time Compiler This is the final stage encountered by the Java
program, and its job is to convert the loaded bytecode into machine code When using a JIT compiler, the hardware can execute the native code, as opposed to having
the JVM interpret the same sequence of bytecode repeatedly and incurring the penalty of a relatively lengthy translation process This can lead to performance gains in
the execution speed, unless methods are executed less frequently The process can be well-illustrated by the diagram 1 Due to the two-step execution process described
above, a Java programis independent of the target operating system However, because of the same, the execution time is way more than a similar program written in a
compiled platform-dependent program Diagram 1 Q 25 What is Variable Size Array? Write a Program to Explain the use of Variable Size Array in Java Ans An array is
used in Java programming to store large amount of data in one variable with different index or subscript The availability to use single name to represent a collection of
item and to refer to an item by specifying the item number enables us to develop concise and efficient program For example, a loop with the subscript as the control
variable can be used to read entire array, perform calculation and entire print the result When array is declared in any programming language including Java, they
specify size of array variable and only limit number of items can be stored in that array variable All other programming language provide facility of only fixed size array
with one dimension or multi-dimension Java provide facility including one dimensional and two-dimensional array and is called variable size array The variable size array
very length of size in columns but it fixes row size According to size of values, length of memory location increases or decrease The variable size array used in Java a
programming to store data in multi-dimensional array with their different length Before using of variable size array its row can be fix but its column can be empty and
after that multiple values with different length can be stored in that array Java treats multi-dimensional array as 'array of array' or variable size array It is possible to
declare a two-dimensional array as array of array or variable size array An example of variable size array can be declaring in the following format:[15:31, 15/03/2023]int
x = new int [3] [[0]= new int (2);[1] = new int [4]: [2]= new int [3];Here, variable X is declared as two-dimensional array with fixed umber of rows but its column size
differs from each other Variable X[0] contains two columns, X[1] contains four columns and X[2] contains three columns After every declaration, column size varies
from different variables and show that these variables are called variable size Q 26 What do you mean by Run-time Error and Compile Time Error ? Ans Errors in Java
occur when a programmer violates[2013]the rules of Javaprogramming language It might be due to programmer's typing mistakeswhile developing a program It may
produce incorrect output or mayterminate the execution of the program abnormally For example, if you use a right parenthesis in a Java program where a right brace is
needed, you have made a syntax error You have violated the rules of Java language Therefore, it is important to detect and fix properly all error occurringin a program
so that the program will not terminate during execution Type of Errors in Java Programming : When we write a program for the first time, it usually contains errors
These errors are mainly divided into three types: 1 Compile-time errors (Syntax errors),2 Run-time errors, For example, if a user inputs a value of string type in a
program but thecomputer is expecting an integer value, a run-time error will be generated Most common run-time errors are as follows: 1 Dividing an integer by zero 2
Accessing an element that is out of rangeof the array 3 Trying to store a value into an array that is not compatible type 4 Passing an argument that is not in a valid
range or validfor amethod 5 Striving to use a negative size for an array 6 Attempting to convert an invalid string into a number 7 and many more When such errors are
encountered in a program, Java generates an error message and terminate the program abnormally To handle these kinds of errors during the run-time, we use
exception handling technique in javaprogram Program source code: In this program, we will divide annumber by zero Java compiler cannot detect 1 public class
divisionbyzeroError2 ( 3 public static void main(string[] args)4 56int a = 20, b = 5, c = 5; int z= a/(b-c); // Division by zero 7system outprintin ("Result:" +2);it
integerNUT[10])[15:32, 15/03/2023]output:Exception in thread "main" java lang ArithmeticException: /by zeroaterrorsProgram DivisionByZeroError main(Divsion
ByZeroError Java:8) The above program is syntactically correct There is no syntax error and therefore, does not cause any problem during compilation While executing
run-time error occurred that is not detected by compiler The error is detected by JVM only in run-time Default exception handler displays an error message and
terminates the program abnormally without executing further statements in the program Q 27 What are Exceptions ? Discuss how to Handle Exceptions in Java with
Suitable Example?Ans In Java, an exception is an event that disrupts the normal flow of the program It is an object which is thrown at run-time There are mainly two
types of exceptions: checked and unchecked Here, an error is considered as the unchecked exception According toOracle, there are three types of exceptions:1
Checked Exception: The classes which directly inherit Throwable class except run-time Exception and Error are known as checked exceptions e g 10Exception,
SQLException etc Checked exceptions are checked at compile-time 2 Unchecked Exception: The classes which inherit run-time Exception are known as unchecked
exceptions e g , Arithmetic Exception,NullPointerException, ArrayIndex OutOf Bounds Exception of Java Exception Handling where we using a try catch statement to
handle the exception 1 public class JavaExceptionExample 2 public static void main(String args[]){3 tryl4 //code that may raise exception 5 intdata= 100/0;6
)catch(ArithmeticException e) (System out println(e);)7 //rest code of the program8 System out println("rest of the code ");9 } 10 )Exception in thread main java lang
ArithmeticException:/ by zerorest of the code In the above example, 100/0 raises an ArithmeticException which ishandled by a try-catch block Q 28 What is the Need
of Static Method? Explain why Main Methods in Java is always Static Ans Static Method-Static methods are the methods in Java that can be called without creating an
object of class They are referenced by the class name itself or reference to the Object of that class public static void geek(String name)// code to be executed //
Must have static modifier in their declaration // Return type can be, float String or user defined data type Memory Allocation-They are stored in the Permanent
Generation space of heap as they are associated with the class in which they reside not to the objects of that class But their local variables and the passed argument(s)
to them are stored in the stack Since they belong to the class, so they can be called to without creating the object of the class Important Points: Static method(s) are
associated with the class in which they reside[15:32, 15/03/2023]ClassName methodName(args),They are designed with the aim to be shared among all objectscreated
from the same class Static methods can not be overridden, since they are resolved usingstatic binding by the compiler at compile_time However, we canhave the
same name methods declared static in both super-class and sub-class, but it will be called Method Hiding as the derived class method will hide the base class method
Java main method is always static Java main() method is always static, which is used in Java database connectivity whichOracle, MS Access, Mysql and SQL server
database Architecture of JDBC:1 Application-It is a Java applet or a servlet which communicates with a data source 2 The JDBC API-The JDBC APIallows Java programs
to execute SQL statements and retrieve results Some of the important classes and interfaces defined in JDBC API are as follows:Driver-ManagerDriverConnection
StatementPrepared StatementCallable StatementResult SetSQL data 3 Driver Manager-It plays an important role in the JDBC architecture It uses some database-specific
drivers to effectively connect enterprise applications to databases 4 JDBC Drivers: To communicate with a data source through JDBC,you need a JDBC driver that
intelligently communicates with the respective data source Q 30 What is the Difference between Compile Time Polymorphismand Run-time Polymorphism in Java ?
Ans If we perform (achieve) method overriding and methodoverloading using instance methods, it is run-time (dynamic) polymorphism In dynamic polymorphism the
binding between the method call the method body happens at the time of execution and this binding is known as dynamic binding or late binding [15:33,
15/03/2023]xample:ass Super-class (public static void sample(){ System out println(" Method of the super class");ublic class run-timePolymorphism extends Super Class
(public static void sample() { System out println("Method of the sub-class");public static void main(String args[])){ Super-class obj 1 = new Run-timePolymorphism(); Run-
timePolymorphism obj2= new Run-timePolymorphism(): obj2 sample();obj 1 sample():Output:Method of the super class Method of the sub-classIf we perform (achieve)
method overriding and method overloading ng static, private, final methods, it is compile time (static) polymorphism In static polymorphism the binding between the
method call the method dy happens at the time of compilation and this binding is known as staticnding or early binding Example:class Super-class public static void
sample(){System out println("Method of the super class");public class Sub-Class extends Super-class {public static void sample(){System out println("Method of the sub-
class");public static void main(String args[])[Super-class sample(); Sub-Class sample();Output:Method of the super class Method of the sub-class[15:34, 15/03/2023]Q 31
Explain the Life Cycle of Multithreading (2018)Or, Give the Short Summary of Multithreading Concept Ans Many applications can run on the same computer at the
same time Each instance in the running condition, is known as process Each process can have one or more threads A thread is a sequence of code, this code is often
responsible for one aspect of the program, or one task a program has been given For instance, a program doing a complex long calculation split into two threads, one to
keep a user interface responsive and one (or more) to progress through the lengthy calculation mayJava has a built in support for multithreading programming A
multithreading is a specialized form of multitasking Multitasking threads require less overhead than multitasking processes A thread has various stages during its life
cycle For example, a thread is born, started, runs, and then dies Given below diagram contains various stages during it's life cycle:NewProgram starts thredUnlock
signalsignalallWaitingAwait lockRunnableThread completes interval expires or when the event it is waiting for occurs A runnable thread enters the terminated state
when itcompletes its task or otherwise terminates 0 32 What do you Mean by Exception Classes? Ans The exception classes can be explained as well seeing the
exception hierarchy structure :Objectjava lang Throwablejava lang Errorjava lang Exceptionjava lang Runtime ExceptionThe java lang package defines several classes and
exceptions Some of these classes are not checked while some other classes are checked ExceptionsDescription Arithmetic errors suchas a divide by zeroChecked
UncheckedArithmeticExceptionYESArray Index Out of Bounds ExceptionClass Not Found ExceptionArrays index is not within array lengthYESRelated Class not
foundYES10 ExceptionInput Ouput field not found Illegal argument whenYESlegal Argument Exceptioncalling a method One thread has been interrupted by
anotherthreadInterrupted ExceptionNonexistent methodNo Such Method Exception Null Pointer ExceptionInvalid use of null referenceNumberFormat Exception Invalid
string for conversion to number YESYESYESYESYESQ 33 What is an Array ? Define its Type and also Show the Ans Arrays: When you need to store same 'type' of data
that can be Declaration of an Array in Java [15:35, 15/03/2023]logically grouped together, then we can go for Java array For imagine if we have to store the list of
countries in individual Java variables and manipulate them, we required more than hundred variables to manage Array is the most important thing in any programming
language By definition, array is the static memory allocation It allocates the memory for the same data type in sequence It contains multiple values of It also store the
values in memory at the fixed size Multiple types of are used in any programming language such as: one-dimensional, two-dimensional or can say multi-dimensional
same types array exampleDeclaration of an array: int num[]; or int num= new int[2]:Sometimes user declares an array and it's size simultaneously We r or may not be
define the size in the declaration time, such as: int num] = (50,20,45,82,25,63); mayIn this program we will see how to declare and implementation This program
illustrates that the array working way This program takes the numbers present in the num[] array in unordered list and prints numbers in ascending order In this
program the sort() function of the java util package is using to sort all the numbers present in the num[] array The Arrays sort() automatically sorts the list of number in
ascending order by default This function held the argument which is the array name num Here is the code of the program :import java util *; public class array{ public
static void main(String[] args) { int num[] = { 50, 20, 45, 82, 25, 63):int 1 = num length;int i, j, t;4 System out print("Given number: "); for (i=0; i<; i++)System out print("
"+num[i]);System out println("\n"); System out print ("Ascending order number: ");Arrays sort(num);light(i=0; i<1; i++){ System out print(" + num[i]);Output of the
Program:C:\chandan>javac array java C:\chandan java arrayGiven number: 50 20 45 82 25 63 Ascending order number: 20 25 45 50 63 82 [15:35, 15/03/2023]Q 34
What is the Difference Between Break and Continue Keyword in Java ?Ans The Break Keyword: The break keyword is used to stop theentire loop The break keyword
must be used inside any loop or a switchstatement The break keyword will stop the execution of the innermost loop and start executing the next line of code after the
block Syntax: The syntax of a break is a single statement inside any loop: break;Example:public class Test { public static void main (String args[]) { int numbers = (10, 20,
30, 40, 50];for(int x: numbers) {if (x=30) (break;1 System out print(x) System out print("w"))):This would produce following result:1020The Continue Keyword: The
continue keyword can be used in any of the loop control structures It causes the loop to immediately jump to the next iteration of the loop In a for loop, the continue
keyword causes flow of control to immediately jump to the update statement In a while loop or dp/while loop, flow of control immediately jumps to the Boolean
expressionSyntax:The syntax of a continue is a single statement inside any loop:continue:Example:public class Test Tpublic static void main(String args[]) { int [] numbers
(10, 20, 30, 40, 50); for(int x: numbers) |if (x == 30){ continue;System out print( x ) System out print("");[15:36, 15/03/2023]Q 35 What is Switch Statement? Explain
with an Example in JavaProgramming Ans The Switch Statement: A switch statement allows a variable be tested for equality against a list of values Each value is called
a case and the variable being switched on is checked for each case Syntax: The syntax of enhanced for loop is:toswitch (expression) I case value:// Statements break;
//optional case value: //Statements break; //optional//You can have any number of case statements;default: //Optional //StatemetsThe following rules apply to a switch
statement: The variable used in a snatch statement can only be a byte, short, int, or char You can have any number of case statements within a switch Eachcase is
followed by the value to be compared to and a colon The value for a case must be the same data type as the variable inthe switch and it must be a constant or a literal
When the variable being switched on is equal to a case, thestatements following that case will execute until a break statement isreached When a break statement is
reached, the switch terminates and the flow of control jumps to the next line following the switchstatement Not every case needs to contain a break If no break
appears, theflow of control will fall through to subsequent cases until a break isreached A switch statement can have an optional default case, which must appear at the
end of the switch The default case can be used for performing a task when none of the cases is true No break is needed in the default case [15:36, 15/03/2023]Example
public classpublic static void main (String args[] //char grade = args[0] charAt (0):char grade = 'C switch(grade){ case 'A':System out println("Excellent!"); break;case
'B':case 'C':System out println ("Well done"): break;case 'D':System out println("You passed"):case 'F: System out println("Better try again");break;default:System out
println ("Invalid grade"); System out println ("Your grade is + grade):Q36 Explain in Detail the Primitive Data Types Operation?Ans Primitive Data Types: There are
eight primitive data types pported by Java Primitive data types are predefined by the language and amed by a key word Let us now look into detail about the eight
primitivedata types byte:Byte data type is a 8-bit signed two's complement integer Minimum value is -128 (-2^7) Maximum value is 127 (inclusive) (27-1) Default value
is 0 Byte data type is used to save space in large arrays, mainly in placeof integers, since a byte is four times smaller than an int • Example: byte a = 100, byte b = -50
Short data type is a 16-bit signed two's complement integer short:• Minimum value is -32,768 (-2^15) • Maximum value is 32,767 (inclusive) (2^15 -1) • Short data type
can also be used to save memory as byte data type A short is 2 times smaller than an intDefault value is 0 • Example: short s = 10000, short r=-20000 [15:36,
15/03/2023]int : Int data type is a 32-bit signed two's complement integer • Minimum value is - 2,147,483,648 (-2^31) • Maximum value is 2,147,483,647(inclusive)
(2^31 -1) Int is generally used as the default data type for integral vunless Double data type is a double-precision 64-bit IEEE 754 floating point This data type is
generally used as the default data type for decimal values, generally the default choice Double data type should never be used for precise values such ascurrency •
Default value is 0 0d • Example: double dl = 123 4 boolean : Boolean data type represents one bit of information There are only two possible values: true and false
This data type is used for simple flags that track truefale conditions Default value is false • Example: boolean one = true char: Char data type is a single 16-bit Unicode
character • Minimum value is u0000' (or 0) • Maximum value is \uffff (or 65,535 inclusive) • Char data type is used to store any character • Example: char letterA = 'A'
[15:37, 15/03/2023]0 Q37 Explain in Detail the Reference Data Types Operation 145AnsReference Data TypesArrayClassInterfacealues-1) EntIn Java a reference data
type is a variable that can contain the reference or an address of dynamically created object These types of data type are not predefined like primitive data type The
reference data types are arrays classes and interfaces that are made and handle according to a programmer program, which can hold the three kinds of values as:ina
Java • array typeclass type// Points to an array instance // Points to an object or a class instance interface type // Points to an object and a method, which
isimplemented Il to the corresponding class →Interface Type: Java provides an another kind of reference data type or a mechanism to support multiple inheritance
feature called an interface The name of an interface can be used to specify the type of a reference A value is not allowed to be assign to a variable declared usingan
interface type until the object implements the specified interface When a class declaration implements an interface, that class inherits all of the variables and methods
declared in that interface So the implementations for all of the methods declared in the interface must be provided by that class For example, Java provides an
interface called ActionListener whose method named actionPerformed() is used to handle the different kind of event Java also provides a class called Thread that
implements Runnable interface Thus the following assignment can be allowed:Runnable r;R = new Thread () Q 38 What are the Different Loops in Java? Explain its
Syntax with an Example Ans Java has very flexible three looping mechanisms You can use oneof the following three loops: while Loop do while Loop for
Loop The while Loop: A while loop is a control structure that allows you to repeat a task a certain number of times [15:37, 15/03/2023]Syntax: while (Boolean
expression)//StatementsWhen executing, if the Boolean_expression result is true then the ctions inside the loop will be be executed This will continue as long as the
result is true Here key point of the while loop is that the loop might not ever expression When the expression is tested and the result is false, the loopbody will be
skipped and the first statement after the while loop will beexecuted Example: public class Test {public static void main(String args[]) {int x = 10; while (x<20) ( System out
print ("value of x : " + x):x ++:System out print ("\n");This would produce following result:value of x: 10 value of x 11value of x 12value of x 13value of x: 14value of x
15value of x 16 value of x 17value of x 18value of x 19 The do while Loop: A do while loop is similar to a while loop, except that a do while loop is guaranteed to
execute at least one time Syntax: The syntax of a do while loop is:do//Statements } while(Boolean expression):Notice that the Boolean expression appears at the end
of the loop, so the statements in the loop execute once before the Boolean is tested If the Boolean expression is true, the flow of control jumps back up to do and the
statements in the loop execute again This process repeats until the Boolean expression is false

You might also like