Index

JAVA tagged Questions - Page 1

Sum of the factorial of a number in JAVA


If anyone wants to find the sum of the digits of a number, i.e., 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.

Below is the code in java to find the sum of the digits of a number factorial.

[JAVA]

import java.math.*;
class ClsSum{
public static void main(String[] args)
{
    int sum=0;
    BigInteger bi = new BigInteger("1");
    for(int i=2;i<100;i++)
    {
        bi=bi.multiply(new BigInteger(""+i));
        String s = bi.toString(10);
        for (int i=0; i<s.length();i++)
            sum=sum+Integer.parseInt(""+s.charAt(i));
        System.out.println(sum);
    }
}

How to copy a file from ftp in java


I was writing a core java program to copy a file from the ftp server to my local machine. Just thought of sharing the java code with you all.

[JAVA]

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;


public class Fusion {

/**
* @param args
* @throws IOException
*/
    public static void main(String[] args) throws IOException {

        URL url = new URL("ftp://username:password@ftpserver.com/requiredfile.xls;type=i");
        URLConnection con;
        try {
            con = url.openConnection();

            BufferedInputStream in = new BufferedInputStream(con.getInputStream());
            FileOutputStream out = new FileOutputStream("C:\\out\\requiredfile.xls");

            int i = 0;
            byte[] bytesIn = new byte[1024];
            while ((i = in.read(bytesIn)) >= 0) {
                out.write(bytesIn, 0, i);
            }
            out.close();
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println(e.toString());
            e.printStackTrace();
        }
    }
}
Hope this helps!!!

How to make a class immutable in Java


Immutable means values cannot be changed and mutable means values could be changed. Strings are considered immutable because the values contained in the reference variable cannot be changed. Whereas String Buffer is considered mutable because the value in a string buffer can be changed.

Note: It is similar to System.String and System.StringBuilder in .NET framework

Is it possible to make a user defined type (class) as immutable? Yes, it is possible. We can achieve this by having final modifier and private access modifier members in the final class. The reason for creating it as final class is to avoid overriding.

[JAVA]

// The immutable class ClassImmutable is made final to avoid overriding
final class ClassImmutable
{
    // instances are made private & final to restrict the access outside the class
    private final int age;
    private final double salary;

    // ClassImmutable Constructor
    public ClassImmutable(int paramCount,double paramSalary)
    {
        age = paramAge;
        salary = paramSalary;
    }

    // provide only methods which return the instance values
    public int getAge()
    {
        return salary;
    }

    public double getSalary()
    {
        return salary;
    }
}

// class TestImmutableClass
public class TestImmutableClass
{
    public static void main(String[] args)
    {
        ClassImmutable obj = new ClassImmutable(22,50000);

        System.out.println(obj.getAge());
        System.out.println(obj.getSalary());
    }
}
Hope this helps.

How to write a csv file in java


I am going to share the code to write a csv file in java. Please find the java code snippet to write a CSV file below.

[JAVA]

public static void main(String[] args) {

    String[] array = {"element 1", "element 2", "element 3"};

    try {
        FileWriter fw = new FileWriter(bundle.getString("outputpath"));
        for(int cnt=0; cnt<array.length;cnt++)
        {
            fw.append(array[cnt]);
            fw.append(", ");
            fw.flush();
        }
        fw.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Hope this helps!!!

Manifest file in JAVA


JAR files support a wide range of functionality, including electronic signing, version control, package sealing, and others. What gives a JAR file this versatility? The answer is the JAR file's manifest.

The manifest is a special file that can contain information about the files packaged in a JAR file. By tailoring this "meta" information that the manifest contains, you enable the JAR file to serve a variety of purposes.

When you create a JAR file, it automatically receives a default manifest file. There can be only one manifest file in an archive, and it always has the pathname

META-INF/MANIFEST.MF

When you create a JAR file, the default manifest file simply contains the following:

Manifest-Version: 1.0
Created-By: 1.6.0 (Sun Microsystems Inc.)

These lines show that a manifest's entries take the form of "header: value" pairs. The name of a header is separated from its value by a colon. The default manifest conforms to version 1.0 of the manifest specification and was created by the 1.6.0 version of the JDK.

The manifest can also contain information about the other files that are packaged in the archive. Exactly what file information should be recorded in the manifest depends on how you intend to use the JAR file. The default manifest makes no assumptions about what information it should record about other files.

Founders of Programming Languages


1. Founder Of C Language
"Dennis_Richie"

2. Founder Of C++
"Bjarne_stroustrup"

3. Founder Of Java
"James-GoslingJava"

4. Founder Of JavaScript
"Brendan Eich"

5. Founder Of Ruby
"Yukihiro Matz"

Practical difference between abstract class and interface


Interfaces are rules (Rules because you must give an implementation to them and that you can't ignore or avoid, so that are imposed like rules) which works as a common understanding document among the various teams in software development.

Interfaces give the idea what is to be done but not how it will be done. So implementation completely depends on developer by following the given rules(Means given signature of methods).

Abstract classes may contain abstract declarations, concrete implementations, or both.

Abstract declarations are like rules to be followed and concrete implementations are like guidelines(You can use that as it is or you can ignore it by overriding and giving your own choice implementation to it).

Moreover which methods with same signature may change the behaviour in different context are provided as interface declarations as rules to implement accordingly in different contexts.

 

Example:

 

 

public interface LoginAuth{

   public String encryptPassword(String pass);

   public void checkDBforUser();

}

Now suppose you have 3 databases in your application. Then each and every implementation for that database needs to define the above 2 methods:

 

public class DBMySQL implements LoginAuth{

          // Needs to implement both methods

}

public class DBOracle implements LoginAuth{

          // Needs to implement both methods

}

public class DBAbc implements LoginAuth{

          // Needs to implement both methods

}

But what if encryptPassword() is not database dependent, and it's the same for each class? Then the above would not be a good approach.

 

Instead, consider this approach:

 

public abstract class LoginAuth{

   public String encryptPassword(String pass){

            // Implement the same default behavior here 

            // that is shared by all subclasses.

   }

 

   // Each subclass needs to provide their own implementation of this only:

   public abstract void checkDBforUser();

}

Now in each child class, we only need to implement one method - the method that is database dependent.

 

 

Similar Tags