3.
i)Read input data from keyboard
import [Link]; // Needed for Scanner class
/**
* This program demonstrates keyboard input.
*/
public class RectangleArea
{
public static void main(String[] args)
{
int length; // To hold rectangle's length.
int width; // To hold rectangle's width.
int area; // To hold rectangle's area
// Create a Scanner object to read input.
Scanner console = new Scanner([Link]);
// Get length from the user.
[Link]("Enter length ");
length = [Link]();
// Get width from the user.
[Link]("Enter width ");
width = [Link]();
// Calculate area.
area = length * width;
// Display area.
[Link]("The area of rectangle is " + area);
}
}
ii)
// Java Program to Demonstrate DataOutputStream
// Importing required classes
import [Link].*;
// Main class
// DataOutputStreamDemo
class GFG {
// Main driver method
public static void main(String args[]) throws IOException {
// Try block to check for exceptions
// Writing the data using DataOutputStream
try ( DataOutputStream dout =
new DataOutputStream(new
FileOutputStream("[Link]")) ) {
[Link](1.1);
[Link](55);
[Link](true);
[Link]('4');
}
catch (FileNotFoundException ex) {
[Link]("Cannot Open the Output File");
return;
}
// Reading the data back using DataInputStream
try ( DataInputStream din =
new DataInputStream(new
FileInputStream("[Link]")) ) {
double a = [Link]();
int b = [Link]();
boolean c = [Link]();
char d = [Link]();
[Link]("Values: " + a + " " + b + " " + c + " "
+ d);
}
// Catch block to handle FileNotFoundException
catch (FileNotFoundException e) {
[Link]("Cannot Open the Input File");
return;
}
}
}
// Java program to Demonstrate DataInputStream Class
// Importing I/O classes
import [Link].*;
// Main class
class DataInputStreamDemo {
// Main driver method
public static void main(String args[]) throws IOException {
// Writing the data
// Try block to check for exceptions
try ( DataOutputStream dout =
new DataOutputStream(new FileOutputStream("[Link]")) ) {
[Link](1.1);
[Link](55);
[Link](true);
[Link]('4');
}
// Catch block to handle the exceptions
catch (FileNotFoundException ex) {
// Display message when FileNotFoundException occurs
[Link]("Cannot Open the Output File");
return;
}
// Reading the data back.
// Try block to check for exceptions
try ( DataInputStream din =
new DataInputStream(new FileInputStream("[Link]")) ) {
// Illustrating readDouble() method
double a = [Link]();
// Illustrating readInt() method
int b = [Link]();
// Illustrating readBoolean() method
boolean c = [Link]();
// Illustrating readChar() method
char d = [Link]();
// Print the values
[Link]("Values: " + a + " " + b + " " + c + " " + d);
}
// Catch block to handle the exceptions
catch (FileNotFoundException e) {
// Display message when FileNotFoundException occurs
[Link]("Cannot Open the Input File");
return;
}
}
}
iii)
import [Link];
import [Link];
import [Link];
public class ReadFromFile {
public static void main(String[] args) throws IOException {
File file = new File("[Link]");
FileReader fr = new FileReader(file);
int ch;
while ((ch=[Link]()) != -1) {
[Link]((char)ch);
}
[Link]();
}
}
import [Link];
import [Link];
import [Link];
public class WriteToFile {
public static void main(String[] args) throws IOException {
File file = new File("[Link]");
FileWriter fw = new FileWriter(file);
[Link]("Hello World!");
[Link]();
}
}
[Link] programs on strings
i)strings compre by equals
public class StringCompareequl{
public static void main(String []args){
String s1 = "tutorialspoint";
String s2 = "tutorialspoint";
String s3 = new String ("Tutorials Point");
[Link]([Link](s2));
[Link]([Link](s3));
}
}
ii)reverse a string
public class StringReverseExample{
public static void main(String[] args) {
String string = "abcdef";
String reverse = new StringBuffer(string).reverse().toString();
[Link]("\nString before reverse: "+string);
[Link]("String after reverse: "+reverse);
}
}
iii)search a word in a string
public class HelloWorld {
public static void main(String[] args) {
String text = "The cat is on the table";
[Link]([Link]("the"));
}
}
[Link] class and object and adding a method
class Lamp {
// stores the value for light
// true if light is on
// false if light is off
boolean isOn;
// method to turn on the light
void turnOn() {
isOn = true;
[Link]("Light on? " + isOn);
// method to turnoff the light
void turnOff() {
isOn = false;
[Link]("Light on? " + isOn);
}
}
class Main {
public static void main(String[] args) {
// create objects led and halogen
Lamp led = new Lamp();
Lamp halogen = new Lamp();
// turn on the light by
// calling method turnOn()
[Link]();
// turn off the light by
// calling method turnOff()
[Link]();
}
}
[Link] program on constructor and constructor overloading
i)constructor
class MyClass
{
MyClass()
{
[Link]("No-argument constructor called");
}
public static void main(String[] args)
{
MyClass obj = new MyClass();
}
}
ii)constructor overloding
Source Code
class Box
{
double width, height, depth;
Box()
{
width = 1;
height = 1;
depth = 1;
}
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
void myMethod()
{
[Link]("Width : " + width);
[Link]("Height : " + height);
[Link]("Depth : " + depth);
}
public static void main(String[] args)
{
Box box1 = new Box();
Box box2 = new Box(3, 8, 6);
[Link]();
}
}
7.
i)
class Example2{
public static void main(String[] args){
int a = [Link](args[0]);
int b = [Link](args[1]);
int sum = a + b;
[Link]("The sum is" +sum);
}
}
ii)
[Link] progrms using concept of overloading method in java
class Adder{
static int add(int a,int b){
return a+b;
}
static int add(int a,int b,int c){
return a+b+c;
}
}
class TestOverloading1{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}
}
[Link]
i) single
Source Code
public class SingleInheritance // Main class
{
public static void main(String[] args)
{
Dog dog = new Dog("Buddy"); // Create an instance of Dog
[Link](); // Call methods from Animal class
[Link](); // Call methods from Dog class
}
}
class Animal // Parent class (Superclass)
{
protected String name;
public Animal(String name)
{
[Link] = name;
}
public void eat()
{
[Link](name + " is Eating");
}
}
class Dog extends Animal // Child class (Subclass) inheriting from Animal
{
public Dog(String name)
{
super(name);
}
public void bark()
{
[Link](name + " is Barking");
}
}
ii)multilevel
Source Code
public class MultilevelInheritance // Main class
{
public static void main(String[] args)
{
Puppy puppy = new Puppy("Buddy"); // Create an instance of Puppy
[Link](); // Call methods from Animal class
[Link](); // Call methods from Dog class
[Link](); // Call methods from Puppy class
}
}
class Animal // Grandparent class
{
protected String name;
public Animal(String name)
{
[Link] = name;
}
public void eat()
{
[Link](name + " is Eating");
}
}
class Dog extends Animal // Parent class inheriting from Animal
{
public Dog(String name)
{
super(name);
}
public void bark()
{
[Link](name + " is Barking");
}
}
class Puppy extends Dog // Child class inheriting from Dog
{
public Puppy(String name)
{
super(name);
}
public void play()
{
[Link](name + " is Playing");
}
}
iii)Hierarchical
public class HierarchicalInheritance // Main class
{
public static void main(String[] args)
{
Car car = new Car(); // Create objects of child classes
Motorcycle motorcycle = new Motorcycle();
[Link](); // Calling methods of parent class
[Link]();
[Link](); // Calling methods of child classes
[Link]();
}
}
class Vehicle // Parent class
{
void display()
{
[Link]("This is a Vehicle");
}
}
class Car extends Vehicle // Child class 1
{
void displayCar()
{
[Link]("This is a Car");
}
}
class Motorcycle extends Vehicle // Child class 2
{
void displayMotorcycle()
{
[Link]("This is a Motorcycle");
}
}
10)Method overriding
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
class Vehicle{
//defining a method
void run(){[Link]("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){[Link]("Bike is running safely");}
public static void main(String args[]){
Bike2 obj = new Bike2();//creating object
[Link]();//calling method
}
}
11)Packages
i)creation of package
package library;
import [Link];
public class Program {
public static void main(String[] args) {
Book book = new Book("the ABCs of packages!");
[Link]("Hello packageworld: " + [Link]());
}
}
ii) importing packge from other packages
package myPackage;
import [Link].*;
public class ImportingExample {
public static void main(String[] args) {
Scanner read = new Scanner([Link]);
int i = [Link]();
[Link]("You have entered a number " + i);
Random rand = new Random();
int num = [Link](100);
[Link]("Randomly generated number " + num);
}
}
12)Interfces
// Java program to demonstrate working of
// interface
import [Link].*;
// A simple interface
interface In1 {
// public, static and final
final int a = 10;
// public and abstract
void display();
}
// A class that implements the interface.
class TestClass implements In1 {
// Implementing the capabilities of
// interface.
public void display(){
[Link]("Geek");
}
// Driver Code
public static void main(String[] args)
{
TestClass t = new TestClass();
[Link]();
[Link](t.a);
}
}
13)Collections
i)search a student mark percentage based on pin using arraylist
import [Link];
public class Student_Marks
{
public static void main(String[] args)
{
int n, total = 0, percentage;
Scanner s = new Scanner([Link]);
[Link]("Enter no. of subject:");
n = [Link]();
int marks[] = new int[n];
[Link]("Enter marks out of 100:");
for(int i = 0; i < n; i++)
{
marks[i] = [Link]();
total = total + marks[i];
}
percentage = total / n;
[Link]("Sum:"+total);
[Link]("Percentage:"+percentage);
}
}
ii)Linked List
import [Link];
class Main {
public static void main(String[] args) {
LinkedList<String> languages = new LinkedList<>();
// add elements in LinkedList
[Link]("Java");
[Link]("Python");
[Link]("JavaScript");
[Link]("Kotlin");
[Link]("LinkedList: " + languages);
// remove elements from index 1
String str = [Link](1);
[Link]("Removed Element: " + str);
[Link]("Updated LinkedList: " + languages);
}
}
iii)search an element from hash table
import [Link];
public class Main {
static final int SIZE = 10; // Define the size of the hash table
static class DataItem {
int key;
}
static HashMap<Integer, DataItem> hashMap = new HashMap<>(); // Define the hash
table as a HashMap
static int hashCode(int key) {
// Return a hash value based on the key
return key % SIZE;
}
static DataItem search(int key) {
// get the hash
int hashIndex = hashCode(key);
// move in map until an empty slot is found or the key is found
while ([Link](hashIndex) != null) {
// If the key is found, return the corresponding DataItem
if ([Link](hashIndex).key == key)
return [Link](hashIndex);
// go to the next cell
++hashIndex;
// wrap around the table
hashIndex %= SIZE;
}
// If the key is not found, return null
return null;
}
public static void main(String[] args) {
// Initializing the hash table with some sample DataItems
DataItem item2 = new DataItem();
[Link] = 25; // Assuming the key is 25
DataItem item3 = new DataItem();
[Link] = 64; // Assuming the key is 64
DataItem item4 = new DataItem();
[Link] = 22; // Assuming the key is 22
// Calculate the hash index for each item and place them in the hash table
int hashIndex2 = hashCode([Link]);
[Link](hashIndex2, item2);
int hashIndex3 = hashCode([Link]);
[Link](hashIndex3, item3);
int hashIndex4 = hashCode([Link]);
[Link](hashIndex4, item4);
// Call the search function to test it
int keyToSearch = 64; // The key to search for in the hash table
DataItem result = search(keyToSearch);
[Link]("The element to be searched: " + keyToSearch);
if (result != null) {
[Link]("\nElement found");
} else {
[Link]("\nElement not found");
}
}
}
iv)sorting employee details using hash map
// Java Code to sort Map by key value
import [Link].*;
class sortmapKey {
// This map stores unsorted values
static Map<String, Integer> map = new HashMap<>();
// Function to sort map by Key
public static void sortbykey()
{
ArrayList<String> sortedKeys
= new ArrayList<String>([Link]());
[Link](sortedKeys);
// Display the TreeMap which is naturally sorted
for (String x : sortedKeys)
[Link]("Key = " + x
+ ", Value = " + [Link](x));
}
// Driver Code
public static void main(String args[])
{
// putting values in the Map
[Link]("Jayant", 80);
[Link]("Abhishek", 90);
[Link]("Anushka", 80);
[Link]("Amit", 75);
[Link]("Danish", 40);
// Calling the function to sortbyKey
sortbykey();
}
}
14)exercises on exception handling
i)try, catch,finlly
public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
[Link](myNumbers[10]);
} catch (Exception e) {
[Link]("Something went wrong.");
}
}
}
finlly
public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
[Link](myNumbers[10]);
} catch (Exception e) {
[Link]("Something went wrong.");
} finally {
[Link]("The 'try catch' is finished.");
}
}
}
ii)multiple catch sattement
public class MultipleCatchBlock1 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
iii)multiple try sttements
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
[Link]("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
[Link](e);
}
//inner try block 2
try{
int a[]=new int[5];
//assigning the value out of array bounds
a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("other statement");
}
//catch block of outer try block
catch(Exception e)
{
[Link]("handled the exception (outer catch)");
}
[Link]("normal flow..");
}
}
15)Exercises on multithreading
i)creation of single and multile threads
//single thread
import [Link].*;
class GFG extends Thread {
public void run()
{
[Link]("Welcome to GeeksforGeeks.");
}
public static void main(String[] args)
{
GFG g = new GFG(); // creating thread
[Link](); // starting thread
}
}
// Java Program to Run Multiple Threads
// class extends thread class
class Main extends Thread {
// run method implementation
public void run()
{
[Link]("Geeks for Geeks");
}
// in the main method
public static void main(String args[])
{
// object creation
Main t1 = new Main();
// object creation
Main t2 = new Main();
// object creation
Main t3 = new Main();
// start the thread
[Link]();
// start the thread
[Link]();
// start the thread
[Link]();
}
}
ii)adding priorities to multithreads
/ Java Program to Illustrate Priorities in Multithreading
// via help of getPriority() and setPriority() method
// Importing required classes
import [Link].*;
// Main class
class ThreadDemo extends Thread {
// Method 1
// run() method for the thread that is called
// as soon as start() is invoked for thread in main()
public void run()
{
// Print statement
[Link]("Inside run method");
}
// Main driver method
public static void main(String[] args)
{
// Creating random threads
// with the help of above class
ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
ThreadDemo t3 = new ThreadDemo();
// Thread 1
// Display the priority of above thread
// using getPriority() method
[Link]("t1 thread priority : "
+ [Link]());
// Thread 1
// Display the priority of above thread
[Link]("t2 thread priority : "
+ [Link]());
// Thread 3
[Link]("t3 thread priority : "
+ [Link]());
// Setting priorities of above threads by
// passing integer arguments
[Link](2);
[Link](5);
[Link](8);
// [Link](21); will throw
// IllegalArgumentException
// 2
[Link]("t1 thread priority : "
+ [Link]());
// 5
[Link]("t2 thread priority : "
+ [Link]());
// 8
[Link]("t3 thread priority : "
+ [Link]());
// Main thread
// Displays the name of
// currently executing Thread
[Link](
"Currently Executing Thread : "
+ [Link]().getName());
[Link](
"Main thread priority : "
+ [Link]().getPriority());
// Main thread priority is set to 10
[Link]().setPriority(10);
[Link](
"Main thread priority : "
+ [Link]().getPriority());
}
}
iii)Inter thread communication
// Java program to demonstrate inter-thread communication
// (wait(), join() and notify())
import [Link];
public class threadexample
{
public static void main(String[] args) throws InterruptedException
{
final PC pc = new PC();
// Create a thread object that calls [Link]()
Thread t1 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
[Link]();
}
catch(InterruptedException e)
{
[Link]();
}
}
});
// Create another thread object that calls
// [Link]()
Thread t2 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
[Link]();
}
catch(InterruptedException e)
{
[Link]();
}
}
});
// Start both threads
[Link]();
[Link]();
// t1 finishes before t2
[Link]();
[Link]();
}
// PC (Produce Consumer) class with produce() and
// consume() methods.
public static class PC
{
// Prints a string and waits for consume()
public void produce()throws InterruptedException
{
// synchronized block ensures only one thread
// running at a time.
synchronized(this)
{
[Link]("producer thread running");
// releases the lock on shared resource
wait();
// and waits till some other method invokes notify().
[Link]("Resumed");
}
}
// Sleeps for some time and waits for a key press. After key
// is pressed, it notifies produce().
public void consume()throws InterruptedException
{
// this makes the produce thread to run first.
[Link](1000);
Scanner s = new Scanner([Link]);
// synchronized block ensures only one thread
// running at a time.
synchronized(this)
{
[Link]("Waiting for return key.");
[Link]();
[Link]("Return key pressed");
// notifies the produce thread that it
// can wake up.
notify();
// Sleep
[Link](2000);
}
}
}
}