[go: up one dir, main page]

0% found this document useful (0 votes)
1 views2 pages

JAVA 4th Sem Tukli (AR)

The document provides an overview of key concepts in Java, including inheritance, polymorphism, method overloading, access modifiers, and exception handling. It distinguishes between object-oriented programming and procedural programming, outlines the features of Java, and explains the structure and purpose of packages and classes. Additionally, it covers the lifecycle of threads and the use of operators in Java.

Uploaded by

disha4tr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views2 pages

JAVA 4th Sem Tukli (AR)

The document provides an overview of key concepts in Java, including inheritance, polymorphism, method overloading, access modifiers, and exception handling. It distinguishes between object-oriented programming and procedural programming, outlines the features of Java, and explains the structure and purpose of packages and classes. Additionally, it covers the lifecycle of threads and the use of operators in Java.

Uploaded by

disha4tr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

1.What is inheritance in Java? 5.What is Polymorphism in Java? 8.

Difference between object oriented programming and


Ans: Inheritance is a fundamental concept in object-oriented Ans: Polymorphism in Java is a fundamental object-oriented procedural programming
programming (OOP) languages like Java. It allows a class to programming concept that allows objects of different classes Procedural Oriented Object-Oriented
inherit to be treated as objects of a common superclass or interface. Programming Programming
properties and behaviors from another class, known as the It provides a way to perform different actions based on the In procedural programming, In object-oriented
superclass or parent class. The class that inherits from the actual type of an object at runtime. the program is divided into programming, the program
superclass There are two main types of polymorphism in Java: small parts called functions. is divided into small parts
is called the subclass or child class. 1. Compile-time Polymorphism (Static Polymorphism) called objects.
In Java, inheritance is implemented using the extends 2. Runtime Polymorphism (Dynamic Polymorphism)
keyword. When a subclass extends a superclass, it gains Here's an example that demonstrates polymorphism in Java: Procedural programming Object-oriented
access to all the class Animal { follows a top-down approach. programming follows
public and protected members (fields and methods) of the public void makeSound() { a bottom-up approach.
superclass. This means that the subclass can reuse and System.out.println("Animal makes a sound"); There is no access specifier in Object-oriented
extend the } procedural programming. programming has access
functionality of the superclass without having to rewrite the } specifiers like private, public,
code. class Dog extends Animal { protected, etc.
The syntax for creating a subclass that inherits from a @Override Adding new data and Adding new data and
superclass is as follows: public void makeSound() { functions is not easy. function is easy.
class Subclass extends Superclass { System.out.println("Dog barks"); Procedural programming does Object-oriented
// subclass-specific members and methods } not have any proper way of programming provides data
} } hiding data so it is less secure. hiding so it is more secure.
class Cat extends Animal {
2. . What is method overloading in Java? @Override In procedural programming, Overloading is possible in
Ans: Method overloading is a feature in Java that allows public void makeSound() { overloading is not possible. object-oriented
multiple methods in the same class to have the same name System.out.println("Cat meows"); programming.
but with } Examples: C, FORTRAN, Pascal, Examples: C++, Java, Python,
different parameters. It provides flexibility and convenience } Basic, etc. C#, etc.
by enabling different ways to invoke a method based on the public class PolymorphismExample {
types public static void main(String[] args) {
or number of arguments. Animal animal1 = new Dog(); 9. What is Abstract Class
Here's an example to illustrate method overloading: Animal animal2 = new Cat(); The abstract class in Java cannot be instantiated (we cannot
public class Calculator { animal1.makeSound(); // Output: Dog barks create objects of abstract classes). We use the abstract
public int add(int a, int b) { animal2.makeSound(); // Output: Cat meows keyword to declare an abstract class.
return a + b; } For example,
} } // create an abstract class
public double add(double a, double b) { 6.Write down about constructors in Java. abstract class Language {
return a + b; Ans: In Java, a constructor is a special method that is used to // fields and methods
} initialize objects of a class. It is called automatically when an }
public int add(int a, int b, int c) { object is created using the new keyword. Constructors have ...
return a + b + c; the same name as the class and do not have a return type, // try to create an object Language
} not even void. They are primarily used to set initial values to // throws an error
public static void main(String[] args) { the instance variables of an object. Language obj = new Language();
Calculator calculator = new Calculator(); Here's an example that demonstrates the use of constructors
int sum1 = calculator.add(2, 3); // Invokes add(int a, int b) in Java: 10.What is Daemon Thread in Java
double sum2 = calculator.add(2.5, 3.7); // Invokes add(double public class Person { Daemon thread in Java is a service provider thread that
a, double b) private String name; provides services to the user thread. Its life depend on the
int sum3 = calculator.add(2, 3, 5); // Invokes add(int a, int b, private int age; mercy of user threads i.e. when all the user threads dies, JVM
int c) // Parameterized constructor terminates this thread automatically.
System.out.println("Sum1: " + sum1); // Output: Sum1: 5 public Person(String name, int age) { Ex:
System.out.println("Sum2: " + sum2); // Output: Sum2: 6.2 this.name = name; class adminThread extends Thread {
System.out.println("Sum3: " + sum3); // Output: Sum3: 10 this.age = age; adminThread() {
} } setDaemon(false);
} // Default constructor (automatically provided if not defined }
explicitly) public void run() {
3.Write down about wrapper classes in Java. public Person() { boolean d = isDaemon();
Ans: In Java, a wrapper class is a class that encapsulates a this.name = "Unknown"; System.out.println("daemon = " + d);
primitive data type within an object. It allows primitive data this.age = 0; }
types to be treated as objects. The wrapper classes provide a } }
way to convert primitive types into objects and vice versa, as public void displayInfo() {
well as provide additional utility methods to work with these System.out.println("Name: " + name + ", Age: " + age); public class Tester {
values. the common wrapper classes in Java- } public static void main(String[] args) throws Exception {
Boolean,Byte,Short,Integer,Long,Float,Double,Character public static void main(String[] args) { Thread thread = new adminThread();
// Creating objects using different constructors System.out.println("thread = " + thread.currentThread());
Here's an example of using a wrapper class: Person person1 = new Person("John", 25); thread.setDaemon(false);
Integer number = new Integer(10); // creating an instance of Person person2 = new Person(); thread.start();
Integer wrapper class // Calling instance method to display information }
int value = number.intValue(); // converting Integer object to person1.displayInfo(); }
int primitive type person2.displayInfo();
System.out.println("Value: " + value); // Output: Value: 10 } 11. What is applet in java.
Integer newValue = value + 5; // autoboxing - converting int } An applet is a Java program that runs in a Web browser. An
to Integer object 7.Write a code to create a package and then use it in a applet can be a fully functional Java application because it has
System.out.println("New Value: " + newValue); // Output: program. the entire Java API at its disposal.
New Value: 15 Ans:- First, let's create a package named Ex:
com.example.mypackage: Following is a simple applet named HelloWorldApplet.java −
4. . Write down about access modifiers in Java. Create a folder named com in your desired location.
Ans: Access modifiers in Java are keywords used to specify Inside the com folder, create a folder named example. import java.applet.*;
the accessibility or visibility of classes, methods, variables, or Inside the example folder, create a folder named mypackage. import java.awt.*;
constructors within a Java program. They determine whether So, the package structure should be:
other classes or objects can access a particular element or com.example.mypackage. public class HelloWorldApplet extends Applet {
not. Next, let's create a class inside the mypackage: public void paint (Graphics g) {
Java provides four types of access modifiers: Create a file named MyClass.java inside the mypackage folder. g.drawString ("Hello World", 25, 50);
1. Public: The public access modifier is the most permissive Add the following code to MyClass.java: }
and allows unrestricted access from anywhere within the }
program. Public members can be accessed by other classes, package com.example.mypackage;
objects, or even outside the package. public class MyClass { 12. what is package in java
2. Protected: The protected access modifier allows access public void displayMessage() { A Java package is a collection of similar types of sub-
from the same package and subclasses (both within and System.out.println("Hello from my package!"); packages, interfaces, and classes. In Java, there are two types
outside the package). Protected members cannot be accessed } of packages: built-in packages and user-defined packages. The
by unrelated classes outside the package. } package keyword is used in Java to create Java packages.
3. Default (No Modifier): If no access modifier is specified, it is let's create a separate program to use the package: 17. what is J D K
considered the default access modifier. The default access import com.example.mypackage.MyClass; JDK is an acronym for Java Development Kit. The Java
allows access within the same package but not from public class MainProgram { Development Kit (JDK) is a software development
subclasses or classes in different packages. public static void main(String[] args) { environment which is used to develop java applications and
4. Private: The private access modifier is the most restrictive. MyClass myObject = new MyClass(); applets. It physically exists. It contains JRE + development
It restricts access to only the class where the member is myObject.displayMessage(); tools.
declared. Private members cannot be accessed by any other }
class, including subclasses. }
15. Explain how exception handling is achieved in Java 20. Write a line of code to create an object of a class called 24. Explain different types of operator in Java?
1.The try block is used to enclose the code that may throw an Myclass. 1.Java Arithmetic Operators:
exception. Arithmetic operators are used to perform arithmetic
2.If an exception occurs within the try block, the control public class MyClass { operations on variables and data. For example,
immediately jumps to the corresponding catch block. // Class members, constructors, and methods can be a + b;
3.The catch block specifies the type of exception it can defined here 2. Java Assignment Operators
handle, and it contains the code to handle the exception. Assignment operators are used in Java to assign values to
Multiple catch blocks can be used to handle different types of public static void main(String[] args) { variables. For example,
exceptions. // Creating an object of MyClass int age;
4.After executing the catch block, the program continues with MyClass myObject = new MyClass(); age = 5;
the code that follows the try-catch block. 3. Java Relational Operators
Example: // Accessing methods or members of the object Relational operators are used to check the relationship
try { myObject.someMethod(); between two operands. For example,
// Code that may throw an exception } // check if a is less than b
int result = divide(10, 0); // Example: Dividing by zero a < b;
System.out.println("Result: " + result); // This line won't be public void someMethod() { 4. Java Logical Operators
executed // Method implementation Logical operators are used to check whether an expression
} catch (ArithmeticException ex) { System.out.println("Hello from MyClass!"); is true or false. They are used in decision making.
// Handling the ArithmeticException } They are- && (Logical AND), || (Logical OR), ! (Logical
System.out.println("Error: " + ex.getMessage()); } NOT).
} 21. Features of Java ? 5. Java Unary Operators
Following are the notable features of Java: Unary operators are used with only one operand. For
16. 1.Object Oriented: example, ++ is a unary operator that increases the value of a
Class Object In Java, everything is an Object. Java can be easily extended variable by 1. That is, ++5 will return 6.
Class is used as a An object is an instance of a since it is based on the Object model. 6. Java Bitwise Operators
template for declaring class. 2.Platform Independent: Bitwise operators in Java are used to perform operations on
and Unlike many other programming languages including C and individual bits. For example,
creating the C++, when Java is compiled, it is not compiled into platform Bitwise complement Operation of 35
objects. specific machine, rather into platform-independent byte 35 = 00100011 (In Binary)
When a class is Objects are allocated memory code. This byte code is distributed over the web and ~ 00100011
created, no memory space whenever they are interpreted by the Virtual Machine (JVM) on whichever _____
is allocated. created. platform it is being run on. 11011100 = 220 (In decimal)
The class has to be An object is created many 3.Simple: Here, ~ is a bitwise operator. It inverts the value of each bit
declared first and times as per requirement. Java is designed to be easy to learn. If you understand the (0 to 1 and 1 to 0).
only once. basic concept of OOP Java, it would be easy to master. 7.Shift Operator: The shift operator is used to shift the bits of
A class can not be Objects can be manipulated. 4.Secure: a number left or right by multiplying or dividing the numbers.
manipulated as they With Java's secure feature it enables to develop virus-free, They are- << (Left Shift), >> (Right Shift).
are not tamper-free systems. Authentication techniques are based on 8.Relational Operator: Relational operator compares two
available in the public-key encryption. numbers and returns a boolean value. This operator is used
memory.
5.Architecture-neutral: to define a relation or test between two operands.
A class is a logical An object is a physical entity.
Java compiler generates an architecture-neutral object file 25.Break statement in java?
entity.
format, which makes the compiled code executable on many Break Statement is a loop control statement that is used to
It is declared with the It is created with a class name
processors, with the presence of Java runtime system. terminate the loop. As soon as the break statement is
class keyword in C++ and
with the new keywords in encountered from within a loop, the loop iterations stop
Java. 22.Explain threads life cycle. there, and control returns from the loop immediately to the
A thread goes through various stages in its lifecycle. For first statement after the loop.
28.Rules for package in java? example, a thread is born, started, runs, and then dies. The Example:
Rules of a Java Package: following diagram shows the complete life cycle of a thread. public class BreakExample {
1.Package name and directory name should be the same. public static void main(String[] args) {
2.A Java package may contain Sub-Packages or sub-directories //using for loop
with unique names. for(int i=1;i<=10;i++){
3.A Java package may contain any number of class files. if(i==5){
4.The package declaration statement should be the very first //breaking the loop
statement in a Java file. break;
5.The package import statement can come after the package }
declaration statement and before any Class declarations. System.out.println(i);
6.The same package-name or class-name can be reused in }
some other packages but not within the same package. }
Following are the stages of the life cycle − }
1.New − A new thread begins its life cycle in the new state. It 26. Continue statement in Java?
18. difference between init() and start() methods in java
remains in this state until the program starts the thread. It is The continue statement is used in loop control structure
1.init() is used in the context of servlet initialization and is
also referred to as a born thread. when you need to jump to the next iteration of the loop
called by the servlet container, while start() is used in the
2. Runnable − After a newly born thread is started, the thread immediately. It can be used with for loop or while loop.
context of multithreading and is called to start the execution
becomes runnable. A thread in this state is considered to be The Java continue statement is used to continue the loop. It
of a new thread.
executing its task. continues the current flow of the program and skips the
2.init() is called once during servlet initialization, whereas
3. Waiting − Sometimes, a thread transitions to the waiting remaining code at the specified condition. In case of an inner
start() is called explicitly to begin the execution of a new
state while the thread waits for another thread to perform a loop, it continues the inner loop only.
thread.
task. Thread transitions back to the runnable state only when Example:
3.init() is specific to servlets and used for setup and
another thread signals the waiting thread to continue public class ContinueExample {
initialization tasks, while start() is a general method in the
executing. public static void main(String[] args) {
Runnable interface used for concurrent execution in
4.Timed Waiting − A runnable thread can enter the timed //for loop
multithreaded programming.
waiting state for a specified interval of time. A thread in this for(int i=1;i<=10;i++){
state transitions back to the runnable state when that time if(i==5){
19.How to swap two numbers without using temp variable
interval expires or when the event it is waiting for occurs. //using continue statement
using java.
5. Terminated (Dead) − A runnable thread enters the continue;//it will skip the rest statement
import java.util.*;
terminated state when it completes its task or otherwise }
class Swap
terminates. System.out.println(i);
{
public static void main(String a[]) }
23. What is encapsulation in java? }
{
Encapsulation in Java is a mechanism of wrapping the data }
System.out.println("Enter the value of x and y");
(variables) and code acting on the data (methods) together as 27. What is control statement in java?
Scanner sc = new Scanner(System.in);
a single unit. In encapsulation, the variables of a class will be Java compiler executes the code from top to bottom. The
/*Define variables*/
hidden from other classes, and can be accessed only through statements in the code are executed according to the order in
int x = sc.nextInt();
the methods of their current class. Therefore, it is also known which they appear. However, Java provides statements that
int y = sc.nextInt();
as data hiding. can be used to control the flow of Java code. Such statements
System.out.println("before swapping numbers: "+x +" "+
y); are called control flow statements. It is one of the
28.Rules for package in java? fundamental features of Java, which provides a smooth flow
/*Swapping*/
1.Package name and directory name should be the same. of program.
x = x + y;
2.A Java package may contain Sub-Packages or sub-directories
y = x - y;
with unique names.
x = x - y;
3.A Java package may contain any number of class files.
System.out.println("After swapping: "+x +" " + y);
4.The package declaration statement should be the very first
}
statement in a Java file.
}
5.The package import statement can come after the package
declaration statement and before any Class declarations.
6.The same package-name or class-name can be reused in
some other packages but not within the same package.

You might also like