Saturday, September 3, 2022

Java Entry Level interview questions and answers


Which Java IDE’s do you use at your previous job?

Netbeans, Eclipse, etc.

List some Java keywords(unlike C, C++ keywords)?

Some Java keywords are import, super, finally, etc.

What do you mean by Object?

Object is a runtime entity and it’s state is stored in fields and behavior is shown via methods. Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication.

List the three steps for creating an Object for a class?

An Object is first declared, then instantiated and then it is initialized.


What is a Class?

A class is a blue print from which individual objects are created. A class can contain fields and methods to describe the behavior of an object.

What kind of variables a class can consist of?

A class consist of Local variable

instance variables

class variables.

What is a Local Variable? 

(Local to the method) Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and it will be destroyed when the method has completed.

class Test{ 

   public void pupAge()

      {

      int age = 0;

      age = age + 7;

      System.out.println("Puppy age is : " + age);

}

In the above programme “Age” is a local variable, which means that variable only accessible in side pupAge method. We can’t access the age variable outside the class

What is a Instance Variable?

Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded.class instance

{

    int instacevariable=10;

}


class InstanceVariable

{

    public static void main(String[] args) 

    {

        instance ins = new instance();

        System.out.println(ins.instacevariable);

    }

}

What is a Class or Static Variable?

These are variables declared with in a class, outside any method, with the static keyword.

class staticVariable

{

      static String cname = "Ecalix";

}


public class ClassORStaticVariable {


    public static void main(String[] args) 

    {

    System.out.println(staticVariable.cname);

       

    }

}


What do you mean by Constructor?

Constructor gets invoked when a new object is created. Every class has a constructor. If we do not explicitly write a constructor for a class the java compiler builds a default constructor for that class.

class MyDefaultConstructor 

{

    public MyDefaultConstructor()

    { 

        System.out.println("I am inside default constructor..."); 

    } 

public static void main(String a[])

    MyDefaultConstructor mdc = new MyDefaultConstructor(); 


}

What is Constructor overloading in java?

Constructor overloading in java allows to have more than one constructor inside one Class.
Constructor overloading you have multiple constructor with different signature with only difference that Constructor doesn't have return type in Java.

package com.ecalix.java;


public class Constructor_OverLoading {

   

    int id;

    String name;

    int age;

   

    Constructor_OverLoading(int i,String n)

    {

        id=i;

        name=n;

        System.out.println(id+" "+name);

    }

    Constructor_OverLoading(int i,String n,int a)

    {

        id=i;

        name=n;

        age=a;

        System.out.println(id+" "+name+""+age);

    }

   

    public static void main(String[] args) {

        // TODO Auto-generated method stub

       

        Constructor_OverLoading co = new Constructor_OverLoading(101, "Sai");

        Constructor_OverLoading co1 = new Constructor_OverLoading(102,"Sam",25);

       

    }

}

What is a static variable?

Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.

What do you mean by Access Modifier?

Java provides access modifiers to set access levels for classes, variables, methods and constructors. A member has package or default accessibility when no accessibility modifier is specified.

public: The class/variable/method is accessible and available to all the other objects in the system.

private: The class/variable/method is accessible and available within this class only.

Default: Current class/ current package

Protected:child classes and current package

What do you mean by synchronized?

synchronized used to indicate that a method/Resource can be accessed by only one thread at a time.


Why is String class considered immutable?

The String class is immutable, so that once it is created a String object cannot be changed. Since String is immutable it can safely be shared between many threads ,which is considered very important for multithreaded programming.

Why is StringBuffer called mutable?

The String class is considered as immutable, so that once it is created a String object cannot be changed. If there is a necessity to make alot of modifications to Strings of characters then StringBuffer should be used.

What is the difference between StringBuffer and StringBuilder class?

Use StringBuilder whenever possible because it is faster than StringBuffer. But, if thread safety is necessary then use StringBuffer objects.

Why is StringBuffer called mutable?

The String class is considered as immutable, so that once it is created a String object cannot be changed. If there is a necessity to make alot of modifications to Strings of characters then StringBuffer should be used.

What is finalize() method?

It is possible to define a method that will be called just before an object's final destruction by the garbage collector. This method is called finalize( ), and it can be used to ensure that an object terminates cleanly.

What is an Exception?

An exception is a problem that arises during the execution of a program. Exceptions are caught by handlers positioned along the thread's method invocation stack.

What do you mean by Checked Exceptions?

It is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.

Explain Runtime Exceptions?

It is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.

When throws keyword is used?

If a method does not handle a checked exception, the method must declare it using the throwskeyword. The throws keyword appears at the end of a method's signature.


   public void parent(){

   try{

    child();

   }catch(MyCustomException e){ }

   }



   public void child throws MyCustomException{

    //put some logic so that the exception occurs.


When throw keyword is used?

An exception can be thrown, either a newly instantiated one or an exception that you just caught, by using throw keyword.

public class ThrowAndThrows {


    public static void checkResult(int marks) throws Exception

    {

        if(35 > marks)

        {

            throw new Exception("Student not qualified");

        }

        else

        {

            System.out.println("student qualified");

        }

    }

   

    public static void main(String[] args) throws Exception {

        // TODO Auto-generated method stub

       

        checkResult(40);

       


    }


}

How finally used under Exception Handling?

The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred.

Constants (final) or Final Keyword in java

Constants are variables defined with the modifier final. A final variable can only be assigned once and its value cannot be modified once assigned.

A final primitive variable cannot be re-assigned a new value.

A final instance cannot be re-assigned a new address.

A final class cannot be sub-classed (or extended).

A final method cannot be overridden.



class FinalExample 

{

public static void main(String[] args) {

final int x=100;

          x=200;  // compile time error comes up.

}

}

What is Method Overloading in Java?

Method Overloading is a feature that allows a class to have two or more methods having same name. Method overloading is also known as Static Polymorphism.

Argument lists could differ in –
1. Number of parameters.
2. Data type of parameters.
3. Sequence of Data type of parameters.

class DisplayOverloading  {

    public void disp(char c) {

         System.out.println(c);  }

    public void disp(char c, int num)  {

         System.out.println(c + " "+num);  }   

}

class Sample

{

   public static void main(String args[])

   {

       DisplayOverloading obj = new DisplayOverloading();

       obj.disp('a');

       obj.disp('a',10);

   }

}

What is Method overriding in java

Declaring a method in subclass which is already present in parent class is known as method overriding

class parentAnimal

{

    public void move()

    {

        System.out.println("Animals can move");

    }

   

   

   

}


class childAnimal extends parentAnimal

{

    public void move()

    {

        System.out.println("Child anilmals also can move");

    }

}



public class Overriding {


    public static void main(String[] args) {

        // TODO Auto-generated method stub

        parentAnimal pa = new parentAnimal();

        childAnimal ca = new childAnimal();

        ca.move();

        pa.move();

}


}

What is polymorphism in programming?

Polymorphism is the capability of a method to do different things based on the object that it is acting upon. In other words, polymorphism allows you define one interface and have multiple implementations. 

Following concepts demonstrate different types of polymorphism in java.
1) Method Overloading (Compile time polymorphisam)
2) Method Overriding(Run time polymorphisam)

What is garbage collection in java?

Garbage collection is an automatic memory management feature in many modern programming languages, such as Java and languages in the .NET framework. Languages that use garbage collection are often interpreted or run within a virtual machine like the JVM. In each case, the environment that runs the code is also responsible for garbage collection.

What is Final/ Finally, Finalize?

final: final is a keyword. The variable declared as final should be initialized only once and cannot be changed. Java classes declared as final cannot be extended. Methods declared as final cannot be overridden. 

finally: finally is a block. The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling - it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated. 

Finalize: finalize is a method. Before an object is garbage collected, the runtime system calls its finalize() method. You can write system resources release code in finalize() method before getting garbage collected. 

What is difference between Set and List in Java?

1. List allows duplicates while Set doesn’t allow duplicate elements. All the elements of a Set should be unique if you try to insert the duplicate element in Set it would replace the existing value.

2. List is an ordered collection it maintains the insertion order, which means upon displaying the list content it will display the elements in the same order in which they got inserted into the list.


How to connect with JDBC?

Load drivers in to the memory

public class jdbc {


    public static void main(String[] args) throws SQLException {

    java.sql.Connection conn = null;

        String url ="jdbc:mysql://localhost:3306/";

        String dbName="test";

        String driver="com.mysql.jdbc.Driver";

        String userName="root";

        String passWord="ABCDEF";

       

        try

        {

           

            Class.forName(driver).newInstance();

            conn=DriverManager.getConnection(url+dbName,userName,passWord);

            Statement stmt = (Statement) conn.createStatement();

            ResultSet rs = stmt.executeQuery("select * from users");

           

            while(rs.next())  //it moves the curson to the next line 

            {

            System.out.println(rs.getString(1) + "---" + rs.getString(2) + "---" + rs.getString(3));

            } 

       

          } 

          catch(Exception e)

        {

           

        }

       

        finally {

           

            conn.close();

        }

         }


}

Difference between try/catch and throws clause?


The try block will execute a sensitive code which can throw exceptions

The catch block will be used whenever an exception (of the type caught) is thrown in the try block

The finally block is called in every case after the try/catch blocks. Even if the exception isn't caught or if your previous blocks break the execution flow.

The throw keyword will allow you to throw an exception (which will break the execution flow and can be caught in a catch block).

The throws keyword in the method prototype is used to specify that your method might throw exceptions of the specified type. It's useful when you have checked exception (exception that you have to handle) that you don't want to catch in your current method.


What is system.out.println?

System is a final class from java.lang package.
out is the reference of Print Stream class and a static member of System class.
println is a method of Print Stream class.

What is the tail command in unix?


The tail command reads the final few lines of any text given to it as an input and writes them to standard output 

What is pipe in Unix?

A Unix pipe provides a one-way flow of data.

How do you know, whether java installed in your computer or not?

A: we need to go to command line and check by typing “Java –version” command


What are environments variables?

Environment variables are a set of dynamic named values that can affect the way running processes will behave on a computer.

What is recursion in java?

Recursion is a basic programming technique you can use in Java, in which a method calls itself 

What are the Different ways to get input from the USER?

Buffred reader

Scanner

Data Input stream


How do you reverse a String?  Eg: Ecalix


          String s = "Ecalix";

        StringBuffer sBuffer = new StringBuffer(s);

        sBuffer.reverse();

        System.out.println(sBuffer);


( Or)


          char[] ca = s.toCharArray();

        for(int i=ca.length-1;i>=0;i--)

            System.out.print(ca[i]);


How do you compare 2 Strings in java?

   .equals()


How to split the string?

String s= "Gold:Stocks:Fixed Income:Commodity:Interest Rates";

String[] splits = s.split(":");

System.out.println("splits.size: " + splits.length);


How to convert string to double?

 String to double conversion is by using parseDouble(String str) from Double class. by far this is my preferred method because its more readable and standard way of converting a string value to double. here is an example :

 Double doubleString = Double.parseDouble(toBeDouble);


What is string tokenizer?

The standard java.util.StringTokenizer class is a special type of Enumeration that represents segments of a string, which may be separated by one or more "delimiters". When you construct a StringTokenizer with a comma delimiter, it will identify each word in a comma separated list for instance.


Jre--runtime environment. used for executing .class files(if u have jar files only jre is required )

jdk--has all software to develop java programm and has java compiler and creates .class files

jvm comes bundeled with jre and jdk.does not understand javacode and it understands bytecode.(has both jre and jdk).


WHAT IS STATICBLOCK ?

Static blocks are also called Static initialization blocks . A static initialization block is a normal block of code enclosed in braces, { },

and preceded by the static keyword. Here is an example:


static {

    // whatever code is needed for initialization goes here

}


 A class can have any number of static initialization blocks, and they can appear anywhere in the class body.

The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.

And don’t forget, this code will be executed when JVM loads the class. JVM combines all these blocks into one single static block and then executes.


Explain with example to describe when to use abstract class and interface?


Consider a scenario where all Cars will have 4 tyres and other features can be different.

 In this case any subclass of Car has to have 4 tyres. This is a case where abstract class will be used and a default implementaion for

 tyres will be provided.


public abstract class Car{

 

public abstract String getCarName();


 public final int getNoOfTyres(){

    return 4;

 }


}

Consider a scenario where Cars can have any number of tyres and other features can also be different. In this case interface will be created.

 

public interface Car{

 

public abstract String getCarName();

public abstract int getNoOfTyres();

}

What is multiple inheritance and does java support?

 If a child class inherits the property from multiple classes is known as multiple inheritance.

Java does not allow to extend multiple classes but to overcome this problem it allows to implement multiple Interfaces.


Application server and web server

when a request is sent from the client or webbrowser The Web server handles the incoming request with  data contents, which usually are static web pages such as HTML also webserver matches that request to the application server set up to handle the given Servlet or JSP.

application server interprets the returned data from database by following the business logic, and provides the output to the web server. Finally, the web server sends the result to the web browser.

 

 What is the Difference between jar, ear and war?

.jar files: These files are with the .jar extension. The .jar files contain the libraries, resources and accessories files like property files.

 

.war files: These files are with the .war extension. The war file contains the web application that can be deployed on the any servlet/jsp container.

The .war file contains jsp, html, java script and other files for necessary for the development of web applications.

 

.ear files: WAR(Web module) + JAR(can be EJB module or application client module).

An EAR(Enterprise archive) is a top-level container which contains modules like: EJB modules, web modules, application client modules etc.

What are collections?

Collection is an object that groups multiple elements into a single unit.

Collection used to store,retrive,manipulate elements.


What is a Iterator?

Iterator is used to Traverse thr' elements of a collection from start to end and allows to process each element .Iterator is an interface.


Difference between HashSet and HashMap in Java


Hash Map

Hash Set

HashMap  is a implementation of Map interface

HashSet is an implementation of Set Interface

HashMap Stores data in form of  key value pair

HashSet Store only objects

Put method is used to add element in map

Add method is used to add element is Set

In hash map hashcode value is calculated using key object

Here member object is used for calculating hashcode value which can be same for two objects so equal () method is used to check for equality if it returns false that means two objects are different.

HashMap is faster than hashset because unique key is used to access object

HashSet is slower than Hashmap



Difference between set,and list?

Set-unordered collection,does not allow duplicates

list is ordered,allows duplicates.


Difference between linkedlist and arraylist?

Linked list searches by traversing end to end traversing sequentially it fast.

arraylist seraches index based ArrayList is much faster than a LinkedList for random access


Difference between Abstract Class and Interface in Java?

abstract Classes

Interfaces

 abstract class can extend only one class or one abstract class at a time

 interface can extend any number of interfaces at a time

 abstract  class  can extend from a class or from an abstract class

 interface can extend only from an interface

 abstract  class  can  have  both  abstract and concrete methods

 interface can  have only abstract methods

 A class can extend only one abstract class

 A class can implement any number of interfaces

 In abstract class keyword ‘abstract’ is mandatory to declare a method as an abstract

 In an interface keyword ‘abstract’ is optional to declare a method as an abstract

 abstract  class can have  protected , public and public abstract methods

 Interface can have only public abstract methods i.e. by default

 abstract class can have  static, final  or static final  variable with any access specifier

 interface  can  have only static final (constant) variable i.e. by default


What is Abstract Classes and Methods in Java?

A class that is declared using “abstract” keyword is known as abstract class. It may or may not include abstract methods which means in abstract class you can have concrete methods (methods with body) as well along with abstract methods ( without an implementation, without braces, and followed by a semicolon). An abstract class can not be instantiated (you are not allowed to create object of Abstract class).

abstract public class AbstractDemo{

   public void myMethod(){

      System.out.println("Hello");

 }

   abstract public void anotherMethod();

}

public class ConcreteDemo{


   public void anotherMethod() { 

        System.out.print("Abstract method"); 

   }

   public static void main(String args[])

   { 

      //Can't create object of abstract class - error!

      AbstractDemo obj = new AbstractDemo();

      obj.display();

   }

}


What is Interface in java?

Interface looks like class but it is not a class. An interface can have methods and variables just like the class but the methods declared in interface are by default abstract (only method signature, no body). Also, the variables declared in an interface are public, static & final by default.

What is the use of interfaces?

are used for abstraction. Since methods in interfaces do not have body, they have to be implemented by the class before you can access them. The class that implements interface must implement all the methods of that interface. Also, java programming language does not support multiple inheritance, using interfaces we can achieve this as a class can implement more than one interfaces, however it cannot extend more than one classes.

Sample programme using Interfaces:-

interface MyInterface

{

   public void method1();

   public void method2();

}

class XYZ implements MyInterface

{

  public void method1()

  {

      System.out.println("implementation of method1");

  }

  public void method2()

  {

      System.out.println("implementation of method2");

  }

  public static void main(String arg[])

  {

      MyInterface obj = new XYZ();

      obj. method1();

  }

}

What is Inheritance in Java Programming?

Inheritance allows a class to use the properties and methods of another class. In other words, the derived class inherits the states and behaviors from the base class. The derived class is also called subclass and the base class is also known as super-class. The derived class can add its own additional variables and methods. These additional variable and methods differentiates the derived class from the base class.


Sample Programme Using Inheritance:-

class Vehicle

{

    String color;

    int speed;

    int size;

   

    public void attributes()

    {

        System.out.println("color="+color);

        System.out.println("speed="+speed);

        System.out.println("size="+size);

       

    }

}


class car extends Vehicle

{

    int cc;

    int gears;

    public void carattributes()

    {

        System.out.println("color="+color);

        System.out.println("speed="+speed);

        System.out.println("size="+size);

        System.out.println("cc="+cc);

        System.out.println("gears="+gears);

    }

}



    public class Sample2Inheritance {

      public static void main(String args[]) {

           

          car c = new car();

          c.color="red";

          c.speed=20;

          c.size=5;

          c.cc=180;

          c.gears=4;

                   

          c.carattributes();

           

      }

    }

What is Encapsulation in Java?

The whole idea behind encapsulation is to hide the implementation details from users. If a data member is private it means it can only be accessed within the same class. No outside class can access private data member (variable) of other class.

class Encapsulation

{

    public int empID;

    public String eName;

    public int eSal;

   

    public int getempID()

    {

        return empID;

    }

   

    public String geteName()

    {

        return eName;

       

    }

    public int geteSal()

    {

        return eSal;

    }

   

    public void setempID(int id)

    {

        empID = id;

    }

   

    public void seteName(String name)

    {

        eName = name;

    }

   

    public void seteSal(int sal)

    {

        eSal = sal;

    }

   

   

   

}


public class Example_Encapsulation {


    public static void main(String[] args) {

        // TODO Auto-generated method stub

        Encapsulation1 obj = new Encapsulation1();

        obj.setempID(101);

        obj.seteName("AAA");

        obj.seteSal(2500);

       

        System.out.println(obj.getempID());

        System.out.println(obj.geteName());

        System.out.println(obj.geteSal());

       

       

    }


}



What does each term in "public static void main(String[] args)" mean?

"public" means that main() can be called from anywhere.
"static" means that main() doesn't belong to a specific object
"void" means that main() returns no value
"main" is the name of a function. main() is special because it is the start of the program.
"String[]" means an array of String.
"args" is the name of the String[] (within the body of main()). "args" is not special; you could name it anything else and the program would work the same.

What is synchronization?

Synchronised means that in a multiple threaded environment, a synchronised object does not let two threads access a method/block of code at the same time. 

The second thread will instead wait until the first is done. The overhead is speed, but the advantage is guaranteed consistency of data.


Java Collections:-

What is Java Collection API?

The collection API is a Architecture for representing and manipulating collections

ArrayList:  List is an interface and ArrayList is an implementation of List interface - 

package com.nlsinc.priyanka.collections;


import java.util.ArrayList;


public class arrayList {


    public static void main(String[] args) {

        ArrayList<Integer> numbers= new ArrayList<Integer>();

        numbers.add(10);

        numbers.add(100);

        numbers.add(1012);

       

        System.out.println(numbers.get(1));

       

        for(int i=0;i<numbers.size();i++)

        {

            System.out.println(numbers.get(i));

        }

        System.out.println("removed num is"+numbers.remove(2));

    }


}



Diffrence between ArrayList and LinkedList:-


Array List : If you want to add or remove items only at end use ArrayList  (Random)

Linked list: If you want to add remove items any where use Linked list (sequential access)


package com.nlsinc.priyanka.collections;


import java.util.LinkedList;


public class SamplelinkedList 

{

    public static void main(String[] args) 

    {


        LinkedList<String> ll= new LinkedList();

        ll.add("sai");

        ll.add("baba");

        ll.add("rama");

        ll.add("Sita");

        ll.add("Hanuman");

       

        System.out.println(ll.get(0));

        System.out.println(ll.size());

        System.out.println(ll.isEmpty());

       

        System.out.println(ll.contains("venkateshwara"));

       

        //using for loop

        for(int i =0;i<ll.size();i++)

        {

            System.out.println(ll.get(i));

        }

        }

}



LinkedList Programme using Iterator:

package com.java2novice.linkedlist;

 

import java.util.Iterator;

import java.util.LinkedList;

 

public class MyLinkedListIterate {

 

    public static void main(String a[]){

        LinkedList<String> arrl = new LinkedList<String>();

        //adding elements to the end

        arrl.add("First");

        arrl.add("Second");

        arrl.add("Third");

        arrl.add("Random");

        Iterator<String> itr = arrl.iterator();

        while(itr.hasNext()){

            System.out.println(itr.next());

        }

    }

}


Remove Items from LinkedList:

package com.java2novice.linkedlist;

 

import java.util.LinkedList;

 

public class ClearMyLinkedList {

 

    public static void main(String a[]){

         

        LinkedList<String> arrl = new LinkedList<String>();

        //adding elements to the end

        arrl.add("First");

        arrl.add("Second");

        arrl.add("Third");

        arrl.add("Random");

        System.out.println("Actual LinkedList:"+arrl);

        arrl.clear();

        System.out.println("After clear LinkedList:"+arrl);



Arr1.push = inserting the ele in to the array

Arr1.pop = removing ele in to the array

arrl.addFirst("I am first"); // adding the ele in first of linked list

    }

}


HashTable using Enumaration


Hash table using key and value combination

Hash table doesn’t allow null values as key 

Synchronized

Uses enumerator to traverse



package com.java2novice.hashtable;

 

import java.util.Enumeration;

import java.util.Hashtable;

 

public class MyHashtableEnumaration {

 

public static void main(String a[]){

         

        Hashtable<String, String> hm = new Hashtable<String, String>();

        //add key-value pair to Hashtable

        hm.put("first", "FIRST INSERTED");

        hm.put("second", "SECOND INSERTED");

        hm.put("third","THIRD INSERTED");

        

        Enumeration<String> keys = hm.keys();

        while(keys.hasMoreElements()){

            String key = keys.nextElement();

            System.out.println("Value of "+key+" is: "+hm.get(key));

        }

    }

}

HASH MAP:

Un synch ronized

Allow null values and null key values

Use iterator


 class MyBasicHashMap {

 

    public static void main(String a[]){

        HashMap<String, String> hm = new HashMap<String, String>();

        //add key-value pair to hashmap

        hm.put("first", "FIRST INSERTED");

        hm.put("second", "SECOND INSERTED");

        hm.put("third","THIRD INSERTED");

        System.out.println(hm);

        //getting value for the given key from hashmap

        System.out.println("Value of second: "+hm.get("second"));

        System.out.println("Is HashMap empty? "+hm.isEmpty());

        hm.remove("third");

        System.out.println(hm);

        System.out.println("Size of the HashMap: "+hm.size());

    }

}


HASH SET: set does not allow duplicates

If You enter duplicate values, it overrites duplicate values

Set is un sorted 

package com.java2novice.hashset;

 

import java.util.HashSet;

 

public class MyBasicHashSet {

 

    public static void main(String a[]){

        HashSet<String> hs = new HashSet<String>();

        //add elements to HashSet

        hs.add("first");

        hs.add("second");

        hs.add("third");

        System.out.println(hs);

        System.out.println("Is HashSet empty? "+hs.isEmpty());

        hs.remove("third");

        System.out.println(hs);

        System.out.println("Size of the HashSet: "+hs.size());

        System.out.println("Does HashSet contains first element? "+hs.contains("first"));

    }

}


How do you convert STRING TO DATE?


        String s="12/08/2006";

        SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");

        Date sd=formatter.parse(s);

        System.out.println(sd);

       

How do you convert DATE TO STRING?


Date d= 12/08/2006;

SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");

        String f=formatter.format(sd);

        System.out.println(f);

 































































No comments:

Post a Comment