java for interview

Java has 8 primitive data types: byte, boolean, char, double, short, int, long, float,

Scanner

Yesterday, we discussed Scanner's next, nextLine, hasNext, and hasNextLine methods
Additive Operator
The + operator is used for mathematical addition and String concatenation (i.e.: combining two Strings into one new String). If you add the contents of two variables together (e.g.: a + b),….. System.out.println(a + b);
c++
// eat whitespace
getline(cin >> ws, s2);
#include <iostream>
#include <iomanip>
using namespace std;
int main(int argc, char *argv[]) {
  double pi = 3.14159;
   
  // Let's say we wanted to scale this to 2 decimal places:
  cout << fixed << setprecision(2) << pi << endl;
  printf("%.2f", pi);
}
which produces this output:
3.14
3.14
This is a common problem, and it happens because the nextInt method doesn't read the newline character of your input, so when you issue the command nextLine, the Scanner finds the newline character and gives you that as a line.
A workaround could be this one:
System.out.println("Enter id");
id1 = in.nextInt();
in.nextLine();   // skip the newline character
System.out.println("Enter name");
name1 = in.nextLine();
 

java variable
  • Local variables
  • Instance variables
  • Class/Static variables
Local variable
Local variables are declared in methods, constructors, or blocks.
There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use.
public class Test {
 public void pupAge() {
    int age = 0;
    age = age + 7;
    System.out.println("Puppy age is : " + age);
 }
 public static void main(String args[]) {
    Test test = new Test();
    test.pupAge();
 }
}

Output

Puppy age is: 7
public class Test
{
 public void pupAge()
{
            int age;
           age = age + 7;
            System.out.println("Puppy age is : " + age);
     }
     public static void main(String args[])
{
            Test test = new Test();
            test.pupAge();
     }
}
Output
Test.java:4:variable number might not have been initialized
age = age + 7;
       ^
1 error

Instance Variables

Instance variables are declared in a class, but outside a method, constructor or any block.
Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is null. Values can be assigned during the declaration or within the constructor.
Instance variables can be accessed directly by calling the variable name inside the class.
import java.io.*;
public class Employee
{
     // this instance variable is visible for any child class.
       public String name;
    // salary  variable is visible in Employee class only.
     private double salary;
    // The name variable is assigned in the constructor.
    public Employee (String empName)
{
           name = empName;
     }
    // The salary variable is assigned a value.
     public void setSalary(double empSal)
{
            salary = empSal;
     }
     // This method prints the employee details.
    public void printEmp()
{
           System.out.println("name  : " + name );
            System.out.println("salary :" + salary);
     }
    public static void main(String args[])
{
            Employee empOne = new Employee("Ransika");
            empOne.setSalary(1000);
            empOne.printEmp();
     }
}
This will produce the following result −

Output

name  : Ransika
salary :1000.0

Class/Static Variables

  • Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
  • Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class.
  • Default values are same as instance variables.
       Static variables can be accessed by calling with the class  name ClassName.VariableName.

Example

import java.io.*;
public class Employee
{
     // salary  variable is a private static variable
      private static double salary;
     // DEPARTMENT is a constant
    public static final String DEPARTMENT = "Development ";
 public static void main(String args[])
{
            salary = 1000;
            System.out.println(DEPARTMENT + "average salary:" + salary);
     }
}
This will produce the following result −

Output

Development average salary:1000

Note − If the variables are accessed from an outside class, the constant should be accessed as Employee.DEPARTMENT.
Note:program for calculator
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution
{
    static int solve(String opr)
{
        // String s11=opr;
         int[] a =new int[10];
         int i=0;
         String s = "+";
         String[] st=opr.split("");
         String s1=String.valueOf(st[1]);
         //int[] in=new
              a[0]=Integer.parseInt(st[0]);
         a[2]=Integer.parseInt(st[2]);
         if(s.equals(s1))   
         {
                 i = a[0] + a[2];
         }
         else
         {
                 i = a[0] - a[2];
         }
        return  i;
    }
public static void main(String[] args) {
         Scanner in = new Scanner(System.in);
         String opr = in.next();
         int result = solve(opr);
         System.out.println(result);
         in.close();
    }
}
package com.javatpoint;  
import java.io.FileReader;  
public class FileReaderExample
{  
    public static void main(String args[])throws Exception
{    
               FileReader fr=new FileReader("D:\\testout.txt");    
               int i;  
               while((i=fr.read())!=-1)    
               System.out.print((char)i);    
               fr.close();    
     }  
}
////////////////////////////////////////////////////////


c++ for take input from file.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream infile1;
string s[10],line;
int k=0;
infile1.open("file1.txt");
if(infile1.is_open())
{
 while(!infile1.eof())
 {
            getline(infile1,line);
            s[k]=line;
            k++;
         }  
}

for(int i=0;s[i]!="\0";i++)
{
     cout<<s[i]<<"\n";;
}
//return 0;
}

Strings and Characters

char myChar = 'c'; // create char c
System.out.println("The ASCII value of " + myChar + " is: " + (int) myChar);

Observe the (int) before the variable name in the code above. This is called explicit casting,

To break a String down into its component characters, you can use the String.toCharArray(); method. For example, this code:
String myString = "This is String example.";
char[] myCharArray = myString.toCharArray();
for(int i = 0; i < myString.length(); i++)
{
   // Print each sequential character on the same line
   System.out.print(myCharArray[i]);
}
// Print a newline
System.out.println();
produces this output:
This is String example.
String vs StringBuilder vs StringBuffer in Java
Prerequisites : String , Initialize a String
Consider below code with three concatenation functions with three different types of parameters, String, StringBuffer and StringBuilder.

// Java program to demonstrate difference between String,
// StringBuilder and StringBuffer
class Geeksforgeeks
{
        // Concatenates to String
       public static void concat1(String s1)
      {
           s1 = s1 + "forgeeks";
      }
      // Concatenates to StringBuilder
      public static void concat2(StringBuilder s2)
     {
           s2.append("forgeeks");
     }
     // Concatenates to StringBuffer
     public static void concat3(StringBuffer s3)
     {
           s3.append("forgeeks");
     }
     public static void main(String[] args)
     {
       String s1 = "Geeks";
       concat1(s1);  // s1 is not changed
       System.out.println("String: " + s1);
       StringBuilder s2 = new StringBuilder("Geeks");
       concat2(s2); // s2 is changed
       System.out.println("StringBuilder: " + s2);
       StringBuffer s3 = new StringBuffer("Geeks");
       concat3(s3); // s3 is changed
       System.out.println("StringBuffer: " + s3);
   }
}
Output:
String: Geeks
StringBuilder: Geeksforgeeks
StringBuffer: Geeksforgeeks



Note::
1..
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("How many Inputs??");
int numOfInputs = input.nextInt();
String[] dataStore = new String[numOfInputs];
System.out.println("Input Strings");
for (int i = 0; i < numOfInputs; i++)
{
dataStore[i] = input.next();
System.out.println("Input " + (i + 1) + " = " + dataStore[i]);
}
}
2..
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.nextLine() reads input including space between the words (that is, it reads till the end of line \n).
3..
// Java program to demonstrate conversion from
// String to StringBuffer and StringBuilder.
public class Test
{
   public static void main(String[] args)
   {
       StringBuffer sbr = new StringBuffer("Geeks");
        
       // conversion from StringBuffer object to StringBuilder
String str = sbr.toString();
       StringBuilder sbl = new StringBuilder(str);
        System.out.println(sbl);     
   }
}
Output:
Geeks

Arrays

A type of data structure that stores elements of the same type (generally).
// the number of elements we want to hold
final int _arraySize = 4;

// our array declaration
String[] stringArray = new String[_arraySize];

for(int i = 0; i < _arraySize; i++) {
   // assign value to index i
   stringArray[i] = "This is stored in index " + i;
   
   // print value saved in index i
   System.out.println(stringArray[i]);
}
string concept::
to convert in string array:
String[] st=opr.split("");
to convert from string array to string:
String s1=String.valueOf(st[1]);
compare two string
  1. By equals() method
  2. By = = operator
  3. By compareTo() method

1…………………..

  1. class Teststringcomparison1{  
  2. public static void main(String args[]){  
  3.   String s1="Sachin";  
  4.   String s2="Sachin";  
  5.   String s3=new String("Sachin");  
  6.   String s4="Saurav";  
  7.   System.out.println(s1.equals(s2));//true  
  8.   System.out.println(s1.equals(s3));//true  
  9.   System.out.println(s1.equals(s4));//false  
  10. }  
  11. }  
Output:true
      true
      false
2……………..
class Teststringcomparison2
{  
           public static void main(String args[])
{  
    String s1="Sachin";  
    String s2="SACHIN";  
    System.out.println(s1.equals(s2));//false  
    System.out.println(s1.equalsIgnoreCase(s2));//true  
}  
}  
Test it Now
Output:
false
true
3………………….
  • s1 == s2 :0
  • s1 > s2   :positive value
  • s1 < s2   :negative value
class Teststringcomparison4
{  
public static void main(String args[])
{  
        String s1="Sachin";  
          String s2="Sachin";  
          String s3="Ratan";  
         System.out.println(s1.compareTo(s2));//0  
          System.out.println(s1.compareTo(s3));//1(because s1>s3)  
          System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )  
    }  
}  
Output:
0
1
-1
SPLIT INTO STRING ARRAY
String opr=”hekko”;
String[] st=opr.split("");
we can also write this as a “String[] st=opr.split(“ ”);”
for Integer array:
int[] a =new int[10];
note:
1.System.out.print("Enter Operator (+, -, *, /) : ");
      ch = scan.next().charAt(0);
      
      if(ch == '+')
      {
           res = a + b;
           System.out.print("Result = " +res);
      }
2 d array printing example:
import java.io.*;
import java.util.*;
public class Solution
{

    public static void main(String[] args)
{
           /* Enter your code here. Read input from STDIN. Print output to STDOUT.
           Your class should be named Solution. */
           int i=0,j=0;
           Scanner sc=new Scanner(System.in);
           int n=sc.nextInt();
           String ar[][]=new String[n][n];    //array intialization
           String ar1[][]=new String[n][n];
           for(i=0;i<n;i++)
           {
                   for(j=0;j<n;j++)
                   {
                       ar[i][j]="#";
                   }
           }
           //printing 2 d array
        String s="";  //its important
           for(i=0;i<n;i++)
           {
                   for(j=0;j<n;j++)
                   {
                       if(i+j >= n-1)   //condition
                       {
                               System.out.print((s+ar[i][j]).toString());//converting to string and print
                               //s=s+ar[i][j];
                       }
                       else
                       {
                               System.out.print(" ");//if blank in matrix
                       }
                 }
               System.out.println();//for change the line   
       }
  }
}
   #
     ##
           ###
         ####
       #####
     ######
Finding maximum in array
for(int i=0;i<arr.length;i++)
           {
                  if(arr[i]<min)
               {
                       min=arr[i];
               }
           }
when string is printing out do this
            int i = scan.nextInt();
       double d=scan.nextDouble();
       scan.next();
       String s=scan.nextLine();
      System.out.println("String: " + s);
To sort the array in java.
  /* Arrays.sort(ar, Collections.reverseOrder());*/
  int a[]={2,4,6,1,3};
    //Arrays.sort(a,collections.reverseOrder());//not working
        Arrays.sort(a,0,4);
or
Arrays.sort(a);
0 can be replace with “start index” and 4 can be replace with “end index”.
Use This To Calculate The Power
for(int k=0;k<n;k++)
{
if(k==0)
{                       
int l=1;                        
}
    else
{                   
int l=l*2;                          
}
    p=p+b*l;    //focus on this part
    System.out.print(p+" ");
}
Function to calculate power
Math.pow(a,b);              //for a^b
Note
// A Car class
public class Car
{
public static int numGears = 5; // static variable
public int currentGear = 3;  // instance variable
}
// an instance of Car class
Car audi = new Car();
System.out.println(Car.numGears) // prints 5
System.out.println(audi.currentGear) // prints 3
System.out.println(Car.currentGear) // compile error.
System.out.println(audi.numGear) // prints 3 but compiles with a warning
          Example
           int t=sc.nextInt();
       for(int i=0;i<t;i++)
       {
           try
           {
               long x=sc.nextLong();
               System.out.println(x+" can be fitted in:");
               if(x>=-128 && x<=127)System.out.println("* byte");
               //Complete the code
               if(x>=-32768 && x<=32767)System.out.println("* short");
                       if(x>=-Math.pow(2,31) && x<=Math.pow(2,31)-1)System.out.println("* int");//for 2^31
               if(x>=-Math.pow(2,64) && x<=Math.pow(2,64)-1)System.out.println("* long");
              }
              catch(Exception e)
             {
               System.out.println(sc.next()+" can't be fitted anywhere.");
            }
Note:
1….
The length of an array is available as
int l = array.length;
The size of a List is availabe as
int s = list.size();
2….
class Person {
   protected String firstName;
   protected String lastName;
   protected int idNumber;
   
   // Constructor
   Person(String firstName, String lastName, int identification){
      this.firstName = firstName;
      this.lastName = lastName;
      this.idNumber = identification;}
////////////////////////////////////////
class Student extends Person{
   private int[] testScores=new int[1000];
    int sum=0;
    String firstName=null,lastName=null;
    int id=0;
    Student(String firstName,String lastName,int id,int[] testScores)
    {
        super(firstName,lastName,id);
3…….
initialization of charecter
char c = '\0';
Super Class
The class whose features are inherited is known as super class(or a base class or a parent class.
4….
int num = 10;
   
This_Example()
 {
     System.out.println("This is an example program on keyword this");   
 }

  This_Example(int num)
  {
        // Invoking the default constructor
         this();
    this.num=num;
  }
    public void greet()
   {
        System.out.println("Hi Welcome to Tutorialspoint");
   }
  this.greet(); //use to call same class method
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
import java.util.*;
abstract class Book
{
    String title;
    String author;
            Book(String title, String author)
{
           this.title = title;
           this.author = author;
    }
   
    abstract void display();
}
class MyBook extends Book
{
int price=0;
    MyBook(String title,String author,int price)
           {
           super(title,author);
     
           this.price=price;
    }
    void display()
    {
           System.out.print("Title: "+title+"\nAuthor: "+author+"\nPrice: "+price);
    }

}
public class Solution
{
    public static void main(String[] args)
{
           Scanner scanner = new Scanner(System.in);
           String title = scanner.nextLine();
           String author = scanner.nextLine();
           int price = scanner.nextInt();
           scanner.close();

           Book book = new MyBook(title, author, price);
           book.display();
    }
}
To check alphabet is character or not…
String s = "BC+D*E-=";
for (int i = 0; i < s.length(); i++)
{
       char charAt2 = s.charAt(i);
       if (Character.isLetter(charAt2))
      {
           System.out.println(charAt2 + "is a alphabet");
      }
}
Note:
public class Test
{
      public static void main(String args[])
       {
             System.out.println("She said \"Hello!\" to me.");
       }
}
output:
She said "Hello!" to me.
selection sort   (     o(n^2)      )
public static void selectionSort(int[] arr)
{  
       for (int i = 0; i < arr.length - 1; i++)  
       {
           int index = i;  
           for (int j = i + 1; j < arr.length; j++)
            {
                  if(arr[j] < arr[index])
                 {
                      index = j;//searching for lowest index  
                   }
           }
           int smallerNumber = arr[index];   
           arr[index] = arr[i];  
           arr[i] = smallerNumber;  
       }
  }
Bubble Sort
for(int i=0;i<n;i++)
       {
            int swap=0;
           for(int j=0;j<n-1;j++)
           {
               if(a[j]>a[j+1])
               {
                   //swap
                   int temp=a[j];
                   a[j]=a[j+1];
                   a[j+1]=temp;
                   t++;
                   swap++;
                      
               }
           }
           if(swap==0)
           break;
           
       }
To round Off integer to 1 decimal digit
double d = (double) Math.round((double)k/c * 10) / 10;

Post Order_pre order_inOrder
void inOrder(Node root)
{
if(root!=null)
{
           inOrder(root.left);
           System.out.print(root.data+" ");
           inOrder(root.right);
}
}
Link List concept:level 0
public class MergeLinkList
{
    Node head1;
    Node head2;
    class Node
    {
           Node next;
                int data;
    }  
    void add1(int d1)
    {
          // Node a=new Node();
           if(head1==null)
           {
                   head1=new Node();
                   head1.data=d1;
                   head1.next=null;
           }
           else
           {
                   Node a=new Node();
                   a=head1;
                   a.data=head1.data;
                   while(a.next!=null)
                   {
                           a=a.next;
                   }
         
                   Node b=new Node();
                   b.data=d1;
                   b.next=null;
                          a.next=b;
           }

Mean Median Mode







User created exception
Insertion sort

           for(int i=1;i<n;i++)
           {
               for(int j=0;j<i;j++)
               {
                       if(arr[i]<arr[j])
                       {
                               int temp=arr[i];
                               arr[i]=arr[j];
                               arr[j]=temp;
                                    }
                }
           }
Questition while loop  going to -1 special case
Note:
If return type of function is not void then to exit from program use “System.exit(0) ;”’
If return type of function is void then to return use “return;”
To find element which occur maximum no  in a array
static int migratoryBirds(int n, int[] ar)
{
int p=0;
Arrays.sort(ar);
       int k=1;
       int s=0;
           for(int j=0;j<ar.length-1;j++)
           {
               if(ar[j]==ar[j+1])
               {
                       k++;
               }
               else
               {              k=1; }
               if(k>p)
               {
                      s=ar[j];
                       p=k;
               }
       }
return s;
}
Method to calculate GCD
static int gcd(int a,int b)
{
       int b1=0,a1=0;
//MAKING POSITIVE FROM NEGATIVE
       if(b<0)
       {
               b1=-b;
       }
       else
       {
               b1=b;
       }
       if(a<0)
       {
               a1=-a;
       }
       else
       {
               a1=a;
       }
                      //GCD CONCEPT
       if(b1==0 )
       {
         
               return a1;
         
       }
       else
       {
               int r=a1-a1/b1*b1;
               return gcd(b1,r);
       }
     
}
Time Conversion
12:00:00 PM=00:00:00
12:00:00 PM=12:00:00
Program will terminate while end-of-file(EOF)
import java.io.*;
import java.util.*;
public class Solution
{
public static void main(String[] args) throws Exception
{
           //Scanner sc=new Scanner(System.in);
               BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
           String str="";
           int i=0;
           while((str=in.readLine())!=null)
           {
                  i++;
                  System.out.println(i+" "+str);
                 // str=in.readLine();   
}      
    }
}
Note:Same concept like above using nextLine()
         String str=null;                 
         int i=0;
        while((str=sc.nextLine())!=null)
       {
i++;                     
System.out.println(i+" "+str);
       }
hasNext() example with List

http://hajsoftutorial.com/wp-content/uploads/2014/12/071.png
Note
hasNext()
Returns true if this scanner has another token in its input.

hasNextLine()
Returns true if there is another line in the input of this scanner.
CURRENCY CONVERTER PROGRAM
import java.util.*;
import java.text.*;

public class Solution {
   
    public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
       double payment = scanner.nextDouble();
       scanner.close();
      NumberFormat us     = NumberFormat.getCurrencyInstance(Locale.US);
      NumberFormat india = NumberFormat.getCurrencyInstance(new Locale("en", "in"));
      NumberFormat china  = NumberFormat.getCurrencyInstance(Locale.CHINA);
      NumberFormat france = NumberFormat.getCurrencyInstance(Locale.FRANCE);

   
       System.out.println("US: "     + us.format(payment));
      System.out.println("India: "  + india.format(payment));
       System.out.println("China: "  + china.format(payment));
       System.out.println("France: " + france.format(payment));
     
    }
}
String method  “String.endsWith(“helll”);”
public class EndsWithExample
{
      public static void main(String args[])
     {
         String str1 = new String("This is a test String");
          String str2 = new String("Test ABC");
          boolean var1 = str1.endsWith("String");
          boolean var2 = str1.endsWith("ABC");
          boolean var3 = str2.endsWith("String");
          boolean var4 = str2.endsWith("ABC");
          System.out.println("str1 ends with String: "+ var1);
          System.out.println("str1 ends with ABC: "+ var2);
          System.out.println("str2 ends with String: "+ var3);
          System.out.println("str2 ends with ABC: "+ var4);
  }
}
Note
String are immutable in Java. You can't change them.
You need to create a new string with the character replaced.
String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);
Or you can use a StringBuilder:
StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');

System.out.println(myName);
String example with Character.toUpperCase(‘A’) TO CHECK ALL 
ALPHABET OF ENGLISH IN STRING OR NOT
import java.io.*;        import java.util.*;   import java.text.*; import java.math.*;                             
   import java.util.regex.*;
public class Solution {
    public static void main(String args[] ) throws Exception
{
           Scanner sc=new Scanner(System.in);
           String s=sc.nextLine();
           String[] s1=s.split(" ");
           String s2="";
           String s4="";
           for(int i=0;i<s1.length;i++)
           {
                   String s3=String.valueOf(s1[i]);
                               s2=s2+s3;
           }
           //converting to lower case
           for(int i=0;i<s2.length();i++)
           {
                   char a=Character.toLowerCase(s2.charAt(i));
                   String s3=String.valueOf(a);
                   s4=s4+s3;
             }
          // System.out.println(s4);
           String[] s5=s4.split("");
           //shorting character of string
           Arrays.sort(s5);
           s2="";
          // System.out.println(s4);
           for(int i=0;i<s5.length;i++)
           {
                   String s3=String.valueOf(s5[i]);
                   s2=s2+s3;
           }
         //  System.out.println(s2);
int j=65;
           int p=0;
           for(int i=0;i<s2.length();i++)
           {
                   char a=Character.toLowerCase((char)(j));
                   char b=Character.toLowerCase(s2.charAt(i));
                  if(a==b)
                   {
                          p++;
                       j++;
                   }
                 if(j==91)
                   {
                           break;
                   }
           }
           if(p!=26)
           {
                   System.out.print("not pangram");
           }
           else
           {
                   System.out.print("pangram");
           }
      }
}
Question for substring
public class Solution
{
    public static void main(String[] args)
{
           Scanner in = new Scanner(System.in);
           String s = in.next();
           int n = in.nextInt();
           for(int a0 = 0; a0 < n; a0++)
           {
                   int x = in.nextInt();
                   // your code goes here
                   //int k=s.length();
                   int x1=0;
                                    //BELOW TWO FOR LOOP TO FIND ALL SUBSTRING
                   for(int i=0;i<s.length();i++)
                   {
                           for(int j=i+1;j<=s.length();j++)
                           {
                                   int p=0;
                                   String s1=s.substring(i,j);
                                   for(int m=0;m<s1.length();m++)
                                   {
                                           p=p+((int)(s1.charAt(m)))-96;
                                      }
                                   if(p==x)
                                   {
                                          // System.out.println(s1);
                                           String[] s2=s.split(s1);
                                           String s3="";
                                           for(int t=0;t<s2.length;t++)
                                           {
                                               s3=s3.concat(String.valueOf(s2[t]));
                                               s="";
                                               s=s3;
                                           }
                                           x1=1;
                                          // System.out.println(s);
                                           break;
                                   }
                            }
                           if(x1==1)
                           {
                                   break;
                           }
                   }
                   if(x1==1)
                   {
                           System.out.println("Yes");
                   }
                   if(x1!=1)
                   {
                           System.out.println("No");
                   }
            }
     }
}
Input
abccddde
6
1
3
12
5
9
10
Sample Output 0
Yes
Yes
Yes
Yes
No
No


PDF VIEWER     
1...standard deviation
Image result for calculate standard deviation from data set
2...mean means average…..
3...variance=sigma square...
Image result for variance of a number
Note
  • float is represented in 32 bits, with 1 sign bit, 8 bits of exponent, and 23 bits of the significand
     (or what follows from a scientific-notation number: 2.33728*1012; 33728 is the significand).
  • double is represented in 64 bits, with 1 sign bit, 11 bits of exponent, and 52 bits of significand.
gcd and lcm of a number








print all prime no in order of n
check after this last number while printing time..same method like above but focus on scanner..taking less time than above…(nloglogn)......sum of prime no
Array rotation in order(n)

NOTE

Find the sum of contiguous sub-array of length m and sum of sub array is d 
find no of that sub array
static int solve(int n, int[] s, int d, int m){
       // Complete this function
       int temp=0;
       for(int i=0;i<n-(m-1);i++)                //managing array index out of bound exception
       {
               int sum=0;
               for(int j=i;j<i+m;j++)            //concept to move
               {
                       sum=sum+s[j];           
}
               if(sum==d)
               {
                       temp++;
               }
       }
       //System.out.println(temp);
       return temp;
    }

Vector
Output:
capacity is6
new capacity is10
new Capacity is4
Now new capacity is4
new capacity is 7
4
5
7
6.0
4.78
first Element is 4
last Element is 4.78
Element at last4.78
deleted last Element:4.78
Now Element At last 7
Now size is 3

Example 2:
public class satck1
{
   public static void main(String args[])
   {
       Vector<Integer> v=new Vector<Integer>(3);
       v.addElement(new Integer(3));
       v.addElement(new Integer(4));
       System.out.println(v.contains(4));
       Enumeration en1=v.elements();
       while(en1.hasMoreElements())
       {
           System.out.println(en1.nextElement());
       }
       System.out.println("first Element is "+v.firstElement());
       System.out.println("last Element is "+v.lastElement());
       System.out.println(v.elementAt(v.size()-1));
       System.out.println(v.remove(v.size()-1));
       System.out.print(v.size()-1);
   }
}
Output:
run:
true
3
4
first Element is 3
last Element is 4

Comments

  1. useful knowledge shared here. We encourage language book publishing as one of the Best self book publishers in India . get in touch with us if you want to publish programming language book

    ReplyDelete
  2. Great article, thanks for sharing..

    ReplyDelete
  3. Great. We would like to tell you we deliver freshly baked cakes as per your requirements at minimal cost to make your every occasion special. Visit us for
    online birthday cake delivery in Mumbai
    online wedding cake delivery in Mumbai
    online custom cake delivery in Mumbai
    online adult cakes cake delivery in Mumbai

    ReplyDelete

Post a Comment