3.
i)Read input data from keyboard
import java.util.Scanner; // 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(System.in);
// Get length from the user.
System.out.print("Enter length ");
length = console.nextInt();
// Get width from the user.
System.out.print("Enter width ");
width = console.nextInt();
// Calculate area.
area = length * width;
// Display area.
System.out.println("The area of rectangle is " + area);
}
}
ii)
// Java Program to Demonstrate DataOutputStream
// Importing required classes
import java.io.*;
// 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("file.dat")) ) {
dout.writeDouble(1.1);
dout.writeInt(55);
dout.writeBoolean(true);
dout.writeChar('4');
}
catch (FileNotFoundException ex) {
System.out.println("Cannot Open the Output File");
return;
}
// Reading the data back using DataInputStream
try ( DataInputStream din =
new DataInputStream(new
FileInputStream("file.dat")) ) {
double a = din.readDouble();
int b = din.readInt();
boolean c = din.readBoolean();
char d = din.readChar();
System.out.println("Values: " + a + " " + b + " " + c + " "
+ d);
}
// Catch block to handle FileNotFoundException
catch (FileNotFoundException e) {
System.out.println("Cannot Open the Input File");
return;
}
}
}
// Java program to Demonstrate DataInputStream Class
// Importing I/O classes
import java.io.*;
// 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("file.dat")) ) {
dout.writeDouble(1.1);
dout.writeInt(55);
dout.writeBoolean(true);
dout.writeChar('4');
}
// Catch block to handle the exceptions
catch (FileNotFoundException ex) {
// Display message when FileNotFoundException occurs
System.out.println("Cannot Open the Output File");
return;
}
// Reading the data back.
// Try block to check for exceptions
try ( DataInputStream din =
new DataInputStream(new FileInputStream("file.dat")) ) {
// Illustrating readDouble() method
double a = din.readDouble();
// Illustrating readInt() method
int b = din.readInt();
// Illustrating readBoolean() method
boolean c = din.readBoolean();
// Illustrating readChar() method
char d = din.readChar();
// Print the values
System.out.println("Values: " + a + " " + b + " " + c + " " + d);
}
// Catch block to handle the exceptions
catch (FileNotFoundException e) {
// Display message when FileNotFoundException occurs
System.out.println("Cannot Open the Input File");
return;
}
}
}
iii)
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadFromFile {
public static void main(String[] args) throws IOException {
File file = new File("filename.txt");
FileReader fr = new FileReader(file);
int ch;
while ((ch=fr.read()) != -1) {
System.out.print((char)ch);
}
fr.close();
}
}
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFile {
public static void main(String[] args) throws IOException {
File file = new File("filename.txt");
FileWriter fw = new FileWriter(file);
fw.write("Hello World!");
fw.close();
}
}
4.Exercise 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");
System.out.println(s1.equals(s2));
System.out.println(s2.equals(s3));
}
}
ii)reverse a string
public class StringReverseExample{
public static void main(String[] args) {
String string = "abcdef";
String reverse = new StringBuffer(string).reverse().toString();
System.out.println("\nString before reverse: "+string);
System.out.println("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";
System.out.print(text.contains("the"));
}
}
5.create 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;
System.out.println("Light on? " + isOn);
// method to turnoff the light
void turnOff() {
isOn = false;
System.out.println("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()
led.turnOn();
// turn off the light by
// calling method turnOff()
halogen.turnOff();
}
}
6.Exercise program on constructor and constructor overloading
i)constructor
class MyClass
{
MyClass()
{
System.out.println("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()
{
System.out.println("Width : " + width);
System.out.println("Height : " + height);
System.out.println("Depth : " + depth);
}
public static void main(String[] args)
{
Box box1 = new Box();
Box box2 = new Box(3, 8, 6);
box2.myMethod();
}
}
7.
i)
class Example2{
public static void main(String[] args){
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int sum = a + b;
System.out.println("The sum is" +sum);
}
}
ii)
8.exercise 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){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
9.Inheritnce
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
dog.eat(); // Call methods from Animal class
dog.bark(); // Call methods from Dog class
}
}
class Animal // Parent class (Superclass)
{
protected String name;
public Animal(String name)
{
this.name = name;
}
public void eat()
{
System.out.println(name + " is Eating");
}
}
class Dog extends Animal // Child class (Subclass) inheriting from Animal
{
public Dog(String name)
{
super(name);
}
public void bark()
{
System.out.println(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
puppy.eat(); // Call methods from Animal class
puppy.bark(); // Call methods from Dog class
puppy.play(); // Call methods from Puppy class
}
}
class Animal // Grandparent class
{
protected String name;
public Animal(String name)
{
this.name = name;
}
public void eat()
{
System.out.println(name + " is Eating");
}
}
class Dog extends Animal // Parent class inheriting from Animal
{
public Dog(String name)
{
super(name);
}
public void bark()
{
System.out.println(name + " is Barking");
}
}
class Puppy extends Dog // Child class inheriting from Dog
{
public Puppy(String name)
{
super(name);
}
public void play()
{
System.out.println(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();
car.display(); // Calling methods of parent class
motorcycle.display();
car.displayCar(); // Calling methods of child classes
motorcycle.displayMotorcycle();
}
}
class Vehicle // Parent class
{
void display()
{
System.out.println("This is a Vehicle");
}
}
class Car extends Vehicle // Child class 1
{
void displayCar()
{
System.out.println("This is a Car");
}
}
class Motorcycle extends Vehicle // Child class 2
{
void displayMotorcycle()
{
System.out.println("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(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}
public static void main(String args[]){
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
11)Packages
i)creation of package
package library;
import library.domain.Book;
public class Program {
public static void main(String[] args) {
Book book = new Book("the ABCs of packages!");
System.out.println("Hello packageworld: " + book.getName());
}
}
ii) importing packge from other packages
package myPackage;
import java.util.*;
public class ImportingExample {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int i = read.nextInt();
System.out.println("You have entered a number " + i);
Random rand = new Random();
int num = rand.nextInt(100);
System.out.println("Randomly generated number " + num);
}
}
12)Interfces
// Java program to demonstrate working of
// interface
import java.io.*;
// 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(){
System.out.println("Geek");
}
// Driver Code
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(t.a);
}
}
13)Collections
i)search a student mark percentage based on pin using arraylist
import java.util.Scanner;
public class Student_Marks
{
public static void main(String[] args)
{
int n, total = 0, percentage;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of subject:");
n = s.nextInt();
int marks[] = new int[n];
System.out.println("Enter marks out of 100:");
for(int i = 0; i < n; i++)
{
marks[i] = s.nextInt();
total = total + marks[i];
}
percentage = total / n;
System.out.println("Sum:"+total);
System.out.println("Percentage:"+percentage);
}
}
ii)Linked List
import java.util.LinkedList;
class Main {
public static void main(String[] args) {
LinkedList<String> languages = new LinkedList<>();
// add elements in LinkedList
languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
languages.add("Kotlin");
System.out.println("LinkedList: " + languages);
// remove elements from index 1
String str = languages.remove(1);
System.out.println("Removed Element: " + str);
System.out.println("Updated LinkedList: " + languages);
}
}
iii)search an element from hash table
import java.util.HashMap;
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 (hashMap.get(hashIndex) != null) {
// If the key is found, return the corresponding DataItem
if (hashMap.get(hashIndex).key == key)
return hashMap.get(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();
item2.key = 25; // Assuming the key is 25
DataItem item3 = new DataItem();
item3.key = 64; // Assuming the key is 64
DataItem item4 = new DataItem();
item4.key = 22; // Assuming the key is 22
// Calculate the hash index for each item and place them in the hash table
int hashIndex2 = hashCode(item2.key);
hashMap.put(hashIndex2, item2);
int hashIndex3 = hashCode(item3.key);
hashMap.put(hashIndex3, item3);
int hashIndex4 = hashCode(item4.key);
hashMap.put(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);
System.out.print("The element to be searched: " + keyToSearch);
if (result != null) {
System.out.println("\nElement found");
} else {
System.out.println("\nElement not found");
}
}
}
iv)sorting employee details using hash map
// Java Code to sort Map by key value
import java.util.*;
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>(map.keySet());
Collections.sort(sortedKeys);
// Display the TreeMap which is naturally sorted
for (String x : sortedKeys)
System.out.println("Key = " + x
+ ", Value = " + map.get(x));
}
// Driver Code
public static void main(String args[])
{
// putting values in the Map
map.put("Jayant", 80);
map.put("Abhishek", 90);
map.put("Anushka", 80);
map.put("Amit", 75);
map.put("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};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}
finlly
public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("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)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("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{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(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)
{
System.out.println(e);
}
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
15)Exercises on multithreading
i)creation of single and multile threads
//single thread
import java.io.*;
class GFG extends Thread {
public void run()
{
System.out.print("Welcome to GeeksforGeeks.");
}
public static void main(String[] args)
{
GFG g = new GFG(); // creating thread
g.start(); // starting thread
}
}
// Java Program to Run Multiple Threads
// class extends thread class
class Main extends Thread {
// run method implementation
public void run()
{
System.out.println("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
t1.start();
// start the thread
t2.start();
// start the thread
t3.start();
}
}
ii)adding priorities to multithreads
/ Java Program to Illustrate Priorities in Multithreading
// via help of getPriority() and setPriority() method
// Importing required classes
import java.lang.*;
// 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
System.out.println("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
System.out.println("t1 thread priority : "
+ t1.getPriority());
// Thread 1
// Display the priority of above thread
System.out.println("t2 thread priority : "
+ t2.getPriority());
// Thread 3
System.out.println("t3 thread priority : "
+ t3.getPriority());
// Setting priorities of above threads by
// passing integer arguments
t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);
// t3.setPriority(21); will throw
// IllegalArgumentException
// 2
System.out.println("t1 thread priority : "
+ t1.getPriority());
// 5
System.out.println("t2 thread priority : "
+ t2.getPriority());
// 8
System.out.println("t3 thread priority : "
+ t3.getPriority());
// Main thread
// Displays the name of
// currently executing Thread
System.out.println(
"Currently Executing Thread : "
+ Thread.currentThread().getName());
System.out.println(
"Main thread priority : "
+ Thread.currentThread().getPriority());
// Main thread priority is set to 10
Thread.currentThread().setPriority(10);
System.out.println(
"Main thread priority : "
+ Thread.currentThread().getPriority());
}
}
iii)Inter thread communication
// Java program to demonstrate inter-thread communication
// (wait(), join() and notify())
import java.util.Scanner;
public class threadexample
{
public static void main(String[] args) throws InterruptedException
{
final PC pc = new PC();
// Create a thread object that calls pc.produce()
Thread t1 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
pc.produce();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});
// Create another thread object that calls
// pc.consume()
Thread t2 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
pc.consume();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});
// Start both threads
t1.start();
t2.start();
// t1 finishes before t2
t1.join();
t2.join();
}
// 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)
{
System.out.println("producer thread running");
// releases the lock on shared resource
wait();
// and waits till some other method invokes notify().
System.out.println("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.
Thread.sleep(1000);
Scanner s = new Scanner(System.in);
// synchronized block ensures only one thread
// running at a time.
synchronized(this)
{
System.out.println("Waiting for return key.");
s.nextLine();
System.out.println("Return key pressed");
// notifies the produce thread that it
// can wake up.
notify();
// Sleep
Thread.sleep(2000);
}
}
}
}