Solution
Solution
An immutable object is an object whose internal state remains constant after it has been entirely
created. This means that once the object has been assigned to a variable, we can neither update
the reference nor mutate the internal state by any means. The key benefits of keeping String class
as immutable are caching, security, synchronization, and performance.
The String is the most widely used data structure. Caching the String literals and reusing them
saves a lot of heap space because different String variables refer to the same object in the String
pool. String intern pool serves exactly this purpose.
For example, lets declare two String variables with same value,
String s1 = “Hello World”;
String s2 =” Hello World”;
Here since s1 and s2 variables has same value (i.e. “Hello World”), instead of creating a separate
objects for each, JVM will create a string pool and both those reference will point to the same
value.
Java String Pool is the special memory region where Strings are stored by the JVM. Since
Strings are immutable in Java, the JVM optimizes the amount of memory allocated for them by
storing only one copy of each literal String in the pool. This process is called interning.
We can verify that the java string are immutable with the help of a sample code below:
class Test{
public static void main(String args[]){
String s="Good";
s.concat(" Morning"); //concat() method appends the string at the end
System.out.println(s); //will print Good because strings are immutable objects
}
}
Output:
Good
2. Define Inheritance and Composition. With the help of a suitable program illustrate
the difference between them.
The composition is a design technique in which your class can have an instance of another
class as a field of your class. Inheritance is a mechanism under which one object can acquire
the properties and behavior of the parent object by extending a class. Composition and
Inheritance both provide code reusability by relating class. We can also get the functionality
of inheritance when you use composition.
Inheritance Composition
Inheritance is an ‘is-a’ relationship Composition is an ‘has-a’ relationship
In Inheritance, a class can extend only one Using composition we can we can reuse
parent class, therefore, you can reuse your code in multiple class
code only in one class only
Inheritance provides its features at compile Composition is achieved at runtime
time
We can’t reuse code from the final class It allows code reuse even from final
classes
It exposes both public and protected method It doesn’t expose. They interact using
of the parent class public interface.
Sample code:
Lets create two classes named Animal and Dog. Since Dog is an Animal, they share ‘is-a’
relationship, thus we can use inheritance.
class Animal{
String name="Orio";
}
class Dog extends Animal{
String type="Dog";
public static void main(String args[]){
Dog p=new Dog();
System.out.println("Name:"+p.name);
System.out.println("Type:"+p.type);
}
}
Lets create two other classes names Student and College, since College ‘has-a’ Student, we
can use composition.
public class Student {
}
public class College {
private Student student;
public College() {
this.student = new Student();
}
}
class Demo
{
public static void main(String args[]) throws Exception
{
// Creating object whose property is to be checked
Test obj = new Test();
// Creating class object from the object using getclass method
Class cls = obj.getClass();
System.out.println("The name of class is " + cls.getName());
// Getting the constructor of the class through the object of the class
Constructor constructor = cls.getConstructor();
System.out.println("The name of constructor is " +
constructor.getName())
Output
The name of the class is Test
The name of the constructor is Test
Private data: Java Programming
Private method invoked
4. Write a program to read a pdf file containing a scanned image of a document and
create a duplicate of the file, also use the concept of buffering.
import java.io.*;
public class Copy {
public static void main(String[] args)
{
FileInputStream fis = null;
FileOutputStream fos = null;
BufferedInputStream bis = null;
BufferedOutputStream bout = null;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
We can convert a Java GUI application to an applet by following the steps listed below:
Import java.applet.Applet package
Make the class public and extend it from Applet instead of JFrame
Delete main() method, since the browser will automatically call the init() method
Rename constructor and replace it with void init() method
Delete any reference to super() method call
Delete any reference to setSize() method since the size of the applet will be provided
by the browser
Change all reference to getContentPane.add() into add()
Lets create a simple Java Swing application containing a button and a Textfield. When the button
is pressed the textfield will display hello world.
import javax.swing.*;
import java.awt.event.*;
public class Example extends JFrame implements ActionListener{
JButton b;
JTextField tf;
public void Example {
setSize(400,500);
tf=new JTextField();
tf.setBounds(30,40,150,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String [] args){
new Example();
}
}
Now let’s convert this application to an applet using the steps mentioned above.
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class EventJApplet extends JApplet implements ActionListener{
JButton b;
JTextField tf;
public void init(){
tf=new JTextField();
tf.setBounds(30,40,150,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
}
7. Create a Swing GUI application containing a textbox and a button. When the
button is pressed the font of the text entered in the textbox should be changed.
Choose the font of your preference. Also delegate the GUI and event handling
section into separate classes.
** Note: Since the question has explicitly asked to delegate GUI and event handling in
separate classes, you need to create 2 classes, one for displaying components and
another for button event handling **
import javax.swing.*;
public GUI(){
super("Sample GUI");
setSize(400,500);
tf = new JTextField("Type anything ...");
tf.setBounds(200,100,50,20);
button = new JButton("Change Font");
button.setBounds(200,300,50,20);
add(tf);
add(button);
Controller c = new Controller(this);
button.addActionListener(c);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String [] args){
new GUI();
}
}
import java.awt.event.*;
import java.awt.Font;
import java.awt.*;
import javax.swing.*;
class PieExample{
public static void main(String [] args){
new Pie();
}
}
9. Create a multithreaded TCP server that can take message from multiple user and
reply back to them individually.
import java.net.*;
import java.io.*;
class MultiThreadServer {
public static void main(String [] args) throws Exception{
// Socket initialise
ServerSocket ss = new ServerSocket(4000); // bind the socket to port 4000(arbitrary)
System.out.println("Server running at 4000 !!");
Thread Code
class Mythread extends Thread{
Socket s;
public Mythread(Socket s){
this.s = s;
}
public void run(){
try{
// to read and write data in socket stream
DataInputStream din = new DataInputStream(this.s.getInputStream());
DataOutputStream dout = new DataOutputStream(this.s.getOutputStream());
String msg =(String) din.readUTF();
System.out.println("Client says: "+ msg);
dout.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
Client Code
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class Client {
public static void main(String [] args) throws Exception{
Socket s = new Socket("localhost", 4000); //Use whatever port that you have used in
the server
dout.close();
scan.close();
s.close();
}
}
10. How can you process URL in Java? Write a sample code to display any four
components of any arbitrary URL.
The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator.
It points to a resource on the World Wide Web.
Example: http://www.example.com:80/nextpage.htm/
A URL contains many information:
Protocol: In this case, http is the protocol.
Server name or IP Address: In this case, www.javatpoint.com is the server name.
Port Number: It is an optional attribute. If we write
http://www.example.com:80/nextpage.htm/ , 80 is the port number. If port number is not
mentioned in the URL, it returns -1.
File Name or directory name: In this case, nextpag.htm is the file name.
Sample Code:
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.college.com/java-tutorial");
System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());
}catch(Exception e){
System.out.println(e);
}
}
}
Output:
Protocol: http
Host Name: www.college.com
Port Number: -1
File Name: /java-tutorial
11. A database “testdb” contains a table “Student” with fields id, name and address.
Write a program that asks user to enter the information and save them in the
database. The program should prompt the user to press y/n to either continue or
exit the program after every successful entry.
import java.sql.*;
import java.util.Scanner;
class RS{
public static void main(String args[])throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb","root","root");
PreparedStatement ps=con.prepareStatement("insert into Student values(?,?,?)");
Scanner scan = new Scanner(System.in);
do{
System.out.println("enter id:");
int id= scan.nextInt();
System.out.println("enter name:");
String name=scan.nextLine();
System.out.println("enter address:");
String add = scan.nextLine();
ps.setInt(1,id);
ps.setString(2,name);
ps.setString(3,add);
int i=ps.executeUpdate();
System.out.println("Do you want to continue: y/n");
String prompt= scan.nextLine();
if(prompt.startsWith("n")){
break;
}
}while(true);
con.close();
}}