How to Convert string to date in java


  • Whenever are having a requirement of converting string (date as string ) in to date we need to use SimpledateFormat class which is present in java.text package.
  • To convert string to date in java we need to follow two steps.
  • First we need to create SimpledateFormat class object by passing pattern of date which we want as a string.
  • Ex: SimpleDateFormat  formatter = new SimpleDateFormat("dd/MM/yyyy");
  • And next we need to call parse() method on the object of  SimpleDateFormat then it will returns Date object.
  • parse() method  throws ParseException so need to handle this exception.
  • By using format method of the object will get string format of given date
  • formatter.format(date).
  • How to convert java string to date object 
  • Java SimpleDateFormat String to Date conversion and parsing examples
Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 2015; 15
Y Week year Year 2009; 09
M Month in year Month July; Jul;07
w Week in year Number 25
W Week in month Number 3
D Day in year Number 143
d Day in month Number 37
F Day of week in month Number 1
E Day name in week Text Tuesday; Tue
u Day number of week (1 = Monday, ..., 7 = Sunday) Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 12
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 30
S Millisecond Number 778
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00
(Ref: Oracle DOCS)

Example program on SimpleDateFormat :

1. Convert string to date in java in MMM dd, yyyy format

Input : Jan 1, 2015 (MMM dd, yyyy):

  1. package com.instanceofjava;
  2.  
  3. public Class DateFormatDemo{ 
  4.  
  5. public static void main (String args[]) {
  6. SimpleDateFormat formatter = new SimpleDateFormat("MMM dd, yyyy");
  7. String dateInString = "Jan 1, 2015"; 
  8.  
  9. try{
  10.  
  11. Date date = formatter.parse(dateInString);
  12. System.out.println(date);
  13. System.out.println(formatter.format(date));  
  14.  
  15. }catch(ParseException e){
  16. e.printStackTrace();
  17. }
  18. }

  19. Output: 
  20. Thu Jan 01 00:00:00 IST 2015
  21. Jan 01, 2015




2.How to convert string into date format in java day MMM dd, yyyy format example

 Input : Sat, Feb 14 2015 (E, MMM dd yyyy):

  1. package com.instanceofjava;
  2.  
  3. public Class DateFormatDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7. SimpleDateFormat formatter = new SimpleDateFormat("E, MMM dd yyyy");
  8. String dateInString = "Sat, February 14 2015"; 
  9.  
  10. try{
  11.  
  12. Date date = formatter.parse(dateInString);
  13. System.out.println(date);
  14. System.out.println(formatter.format(date));  
  15.  
  16. }catch(ParseException e){
  17. e.printStackTrace();
  18. }
  19. }
  20. }
  21. Output: 
  22. Sat Feb 14 00:00:00 IST 2015
  23. Sat, Feb 14 2015



3. Convert string to date in java in dd/MM/ yyyy format example program

Input : 01/01/2015 (dd/MM/yyyy):

  1. package com.instanceofjava;
  2.  
  3. public Class DateFormatDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7. SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy);
  8. String dateInString = "01/01/2015";
  9.  
  10. try{
  11.  
  12. Date date = formatter.parse(dateInString);
  13. System.out.println(date);
  14. System.out.println(formatter.format(date)); 
  15.  
  16. }catch(ParseException e){
  17. e.printStackTrace();
  18. }
  19. }

  20. Output: 
  21. Thu Jan 01 00:00:00 IST 2015
  22. 01/01/2015


4. Convert string to date in java in dd-MMM-yyyy format example program

Input : 1-Jan-2015 (dd-MMM-yyyy):

  1. package com.instanceofjava;
  2.  
  3. public Class DateFormatDemo{ 
  4.  
  5. public static void main (String args[]) {
  6. SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
  7. String dateInString = "1-Jan-2015"; 
  8.  
  9. try{
  10.  
  11. Date date = formatter.parse(dateInString);
  12. System.out.println(date);
  13. System.out.println(formatter.format(date));  
  14.  
  15. }catch(ParseException e){
  16. e.printStackTrace();
  17. }
  18. }

  19. Output: 
  20. Thu Jan 01 00:00:00 IST 2015
  21. 01-Jan-2015


  5. Convert string to date in java in yyyyMMdd format example program

Input : 20150101 (yyyyMMdd):

  1. package com.instanceofjava;
  2.  
  3. public Class DateFormatDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7. SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
  8. String dateInString = "20150101"; 
  9.  
  10. try{
  11.  
  12. Date date = formatter.parse(dateInString);
  13. System.out.println(date);
  14. System.out.println(formatter.format(date));  
  15.  
  16. }catch(ParseException e){
  17. e.printStackTrace();
  18. }
  19. }

  20. Output: 
  21. Thu Jan 01 00:00:00 IST 2015
  22. 20150101


6.Convert string to date in java in ddMMyyyy format example program

Input : 01012015 (ddMMyyyy):

  1. package com.instanceofjava;
  2.  
  3. public Class DateFormatDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7. SimpleDateFormat formatter = new SimpleDateFormat("ddMMyyyy");
  8. String dateInString = "01012015"; 
  9.  
  10. try{
  11.  
  12. Date date = formatter.parse(dateInString);
  13. System.out.println(date);
  14. System.out.println(formatter.format(date));  
  15.  
  16. }catch(ParseException e){
  17. e.printStackTrace();
  18. }
  19. }

  20. Output: 
  21. Thu Jan 01 00:00:00 IST 2015
  22. 01012015


7.Convert string to date in java in dd-MMM-yy format example program

Input : 01-January-15 (dd-MMM-yy):

  1. package com.instanceofjava;
  2.  
  3. public Class DateFormatDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7. SimpleDateFormat formatter = new SimpleDateFormat("dd-MMMM-yy");
  8. String dateInString = "01-January-2015"; 
  9.  
  10. try{
  11.  
  12. Date date = formatter.parse(dateInString);
  13. System.out.println(date);
  14. System.out.println(formatter.format(date));  
  15.  
  16. }catch(ParseException e){
  17. e.printStackTrace();
  18. }
  19. }

  20. Output: 
  21. Thu Jan 01 00:00:00 IST 2015
  22. 01012015


8.Convert string to date in java in dd-M-yyyy HH:mm:SS format example program

 
convert string to date in java

JVM Architecture

  • This topic clears your questions like Explain jvm architecture in java  , jvm architecture in java with diagram, how JVM works internally and areas of Java Virtual Machine.
  • Virtual machine : In general terms Virtual machine is a software that creates an environment between the computer and end user in which end user can operate programs.
  • As per functionality Virtual machine is creation of number of different identical execution environments on a single computer to execute programs is called Virtual machine.
  • Java Virtual machine: it is also Virtual machine that runs java bytecode  by creating five identical run time areas to execute class members.

Function of java virtual machine

  • The bytecode is generated by java compiler in a JVM understandable format.
  • As a programmer we develop a java application and when we compile a java program, the compiler will generate .class (dot class) file.
  • The .class file contains byte code (Special java instructions).
  • To execute a java program we take the help of JVM (java virtual machine) to the JVM we have to provide .class file as the input.

Types of JVMs:

  • The java 2 SDK , Standard Edition , contains two implementation of the java virtual machine 
  1. Java HotSpot Client VM
  2. Java Hotspot Server VM

Java HotSpot Client VM:

  • The Hotspot Client VM is the default virtual machine of the java 2 SDK and java 2 run time environment .
  • As its name implies, it is tuned for best performance when running applications in a client environment by reducing application start up time and memory footprint.  

Java HotSpot Server VM:

  • The java HotSpot server VM is designed for maximum program execution speed for applications running in a server environment.
  • The Java HotSpot Server VM is invoked by using the server command line option when an application , as in java server MyApp.
  • Some of the features java HotSpot technology , common to both VM implementations, are the following.

Adaptive compiler:

  • Applications are launched using a standard interpreter, but the code is then analyzed as it runes to detect performance bottlenecks, or "hot spots".
  • The Java HotSpot VMs compile those performance critical portions of the code for a boost in performance , while avoiding unnecessary compilation of seldom used code.
  • The Java HotSpot VMs also uses the adoptive compiler to decide on the fly , how best to optimize compiled code with techniques such as in lining.
  • The run time analysis performed by the compiler allows it to eliminate guesswork in determining which optimizations will yield the largest performance benefit.

Rapid memory allocation garbage collection:

  • Java HotSpot technology provides for rapid memory allocation for objects , and it has a fast, efficient, state-of-the-art  garbage collector. 

Thread Synchronization:

  • The Java programming language allows for use of multiple , concurrent paths of program execution (called threads).
  • Java HotSpot technology provides a thread- handling capability that is designed to scale readily for use in large , shared memory multiprocessor servers.

Jvm architecture in java with diagram





Class Loader Sub System:     

  • The class loader sub system will take a .class file as the input and performance the following operations. 
  • The class loader sub system is responsible for loading the .class file (Byte code) into the JVM.
  • Before loading the Byte code into the JVM it will verify where there the Byte code is valid      or   not. This verification will be done by Byte code verifier.
  • If the Byte code is valid then the memory for the Byte code will be allocated in different areas.
  • The different areas into which the Byte code is loaded are called as Run Time Data Areas. The various run time data areas are.


1.Method Area: 

  • Java Virtual Machine Method Area can be used for storing all the class code and method code.
  • All classes bytecode is loaded and stored in this run time area , and all static variables are created in this area.

2.Heap Memory:

  • JVM Heap Area can be used for storing all the objects that are created.
  • It is the main memory of JVM , all objects of classes :- non static variables memory are created in this run time area.
  • This runtime  area memory is finite memory.
  • This area can be configured at the time of setting up of runtime environment using non standard option like
  • java -xms <size> class-name.
  • This can be expandable by its own , depending on the object creation.
  • Method area and Heap area both are sharable memory areas.

3.Java Stack area:

  • JVM stack Area can be used for storing the information of the methods. That is under execution. The java stack can be considered as the combination of stack frames where every frame will contain the stat of a single method.
  • In this runtime area all Java methods are executed.
  • In this runtime JVM by default creates two threads. they are
  • 1.main method
  • 2.Garbage Collection Thread
  •  main thread responsible to execute java methods starts with main method.
  • Also responsible to create objects in heap area if its finds new keyword in any method logic.
  • Garbage collection thread is responsible to destroy all unused objects from heap area.

4.PC Register (program counter) area:

  • The PC Register i Java Virtual Machine will contain address of the next instruction that have to be executed.

5.Java Native Stack:   

  • Java native stack area is used for storing non-java coding available in the application. The non-java code is called as native code.

  

Execution Engine:

  • The Execution Engine of JVM is Responsible for executing the program and it contains two parts.
  1. Interpreter.
  2. JIT Compiler (just in time compiler).
  • The java code will be executed by both interpreter and JIT compiler simultaneously which will reduce the execution time and them by providing high performance. The code that is executed by JIT compiler is called as HOTSPOTS (company).
  



Java programming interview questions

  1. Java Program to Print prime numbers? 
  2. What happens if we place return statement in try catch blocks 
  3. Write a java program to convert binary to decimal 
  4. Java Program to convert Decimal to Binary
  5. Java program to restrict a class from creating not more than three objects
  6. Java basic interview programs on this keyword 
  7. Interfaces allows constructors? 
  8. Can we create static constructor in java 
  9. Super keyword interview questions java 
  10. Java interview questions on final keyword
  11. Can we create private constructor in java
  12. Java Program Find Second highest number in an integer array 
  13. Java interview programming questions on interfaces 
  14. Top 15 abstract class interview questions  
  15. Java interview Questions on main() method  
  16. Top 20 collection framework interview Questions
  17. Java Interview Program to find smallest and second smallest number in an array 
  18. Java Coding Interview programming Questions : Java Test on HashMap  
  19. Explain java data types with example programs 
  20. Constructor chaining in java with example programs 
  21. Swap two numbers without using third variable in java 
  22. Find sum of digits in java 
  23. How to create immutable class in java 
  24. AtomicInteger in java 
  25. Check Even or Odd without using modulus and division  
  26. String Reverse Without using String API 
  27. Find Biggest substring in between specified character
  28. Check string is palindrome or not?
  29. Reverse a number in java?
  30. Fibonacci series with Recursive?
  31. Fibonacci series without using Recursive?
  32. Sort the String using string API?
  33. Sort the String without using String API?
  34. what is the difference between method overloading and method overriding?
  35. How to find largest element in an array with index and value ?
  36. Sort integer array using bubble sort in java?
  37. Object Cloning in java example?
  38. Method Overriding in java?
  39. Program for create Singleton class?
  40. Print numbers in pyramid shape?
  41. Check armstrong number or not?
  42. Producer Consumer Problem?
  43. Remove duplicate elements from an array
  44. Convert Byte Array to String
  45. Print 1 to 10 without using loops
  46. Add 2 Matrices
  47. Multiply 2 Matrices
  48. How to Add elements to hash map and Display
  49. Sort ArrayList in descending order
  50. Sort Object Using Comparator
  51. Count Number of Occurrences of character in a String
  52. Can we Overload static methods in java
  53. Can we Override static methods in java 
  54. Can we call super class static methods from sub class 
  55. Explain return type in java 
  56. Can we call Sub class methods using super class object? 
  57. Can we Override private methods ? 
  58. Basic Programming Questions to Practice : Test your Skill
  59. Java programming interview questions on collections

Inner classes in java

  • Class inside a class is known as nested class.
  • We will use nested classes to group classes and interfaces at one place for readability and maintainability.
  1. package com.instanceofjava;
  2. public class A{ 
  3.  class B{
  4. // inner class
  5. }
  6. }


  • Inner class is a part of nested class. Non-static nested classes are known as inner classes. 
  • Nested classes are two types
  • Non-static nested class(inner class)
    1. Member inner class
    2. Anonymous inner class
    3. Local inner class
  • Static nested class.

Member inner class:

  •  A class is defined within a class and outside of methods of that class known as member inner class.
  1. package instanceofjavaforus;
  2. public class A{ 
  3.  class B{
  4. public void show(){
  5. }
  6. }
  7. public static void main(String args[]){
  8. A a= new A();
  9. a.B b= a.new B();
  10. b.show();
  11. }
  12. }

 

Anonymous inner class:

  • Anonymous inner class is a inner class which does not have a name and whose instance is created at the time creating class itself.
  • Anonymous inner classes are somewhat different from normal classes in its creation.
  • There are two ways to create in two ways.
    1. Using class.
    2. Using interface.

Using class:

  1. package instanceofjavaforus;
  2. public class A{ 
  3. public void show(){
  4. }
  5. public static void main(String args[]){
  6. A a= new A(){
  7.  public void display(){
  8. System.out.println('anonymous class method');
  9. }
  10. };
  11. a.display();
  12. }
  13. }


  Using interface:

  1. package instanceofjavaforus;
  2. public interface A{ 
  3.  public void show();
  4. }

  1. package instanceofjavaforus;
  2. public class Demo{ 
  3. public static void main(String args[]){
  4. A a= new A(){
  5.  public void show(){
  6. System.out.println('anonymous class method');
  7. }
  8. };
  9. a.show();
  10. }
  11. }

 

Local inner class:

  • A class which is defined inside a method of another class known as local inner class
  1. package instanceofjavaforus;
  2. public class Demo{ 
  3. void create(){
  4. class A{
  5. void show(){
  6. System.out.println("local inner class method");
  7. }
  8. }
  9. A a= new A();
  10. a.show();
  11. }
  12. public static void main(String args[]){
  13. Demo obj= new Demo();
  14.  obj.create();
  15. }
  16. }

 

Static nested class:

  • A static nested class is a class which is defined inside a class as static.
  1. package instanceofjavaforus;
  2. public class Outer{ 
  3.   static class inner{
  4. public void show(){
  5. System.out.println("static inner class method");
  6. }
  7. }
  8. public static void main(String args[]){
  9. Outer.inner in= new Outer.innner();
  10. in.show();
  11. }
  12. }

Top 25 Core java interview questions for freshers

1. what is a transient variable?

  •  A transient variable is a variable that whose value is not going to be serialized

2. What is synchronization?

  • With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources.
  •  Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often leads to significant errors.

3. What’s new with the stop(), suspend() and resume() methods in JDK 1.2? 

  • The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

4. Is null a keyword?

  •  "null"  is not a keyword. .null is a literal.

5. What state does a thread enter when it terminates its processing?

  • When a thread terminates its processing, it enters the dead state.

6. What is the Collections API?

  • The Collections API is a set of classes and interfaces that support operations on collections of objects.

7. What is the List interface?

  • The List interface provides support for ordered collections of objects which allows duplicate elements also.

8. What is the Vector class?

  • The Vector class provides the capability to implement a growable array of objects

9.Can we instantiate Abstract class?

  • We can not create object for abstract class directly. but indirectly through sub class object we can achieve it.

10.What is the first keyword used in a java program?

  • Its "package" keyword.

11.When a class should be defined as final?

  • If we do not want allow subclasses.
  • If we do not want to extend the functionality.

12.Can we declare abstract method as static?

  • No, we are not allowed to declare abstract method as static.
  • It leads to compilation error: illegal combination of modifiers abstract and static.

13.Can we apply abstract keyword to interface?

  • Yes, it is optional.
  • abstract interface A{}

14.Can we write empty interface?

  • Yes it is possible it is marker interface.
  • interface A{}

15.Can we declare interface as final?

  • No, it leads to compile time error. Because it should allow sub class.

16.How to solve ClassCastException?

  • To solve  ClassCastException we should use instanceof operator.
  • obj instanceof class_name

17. Is “xyz” a primitive value? 

  • No, it is not primitive it is string literal.

18.When is an object subject to garbage collection? 

  • An object is subject to garbage collection when it becomes unreachable to the program in which it is used.

19.What method must be implemented by all threads? 

  • The run() method, whether they are a subclass of Thread or implement the Runnable interface.


20.What happens if an exception is not caught?

  • An uncaught exception results in the uncaughtException() method of the thread’s ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.

21.How are this() and super() used with constructors?

  • this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

22.Under what conditions is an object’s finalize() method invoked by the garbage collector?

  • The garbage collector invokes an object’s finalize() method when it detects that the object has become unreachable.

23.What restrictions are placed on method overloading? 

  • Methods should have same name  and defer in parameters.

24.When does the compiler supply a default constructor for a class? 

  • The compiler supplies a default constructor for a class if no other constructors are provided.

25.What modifiers can be used with a local inner class?

  • A local inner class may be final or abstract.

For More Questions Check below on your interest:

1. Concept and Interview Program

2. Concept and Interview Questions

3. 0-3 Years Core Java Interview Questions



1. Top 15 Garbage Collection Interview Questions

2. Top 10 Oops Concepts Interview Questions 

3. Top 15 Java Interview Questions on Constructors

4. Top 10 Inheritance Interview Questions

5. Interview Programs on Strings

6. 10 Interesting Core Java Interview Coding Questions and Answers

7. Top 20 Basic Java Interview Questions for Frehsers 

8. Top 10 interview Question on Static keyword. 

9.Top 20 Java interview Questions on Increment and Decrement operators

10.Top 10 Interview Questions on main() method

11. Top 12 Java Experienced interview Programming Questions on Strings

12.Pattern Programs in java Part-1

13.Pattern Programs in java Part-2

14.Pattern Programs in java Part-3 

15. Collection framework interview programming questions 

Access Specifiers/modifiers in java


Access Specifier:

  • To Explicitly mention the way how the data (variables and methods of a class) available to outside.
  • Access specifier is something which mentions the way how the member of a class has to be available to anything outside the class.
  • Access specifiers not not applicable to the local variables.(present inside method).
  • Access specifiers are the keywords using which we can control the accessibility of the members of a class.
  • There are 4 different ways in which we can control the accessibility of the members of a class
  • Thus there are "4" access specifiers and they are,
  1. public
  2. private
  3. protected
  4. default (not a keyword) 
  • if we not specify any keyword that will be considered as default 

Public:

  • The access specifier "public" makes the member of a class available to any location outside of the class.
  • Thus anything mentioned as public would be available to any location outside the class.
  • Means if we have a class with public access specifier then we can use it in other packages also by importing the corresponding package.

  1. package package1;
  2. public Class A{ 
  3. public void show(){
  4. }
  5. public static void main (String args[]) {
  6. }
  7. }

  1. package package2;
  2. import package1.*;
  3. public Class B {
  4. public static void main (String args[]) {
  5. A a = new A();
  6.  a.show();
  7. }
  8. }

Private:

  • Private would not allow the member of class available to any location outside the class.
  • private members would be available only within the same class.
  • Private members of a class would not be available to anything outside the class under any condition.
  • Private members of a class would also be not available to the sub class objects

  1. package package1;
  2. Class A{ 
  3. private void show(){
  4. }
  5. public static void main (String args[]) {
  6. A a= new A();
  7. a.show();
  8. }
  9. }

Default:

  • Any member of class mentioned without any access specifier then its considers that as default .
  • Default will act as "public " within the same package and same path.
  • The same default would act as private outside the package.
  • Default members of any class would be available to anything within the same package and would not be available outside the package under any condition.

  1. package package1;
  2. Class A{ 
  3. void show(){
  4. }
  5. public static void main (String args[]) {
  6. A a= new A(); // works fine in same class
  7. a.show();
  8. }
  9. }



  1. package package1;
  2. Class B{ 
  3. public static void main (String args[]) {
  4. A a= new A(); // works fine in same package
  5. a.show();
  6. }
  7. }

  1. package package2;
  2. import package1.*;
  3. Class B{ 
  4. public static void main (String args[]) {
  5. A a= new A(); // gives an error
  6. a.show(); // gives an error
  7. }
  8. }

 

Protected:

  • protected will act as public within the same package and acts as private outside the package.
  • But protected will also act as public outside the package only with respect to sub class objects.
  1. package package1;
  2. public Class A{ 
  3. protected void show() {
  4. }
  5. }

  1. package package2;
  2. import package1.*;
  3. public Class B extends A { 
  4. public static void main (String args[]) {
  5. B b= new B();
  6. b.show();
  7. }
  8. }
  • Access specifiers are applicable to static inner class and member inner class.
  • Access specifiers are not applicable to anonymous inner class and local inner class

Packages in java

Package:

  • Packages are nothing but all the related classes and interfaces and .class files.
  • Packages are the folders which are binding all the related ".class " files together
  • Binding: making something available to related functionalities.
  • A simple folder would only groups all the related files . But where as packages are also folders which binds all the related files.
  • Every package would be a folder. But every folder can not be a package

How to create user defined package:

  • By using a keyword "package".
  •  package package_name.
  1. package instanceofjavaforus;
  2. Class Demo{
  3. public static void main (String args[]) {
  4. }
  5. }

 

The Directory Structure of Packages:

  • To make java compiler to crate a package for us and automatically load all corresponding files into package
  1. package instanceofjavaforus;
  2. public Class Demo{
  3. public static void main (String args[]) {
  4. }
  5. }
  • Save this as Demo.java 
  • At this time there is no folder with name instanceofjavaforus 
  •  Javac -d . Demo.java.
  • -d : creates directory
  • instanceofjavaforus -> Demo.java: a folder with name instanceofjavaforus will be created and inside Demo.class will be there.

Creating Sub packages:

  • Create a package with a class;
  1. package pack;
  2. public  Class Demo{
  3. public static void main (String args[]) {
  4. }
  5. }
  •  C:/> javac -d . Demo.java
  • Now pack-> Demo.class folder structure will be created.
  • Now create sub package like this.

  1. package pack.subpack;
  2. public  Class Abc{
  3. public static void main (String args[]) {
  4. }
  5. }
  •  c:/> javac -d . Abc.java
  • pack->subpack -> Demo.class,Abc.class 

 How to create jar file representing our package: 

  •  By using dos command
  • c:/> jar -cvf file_name package_name.
  • Ex: jar -cvf instanceofjava.jar pack

Importing a package:

  • We can import packages by using "import".
  • To import the package
  • import<space><package-name><.><* or name of class you want to use from that package
  • To import particular class inside a package>.
  • import<space><package-name><.><name of class you want to use from that package>
  • As per the naming convention: For  package names use  small case letters.
  1. import pack.Demo;
  2. public  Class Xyz extends Demo {
  3. public static void main (String args[]) {
  4. }
  5. }



  1. import pack.*;
  2. public  Class Xyz extends Demo {
  3. public static void main (String args[]) {
  4. }
  5. }

 

Commonly using Predefined packages in java:  

Java.lang:

Provides classes that are fundamental to the design of the Java programming language. like
  1. Integer
  2. boolean
  3. Class
  4. Object
  5. Runtime
  6. Thread
  7. System
  8. Process
  9. Package
  10. String

Java.util.*:

This package contains the collections framework classes, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous. some of the interfaces and classes present in java.util package are as follows.
  1. Collection
  2. Comparator
  3. Enumeration
  4. RandomAccess
  5. List
  6. Set
  7. Map
  8. Iteraot
  9. EventListener
  10. Scanner (class)

Java.io.* :

This package provides classes and interfaces for system input and output through data streams, serialization and the file system.Some of the classes present in java.io package are as follows.
  1. BufferedInputStream
  2. BufferedOutputStream
  3. BufferedReader
  4. SerializablePermission
  5. Console
  6. File
  7. FileReader
  8. FilerWriter
  9. InputStream
  10. PrintStream

Java.text.* :

This package is used for formatting date and time on day to day business
operations.Some of the classes present in java.text package are as follows
  1. Annotation
  2. Collater
  3. Format
  4. DateFormat
  5. DecimalFormat
  6. MessageFormat
  7. NumberFormat
  8. Normalizer
  9. RuleBasedCollator
  10. ParsePosition

Java.sql.* 

This package is used for retrieving the data from data base and performing
various operations on data base. here some of the classes present in java.sql.
  1. Drivermanger
  2. Date 
  3. Time
  4. SqlPermission
  5. Timestamp
some of the interfaces present in java.sql package
  1. CallableStatement
  2. Connection
  3. PreparedStatement
  4. ResultSet
  5. Statement
  6. SQLData
  7. SQLInput
  8. SQLOutput

What is the difference between equals() method and == operator


== operator:

  •  == operator used to compare objects references.
  • used to compare data of primitive data types
  • if  we are comparing two objects using "==" operator if reference of both are same then it will returns true otherwise returns false.
  • obj1==obj2;
  • If we are comparing primitive data type variables then it compares data of those two variables
  • Ex: int a=12; int b=12; if(a==b) returns true

Comparing primitive values: 


  1. package com.instanceofjava;
  2.  
  3. Class Demo{ 
  4.  
  5. public static void main (String args[]) {

  6. int a=12;
  7. int b=13;
  8. int c=12;
  9.  
  10. if(a==b){
  11. System.out.println("a and b are equal");
  12.  
  13. if(b==c){
  14. System.out.println("a and b are equal");
  15.  
  16. }
  17. }
     

Comparing Objects:

  1. package com.instanceofjavaforus;
  2.  
  3. Class Demo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.  Demo obj1= new Demo();
  8. Demo obj2=new Demo();
  9.  
  10. if(obj1==obj2){ // here both are two different objects(memory allocation wise);
  11.  
  12. System.out.println("obj1 and obj2 are referring to same address");
  13.  
  14. }else{
  15.  
  16.  System.out.println("obj1 and obj2 are referring to different address");
  17.  
  18. }
  19. }
  20. }

Comparing String Objects:

  1. package com.instanceofjava;
  2.  
  3. Class ComapreStringDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.  String s1=new String("abc");
  8. String s2=new String("abc");
  9.  
  10. if(s1==s2){ // here it returns false
  11. System.out.println("obj1 and obj2 are referring to same address");
  12. }else{
  13.  System.out.println("obj1 and obj2 are referring to different address");
  14.  
  15. }
  16. }

Comparing String Literals:

  •  If we declared two string literals with same data then those will refer same reference.
  • means if we create any object using string literal then it will be created in string pool 
  • then if we are created another literal with same data then it wont create another object rather refers same object in pool.
  • so if compare two string literals with same data using "==" operator then it returns true.
  1. package com.instanceofjava;
  2.  
  3. Class ComapreStringLiteralDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.  String s1="abc";
  8. String s2="abc";
  9.  
  10. if(s1==s2){ // here it returns true
  11.  
  12. System.out.println("obj1 and obj2 are referring to same address");
  13.  
  14. }else{
  15.  
  16.  System.out.println("obj1 and obj2 are referring to different address");
  17.  
  18. }
  19. }
  20. }

equals() method:

  • equals() method defined in "object" class.
  • By default equals methods behaves like "==" operator when comparing objects.
  • By default equals() method compares references of objects.
  • But All wrapper classes and String class overriding this equals method and comparing data .
  • Means in String class and in All wrapper classes this equals() methods is overridden so that to compare data of those class objects. 

Comparing String Objects:

  1. package com.instanceofjava;
  2.  
  3. Class ComapreStringDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.  String s1=new String("abc");
  8. String s2=new String("abc");
  9.  
  10. if(s1.equals(s2)){ // here it returns true
  11.  
  12. System.out.println(" data present in obj1 and obj2 is same");
  13.  
  14. }else{
  15.  
  16.  System.out.println(" data present in obj1 and obj2 is different");
  17.  
  18. }
  19. }
  20. }


 Comparing custom objects:

  • If we want to compare custom objects means our own objects data.
  • Then we need to override equals method and in that we need to compare data.

  1. package com.instanceofjavaforus;

    public class Patient {
       String name;
       Patient(String name){
           this.name=name;
       }
          public boolean equals(Patient obj){
          
           if(this.name.equals(obj)){
               return true;
           }else{
               return false;
           }
       }
           public static void main(){
            Patient obj1= new Patient("sam");
           
            Patient obj2= new Patient("sam");
           
            System.out.println(obj1.equals(obj2)); //returns true
        }
           
    }

Important points to note about equals() and "==":

  • "==" used to compare data for primitive data type variables .
  • "==" operator compares objects references
  • By default equals() method behaves like "==" operator for objects means compares objects references.
  • All wrapper classes and String class overriding this equals() method and compares data of two objects. if same returns true.(when ever we overrides equals() method we need to override hashcode() method too and if two objects on equal method same then both should have same hashcode).
  • And in equals() method in string class logic includes "==" operator too.

  1. package com.instanceofjava;
  2.  
  3. public boolean equals(Object anObject) {
  4.    if (this == anObject) {
  5.       return true;
  6.      }
  7.  if (anObject instanceof String) {
  8.      String anotherString = (String) anObject;
  9.      int n = value.length;
  10.     if (n == anotherString.value.length) {
  11.     char v1[] = value;
  12.      char v2[] = anotherString.value;
  13.   int i = 0;
  14. while (n-- != 0) {
  15.    if (v1[i] != v2[i])
  16.            return false;
  17.            i++;
  18.        }
  19.          return true;
  20.         }
  21.     }
  22.        return false;
  23.   }
Select Menu