Showing posts with label Core Java. Show all posts
Showing posts with label Core Java. Show all posts

Monday, January 30, 2023

Emi calculator in java code

Here's a simple Java code to calculate EMI (Equated Monthly Installment) using the formula:


import java.math.BigDecimal;

import java.math.RoundingMode;


public class EMI_Calculator {

  public static void main(String[] args) {

    double p = 10000;   // Loan amount

    double r = 0.05;    // Interest rate

    int n = 12;         // Loan tenure in months


    double emi = (p * r * Math.pow(1 + r, n)) / (Math.pow(1 + r, n) - 1);


    BigDecimal bd = new BigDecimal(emi).setScale(2, RoundingMode.HALF_UP);

    System.out.println("EMI: $" + bd.doubleValue());

  }

}


This code calculates the EMI for a loan of $10,000 with 5% interest rate for a tenure of 12 months. The output will be rounded to 2 decimal places using BigDecimal class. 

Wednesday, January 11, 2017

How to convert JSON file to String

Below method will return String. You need to pass argument file path.



public static String getStringFromInputStream(String filepath) {

         BufferedReader br = null;
         StringBuilder sb = new StringBuilder();

         String line;
         try {
             br = new BufferedReader(new FileReader(filepath));
             while ((line = br.readLine()) != null) {
                 sb.append(line);
             }

         } catch (IOException e) {
             e.printStackTrace();
         } finally {
             if (br != null) {
                 try {
                      br.close();
                 } catch (IOException e) {
                      e.printStackTrace();
                 }
             }
         }

         return sb.toString();


    }

Friday, October 18, 2013

How sort list of object with multiple data sort in java



package example;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Demo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Demo demo = new Demo();
        List<Student> list = new ArrayList<Student>(); // your Car list
        Student st = demo.new Student();
        st.setName("sekhar");
        st.setCity("bbsr");
        st.setRoll(23);
        list.add(st);
        st = demo.new Student();
        st.setName("himanshu");
        st.setCity("agra");
        st.setRoll(23);
        list.add(st);
        st = demo.new Student();
        st.setName("nitin");
        st.setCity("delhi");
        st.setRoll(23);
        list.add(st);
        st = demo.new Student();
        st.setName("nitin");
        st.setCity("delhi");
        st.setRoll(22);
        list.add(st);
        st = demo.new Student();
        st.setName("nitin");
        st.setCity("bbsr");
        st.setRoll(23);
        list.add(st);
        st = demo.new Student();
        st.setName("arun");
        st.setCity("patna");
        st.setRoll(23);
        list.add(st);
        st = demo.new Student();
        st.setName("arun");
        st.setCity("kendrapara");
        st.setRoll(23);
        list.add(st);
        System.out.println("before sort");
        System.out.println("Name:" + "-------------------" + "City...........roll");
        for (Student st1 : list) {
            System.out.println(st1.getName() + " --------------" + st1.getCity() + "------------" + st1.getRoll());
        }

        Collections.sort(list, demo.new CarHorsePowerComparator());
        System.out.println("after sort");
        System.out.println("Name:" + "-------------------" + "City...............roll");
        for (Student st1 : list) {
            System.out.println(st1.getName() + " --------------" + st1.getCity() + "------------" + st1.getRoll());
        }
    }

    public class Student {

        String name;
        String city;
        int roll;

        public int getRoll() {
            return roll;
        }

        public void setRoll(int roll) {
            this.roll = roll;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    class CarHorsePowerComparator implements Comparator<Student> {
        private final Collator collator = Collator.getInstance(); //Default local is taken.

          public int compare(Student left, Student right) {

            int result = collator.compare(left.getName(),right.getName());

            if(result == 0) {
                result = collator.compare(right.getCity(),left.getCity());
            }

            if(result == 0) {
                result = Integer.compare(left.getRoll(), right.getRoll()); //JDK 7
               //result = Double.compare(left.getRoll(), right.getRoll());
            }

            return result;
        }
    }
}


OutPut:

before sort
Name:-------------------City...........roll
sekhar --------------bbsr------------23
himanshu --------------agra------------23
nitin --------------delhi------------23
nitin --------------delhi------------22
nitin --------------bbsr------------23
arun --------------patna------------23
arun --------------kendrapara------------23
after sort
Name:-------------------City...............roll
arun --------------patna------------23
arun --------------kendrapara------------23
himanshu --------------agra------------23
nitin --------------delhi------------22
nitin --------------delhi------------23
nitin --------------bbsr------------23
sekhar --------------bbsr------------23

Friday, July 26, 2013

What and where are the stack and heap?

Q. 1
Programming language books usually explain that value types are created on the stack, and reference types are created on the heap, without really explaining what these two things are. With my only programming experience being in high level languages, I haven't read a clear explanation of this. I mean I understand what a stack is, but where and what are they (relative to the physical memory of a real computer)?
  • To what extent are they controlled by the OS or language runtime?
  • What is their scope?
  • What determines the size of each of them?
  • What makes one faster? 
A. 1

The stack is the memory set aside as scratch space for a thread of execution. When a function is called, a block is reserved on the top of the stack for local variables and some bookkeeping data. When that function returns, the block becomes unused and can be used the next time a function is called. The stack is always reserved in a LIFO order; the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack; freeing a block from the stack is nothing more than adjusting one pointer.
The heap is memory set aside for dynamic allocation. Unlike the stack, there's no enforced pattern to the allocation and deallocation of blocks from the heap; you can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time; there are many custom heap allocators available to tune heap performance for different usage patterns.
Each thread gets a stack, while there's typically only one heap for the application (although it isn't uncommon to have multiple heaps for different types of allocation).
To answer your questions directly:

To what extent are they controlled by the OS or language runtime?
The OS allocates the stack for each system-level thread when the thread is created. Typically the OS is called by the language runtime to allocate the heap for the application.

What is their scope?
The stack is attached to a thread, so when the thread exits the stack is reclaimed. The heap is typically allocated at application startup by the runtime, and is reclaimed when the application (technically process) exits.

What determines the size of each of them?
The size of the stack is set when a thread is created. The size of the heap is set on application startup, but can grow as space is needed (the allocator requests more memory from the operating system).

What makes one faster?
The stack is faster because the access pattern makes it trivial to allocate and deallocate memory from it (a pointer/integer is simply incremented or decremented), while the heap has much more complex bookkeeping involved in an allocation or free. Also, each byte in the stack tends to be reused very frequently which means it tends to be mapped to the processor's cache, making it very fast.

More Details here

Thursday, July 18, 2013

String Permutation in java

package com.swain;

public class Permutation {

    public static void main(String args[]) throws Exception {
        String str = "abc";
        System.out.println("String is " + str);
        System.out.println("*********************");
        System.out.println("After Permutation ");
        showString("", str);
    }

    public static void showString(String st, String str) {
        if (str.length() <= 1)
            System.out.println(st + str);
        else
            for (int i = 0; i < str.length(); i++) {
                String newValue = str.substring(0, i) + str.substring(i + 1);
                showString(st + str.charAt(i), newValue);
            }
    }

}
************************************
or
 ************************************
package com.swain;

public class Permutation {
    static String permutationStr[];
    static int indexStr = 0;

    static int factorial(int i) {
        if (i == 1)
            return 1;
        else
            return i * factorial(i - 1);
    }

    public static void permutation(String str) {
        char strArr[] = str.toLowerCase().toCharArray();
        java.util.Arrays.sort(strArr);

        int count = 1, dr = 1;
        for (int i = 0; i < strArr.length - 1; i++) {
            if (strArr[i] == strArr[i + 1]) {
                count++;
            } else {
                dr *= factorial(count);
                count = 1;
            }
        }
        dr *= factorial(count);

        count = factorial(strArr.length) / dr;

        permutationStr = new String[count];

        permutation("", str);

        for (String oneStr : permutationStr) {
            System.out.println(oneStr);
        }
    }

    private static void permutation(String prefix, String str) {
        int n = str.length();
        if (n == 0) {
            for (int i = 0; i < indexStr; i++) {
                if (permutationStr[i].equals(prefix))
                    return;
            }
            permutationStr[indexStr++] = prefix;
        } else {
            for (int i = 0; i < n; i++) {
                permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
            }
        }
    }

    public static void main(String arg[]) {
        Permutation p = new Permutation();
        p.permutation("aaa");
    }
}

output :


Monday, July 15, 2013

how to replace 2 or more spaces with single space in string using Java

package com.swain;

public class StringUtil {
    public static void main(String args[]) {
        String before = " Himanshu      Sekhar           Swain  ";
        System.out.println("before: " + before);
        String after = before.trim().replaceAll(" +", " ");
        System.out.println("after: " + after);
    }

}

Thursday, June 13, 2013

how to get after 5 days date

Calendar currentDate = Calendar.getInstance();
        Calendar prevDay = (Calendar) currentDate.clone();
        prevDay.add (Calendar.DAY_OF_YEAR, 5);
        System.out.println ("After 5 Day: " + prevDay.getTime());

How to get previous 7 day Date

Calendar currentDate = Calendar.getInstance();
        Calendar prevDay = (Calendar) currentDate.clone();
        prevDay.add (Calendar.DAY_OF_YEAR, -7);
        System.out.println ("Previous 7 Day: " + prevDay.getTime());

Sunday, March 31, 2013

Print Collection



OutPut

Tree Map Example!

Keys of tree map: [1, 2, 3, 4, 5, 6, 7]
Values of tree map: [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]
Key: 5 value: Thursday

First key: 1 Value: Sunday

Last key: 7 Value: Saturday

Removing first data: Sunday
Now the tree map Keys: [2, 3, 4, 5, 6, 7]
Now the tree map contain: [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]

Removing last data: Saturday
Now the tree map Keys: [2, 3, 4, 5, 6]
Now the tree map contain: [Monday, Tuesday, Wednesday, Thursday, Friday]

package com.swain.cell;

import java.util.TreeMap;

public class TreeExample {

       public static void main(String[] args) {
              System.out.println("Tree Map Example!\n");
              TreeMap tMap = new TreeMap();
              tMap.put(1, "Sunday");
              tMap.put(2, "Monday");
              tMap.put(3, "Tuesday");
              tMap.put(4, "Wednesday");
              tMap.put(5, "Thursday");
              tMap.put(6, "Friday");
              tMap.put(7, "Saturday");
              System.out.println("Keys of tree map: " + tMap.keySet());
              System.out.println("Values of tree map: " + tMap.values());
              System.out.println("Key: 5 value: " + tMap.get(5) + "\n");
              System.out.println("First key: " + tMap.firstKey() + " Value: "
                           + tMap.get(tMap.firstKey()) + "\n");
              System.out.println("Last key: " + tMap.lastKey() + " Value: "
                           + tMap.get(tMap.lastKey()) + "\n");
              System.out.println("Removing first data: "
                           + tMap.remove(tMap.firstKey()));
              System.out.println("Now the tree map Keys: " + tMap.keySet());
              System.out.println("Now the tree map contain: " + tMap.values() + "\n");
              System.out
                           .println("Removing last data: " + tMap.remove(tMap.lastKey()));
              System.out.println("Now the tree map Keys: " + tMap.keySet());
              System.out.println("Now the tree map contain: " + tMap.values());
       }

}

How ChatGPT can Benefit Coding: Your Guide to Leveraging an AI Language Model

 Introduction: Hello, coders! Welcome to this blog post on how ChatGPT, an AI language model, can benefit your coding skills and projects. A...