Java Solution for end Sem _Oct_Nov_2022-3
Java Solution for end Sem _Oct_Nov_2022-3
When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.
public class A {
public void display() {
System.out.println("I am a method from class A");
}
}
class Animal{
void eat(){System.out.println("eating...");}
class TestInheritance{
d.bark();
d.eat();
}}
Output:
barking...
eating...
b) Write a method called
String Delete(String str, int m)
That returns the input str with mth element removed. [8 Marks]
class Main {
// Driver Code
public static void main(String args[])
{
// Given String str
String str = "GeeksForGeeks";
//int m=str.length()-1;
int m=5;
Output: GeeksorGeek
OR
public class Demo {
public static void main(String[] args) {
String str = "The Haunting of Hill House!";
System.out.println("String: "+str);
// removing character at position 7
int pos = 7;
String res = str.substring(0, pos) + str.substring(pos + 1);
System.out.println("String after removing a character: "+res);
}
}
c) What is an array? How to declare an array in java? compare C array with java array. [5]
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value. To declare an array, define the variable type with square brackets:
String[] cars; We have now declared a variable that holds an array of strings.
OR
An array is a container object that holds a fixed number of values of a single type. The length
of an array is established when the array is created. After creation, its length is fixed.
OR
Array in java is a group of like-typed variables referred to by a common name. Arrays in Java
work differently than they do in C/C++. Following are some important points about Java
arrays.
Syntax:
datatype var-name[];
OR
datatype[] var-name;
OR
datatype []var-name;
You must be very careful when indexing an array in C. In Java, you immediately get an
ArrayIndexOutOfBoundsException when you try to access an illegal element in an array.
Another issue is that C arrays do not have a length property, unlike in Java.
Polymorphism in Java has two types: Runtime polymorphism (dynamic binding) and Compile
time polymorphism (static binding). Method overriding is an example of dynamic
polymorphism, while method overloading is an example of static polymorphism.
[4 Marks]
Static Polymorphism
At compile time, Java knows which method to invoke by checking the method signatures. So,
this is called compile time polymorphism or static binding. The concept will be clear from the
following example:
class DemoOverload{
public int add(int x, int y){ //method 1
return x+y;
}
public int add(int x, int y, int z){ //method 2
return x+y+z;
}
class Test{
public static void main(String[] args){
DemoOverload demo=new DemoOverload();
System.out.println(demo.add(2,3)); //method 1 called
System.out.println(demo.add(2,3,4)); //method 2 called
System.out.println(demo.add(2,3.4)); //method 4 called
System.out.println(demo.add(2.5,3)); //method 3 called
}
}
[4 Marks]
Dynamic Polymorphism
Suppose a subclass overrides a particular method of the superclass. The polymorphic nature of
Java will use the overriding method. Let’s say we create an object of the subclass and assign it to
the superclass reference. Now, if we call the overridden method on the superclass reference then
the subclass version of the method will be called.
class Vehicle{
public void move(){
System.out.println(“Vehicles can move!!”);
}
}
Concatenation is the process of combining two or more strings to form a new string by
subsequently appending the next string to the end of the previous strings.
In Java, two strings can be concatenated by using the + or += operator, or through the concat()
method, defined in the java.lang.String class.
This section will discuss how to perform string concatenation using both of these methods.
Example 1
The program below demonstrates how to concatenate two strings using the + operator in Java.
class HelloWorld {
public static void main( String args[] ) {
String first = "Hello";
String second = "World";
System.out.println(third);
Note: You can also directly concatenate the strings within the println method itself as
System.out.println(first + second); or System.out.println(first.concat(second));.
//Initialize array
int [] arr = new int [] {5, 2, 8, 7, 1};
int temp = 0;
System.out.println();
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in
the Java interface, not method bodies. It is used to 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.
There are mainly three reasons to use interfaces. They are given below.
interface printable{
void print();
obj.print();
Output: Hello
interface Drawable{
void draw();
class TestInterface1{
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
d.draw();
}}
float rateOfInterest();
class TestInterface2{
System.out.println("ROI: "+b.rateOfInterest());
}}
Java provides a large number of classes grouped into different packages based on a particular
functionality.
Examples:
java.lang: It contains classes for primitive types, strings, math functions, threads, and
exceptions.
java.util: It contains classes such as vectors, hash tables, dates, Calendars, etc.
java.awt: Classes for implementing Graphical User Interface – windows, buttons, menus, etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations ) providing access protection and namespace management.
Programmers can define their own packages to bundle groups of classes/interfaces, etc. It is a
good practice to group related classes implemented by you so that a programmer can easily
determine that the classes, interfaces, enumerations, and annotations are related.
● The String class which is present in java.lang package. To use the String class we don’t
need to write an import statement, because java by default adds all the classes of the
java.lang package in all the programs.
● We use the Properties class which is present in java. util package. To use this class we
have to write an import statement because this is in a different package. import
java.util.Properties;
● We use the File class which is present in the java.io package. To use file class we have to
write an import statement. import java.io.File;
There are two ways to access a different package class in our program-
● First is a fully qualified name as we see in the above statements. import java.io.File;
● Second is giving the super package name and including all the sub packages and
subclasses import java.io.*;
java.util.Vector
An interface in Java is similar to class but it contains only abstract methods and fields which are
final and static.
Since Java8 static methods and default methods are introduced in interfaces.
Default methods are methods that can have a body. The most important use of default methods in
interfaces is to provide additional functionality to a given type without breaking down the implementing
classes.
Default Methods - Unlike other abstract methods these methods can have a default
implementation. If you have a default method in an interface, it is not mandatory to override
(provide body) it in the classes that are already implementing this interface.
In short, you can access the default methods of an interface using the objects of the
implementing classes.
void cleanVehicle();
Example
interface MyInterface{
public static int num = 100;
public default void display() {
System.out.println("display method of MyInterface");
}
}
public class InterfaceExample implements MyInterface{
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display();
}
}
Output
Definition Applications are just like a Java Applets are small Java programs that
program that can be executed are designed to be included with the
independently without using HTML web document. They require a
the web browser. Java-enabled web browser for
execution.
main () The application program The applet does not require the main()
method requires a main() method for method for its execution, instead init()
its execution. method is required.
Compilation The “javac” command is used Applet programs are compiled with
to compile application the “javac” command and run using
programs, which are then either the “appletviewer” command or
executed using the “java” the web browser.
command.
File access Java application programs Applets don’t have local disk and
have full access to the local file network access.
system and network.
Access level Applications can access all Applets can only access
kinds of resources available on browser-specific services. They don’t
the system. have access to the local system.
Installation First and foremost, the The Java applet does not need to be
installation of a Java installed beforehand.
application on the local
computer is required.
Execution Applications can execute the Applets cannot execute programs from
programs from the local
system. the local machine.
Run It cannot run on its own; it It cannot start on its own, but it can be
needs JRE to execute. executed using a Java-enabled web
browser.
Read and It supports the reading and It does not support the reading and
Write writing of files on the local writing of files on the local computer.
Operation computer.
Q 6) a)Explain the concept of thread priority with the help of suitable examples. [9]
Concept of thread priority along with syntax of setPriority and getPriority method[04 marks]
Each thread has a priority. Priorities are represented by a number between 1 and 10. In most
cases, the thread scheduler schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses. Note that not only JVM a Java programmer can also assign the
priorities of a thread explicitly in a Java program.
Thread priorities are represented by a number from 1 to 10 that specifies the relative priority of
one thread to another. The thread with the highest priority is selected by the scheduler to be
executed first.
The default priority of a thread is 5. Thread class in Java also provides several priority constants to
define the priority of a thread. These are:
1. MIN_PRIORITY = 1
2. NORM_PRIORITY = 5
3. MAX_PRIORTY = 10
These constants are public, final, and static members of the Thread class.
public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority of
the given thread.
FileName: ThreadPriorityExample.java
import java.lang.*;
// Method 1
}
// the main method
// 1st Thread
// 2nd Thread
// 3rd Thread
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
// 6
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
// 3
// 9
// Main thread
Thread.currentThread().setPriority(10);
Output:
Priority of the thread th1 is : 5
Priority of the thread th2 is : 5
Priority of the thread th2 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priority of the main thread is : 10
Q 6) b)Write a java code using buffer Reader class to read names from users. [5]
import java.io.IOException;
import java.io.InputStreamReader;
System.out.println(name);
OR
package com.javatpoint;
import java.io.*;
String name=br.readLine();
System.out.println("Welcome "+name);
}
Q 6) c) Explain syntax of try and catch block . [4]
2. One or more catch clauses matching a specific exception will handle the occurred
exception.
OR
try
catch(ArithmeticException e)
System.out.println(e);
}
Q 7) a) Explain the Graphics class in java. List out and explain any three drawing methods
from graphics class. [9]
• A Graphics object manages a graphics context and draws pixels on the screen that represent
text and other graphical objects (e.g., lines, ellipses, rectangles and other polygons).
• Graphics objects contain methods for drawing, font manipulation, color manipulation and
the like.
• Main feature in java is creating a graphical interface.
• Graphics in any language gives a wonderful look and feel to the users.
• Two packages that are mainly used to draw graphics.
○ Applet package
○ awt package
Listing out and Explanation of any three drawing methods from graphics class [2 Marks each]
• Draws the text given by the specified string, using this graphics context's current font and
color.
• abstract void drawLine(int x1, int y1, int x2, int y2)
• Draws a line, using the current color, between the points (x1, y1)
and (x2, y2) in this graphics context's coordinate system.
• abstract void drawOval(int x, int y, int width, int height)
• Draws the outline of an oval.
• drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)
• Draws the outline of a circular or elliptical arc covering the specified rectangle.
• drawRect(int x, int y, int width, int height)
• Draws the outline of the specified rectangle.
Q 7) b) Create an application to create window in java deriving from the Frame class to
display message “Welcome to World of Java”. [8]
import java.awt.*;
public class Testawt
{
Testawt()
{
Frame fm=new Frame(); //Creating a frame
Label lb = new Label("Welcome to world of Java"); //Creating a label
fm.add(lb); //adding label to the frame
fm.setSize(300, 300); //setting frame size.
fm.setVisible(true); //set frame visibilty true
}
public static void main(String args[])
{
Testawt ta = new Testawt();
}
}
Hierarchy Of AWT
The hierarchy of Java AWT classes are given below, all the classes are available in java.awt
package.
Component class
Component class is at the top of AWT hierarchy. It is an abstract class that encapsulates all the
attributes of a visual component. A component object is responsible for remembering the current
foreground and background colors and the currently selected text font.
Container
Container is a component in AWT that contains another component like button, text field, tables
etc. Container is a subclass of component class. Container class keeps track of components that
are added to another component.
Panel
Panel class is a concrete subclass of Container. Panel does not contain title bar, menu bar or
border. It is a container that is used for holding components.
Window class
Window class creates a top level window. Window does not have borders and a menubar.
Frame
Frame is a subclass of Window and has resizing canvas. It is a container that contains several
different components like button, title bar, textfield, label etc. In Java, most of the AWT
applications are created using Frame window. Frame class has two different constructors,
package practical;
import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception
{
FileReader fr=new FileReader
("C:\\Users\\Lenovo\\Desktop\\javaprac\\3FileReader\\A.txt");
int i;
while((i=fr.read())!=-1)
{
System.out.print((char)i);
}
fr.close();
}
}
Output: