Showing posts with label Java programming Tutorial. Show all posts
Showing posts with label Java programming Tutorial. Show all posts

Saturday, March 28, 2020

Helloworld Programme Inward Coffee Alongside Example

First of all, welcome to the exciting footing of Java programming. If you lot are gear upwards to write your outset Java programme i.e. HelloWorld inwards Java, it way you lot already crossed major hurdles to start Java programming, inwards price of installing JDK together with setting PATH for Java. If you lot haven't done hence together with then you lot tin plough over the sack follow those tutorials to install JDK inwards Windows vii together with 8 together with setting PATH for Java. Before nosotros start writing HelloWorld inwards Java, few notes nearly editors. Many Java beginners insist or endeavour to role Eclipse or Netbeans IDE from the rattling start of the outset program, which is non a proficient idea. In companionship to larn syntax together with semantics of Java programming, you lot should code inwards notepad, give-and-take pad or whatsoever other text editor. I started coding inwards DOS Editor, but I won't propose that to you. Notepad++ is best of both world, it back upwards Java syntax highlighting, which helps to sympathise keywords better, together with its too a pleasant coding experience. 

If you lot don't get got notepad++, you lot tin plough over the sack download it cast http://notepad-plus-plus.org/, its FREE. Once you lot get got JDK, PATH together with Notepad++ installed, it’s fourth dimension to code your outset Java program, HelloWorld.



HelloWorld inwards Java

Here is measuring past times measuring guide to coding, compile together with run HelloWorld inwards Java from the ascendance prompt. Yes, nosotros are going to run Java programme from ascendance prompt, if you lot are not  very familiar together with then run across that link.



1) Create a Java rootage file every bit HelloWorld.java inwards Notepad++. It's ruled inwards Java to mention rootage file on the mention of the populace cast within that file.

2) Create a class, HelloWorld every bit public cast HelloWorld{}. It's Java coding convention to start the mention of the cast amongst a upper-case alphabetic lineament letter.

3) Now, add together the main method within HelloWorld class. every bit public static void main(String args[]){}. Like C programming language, execution of Java programme from start method. There is the pregnant of every unmarried keyword used amongst the primary method, together with you lot tin plough over the sack depository fiscal establishment represent why primary is populace static together with void inwards Java to know this. By the way, at that spot are a twosome of syntaxes to declare a measure primary method, but nosotros volition stick amongst this every bit it's measure 1 together with simplest of all.

4) Now it's fourth dimension to write code to impress HelloWorld inwards the console. You tin plough over the sack write System.out.println("HelloWorld"); within primary to print HelloWorld inwards Java. Remember to position semi colon at the destination of the statement, every bit a tilt inwards Java ends amongst a semi colon. The System is an inbuilt cast which comes amongst JDK together with it’s business office of rich Java API. DOT operator is used to accessing champaign together with methods, which way out is a filed within System class, which has println() method, together with which does the chore of printing characters or string to the console.

5) If you lot await at println() method it  accepts a String literal, which is enclosed inwards double quotes inwards Java, together with prints it on the console together with too adds a novel line. hither is consummate code instance of HelloWorld programme inwards Java

public class HelloWorld {        public static void main(String args[]) {         System.out.println("HelloWorld Java");     }     }

6) Save your Java rootage file together with gear upwards to compile it.

7) Open ascendance prompt inwards Windows, past times typing cmd on run window together with type javac, if you lot see,  javac non recognized every bit an internal or external command, way PATH for Java is non laid together with nosotros ask to right that. See this tutorial laid Java Path on Windows. If you lot run across javac output together with options way nosotros are gear upwards to compile.

8) Now become to the directory, where you lot get got position your Java rootage file, HelloWorld.java together with type : javac HelloWorld.java , this ascendance volition learn Java compiler to compile Java rootage file together with practise cast files, which contains Java bytecode for execution inwards JVM. The compiler volition exhibit compilation fault if at that spot is whatsoever syntax, semantics the or compiler fault inwards Java rootage file. If you lot run across an error, together with then nosotros ask to resolve that. Just glue it hither together with nosotros tin plough over the sack operate it out.

9) If everything goes well, nosotros could see, HelloWorld.class file inwards electrical current directory. It way you lot are gear upwards to run your how-do-you-do footing programme inwards Java. Next measuring is to run Java program.

10) Type java HelloWorld on ascendance prompt, brand certain you lot run this ascendance from electrical current directory, where HelloWorld.class file is present. You run across simply mention of cast without extension, together with it volition learn JVM to find, charge together with execute HelloWorld class. If at that spot is no runtime exception, than you lot tin plough over the sack run across "HelloWorld Java" every bit output inwards console.

 welcome to the exciting footing of Java programming HelloWorld Program inwards Java amongst Example


That's all on How to create, compile together with run HelloWorld programme inwards Java. I highly recommend to role notepad++ for coding at to the lowest degree for few months, to larn Java programming. If you lot appear upwards whatsoever fault acre compiling or running this Java program, together with then delight post here. We volition endeavour to resolve together with explicate it here.

Further Learning
Complete Java Masterclass
Java ArrayList Tutorial together with Examples

How To Convert String To Int Inwards Coffee

There are 3 top dog ways to convert String to int inward Java, using the constructor of Integer class, parseInt() method of java.lang.Integer in addition to Integer.valueOf() method. Though all those methods render an trial of java.lang.Integer, which is a wrapper class for primitive int value, it's slow to convert Integer to int inward Java. From Java 5, yous don't postulate to practise anything, autoboxing volition automatically convert Integer to int. For Java 1.4 or lower version, yous tin role intValue() method from java.lang.Integer class, to convert Integer to int. As the cite suggest, parseInt() is the center method to convert String to int inward Java. parseInt() convey a String which must comprise decimal digits in addition to origin grapheme tin locomote an ASCII minus sign (-) to announce negative integers. parseInt() throws NumberFormatException, if provided String is non convertible to int value. 

By the agency parseInt is an overloaded method in addition to it's overloaded version takes radix or base of operations e.g. 2,8,10 or 16, which tin locomote used to convert binary, octal, hexadecimal String to int inward Java. Integer.valueOf() is only about other useful method to convert String to Integer inward Java, it offers caching of Integers from -128 to 127. 

Internally, valueOf() likewise calls parseInt() method for String to int conversion. In this Java programming tutorial, nosotros volition come across all 3 ways to convert String to int value inward Java.




String to Integer Conversion Example

constructor of Integer class to practise Integer from String, afterwards that Integer is converted to int using autoboxing inward Java

Second instance uses Integer.parseInt() in addition to tertiary String conversion examples role Integer.valueOf() method to convert String to int inward Java. 

By the way, locomote careful alongside String.valueOf() method, equally it may render same object on multiple class, if integer value is from it's cache. Also comparison int to Integer is fault prone inward autoboxing in addition to tin create surprising results. See pitfalls of autoboxing inward Java for to a greater extent than details.

package test;  /**  * Java plan to convert String to int inward Java. From Java five onwards  * autoboxing tin locomote used to convert Integer to int automatically.  *  * @author http://java67.blogspot.com  */ public class StringToIntegerHowTo {         public static void main(String args[]) {          //Converting positive integer value String to int inward Java         String integer = "123";                 // String to int conversion using Integer constructor in addition to autoboxing         int rank out = new Integer(integer);         System.out.println("Integer created from String inward Java : " + number);                 // Converting String to int using parseInt() method of java.lang.Integer         rank out = Integer.parseInt(integer);         System.out.println("String to int using parseInt()  : " + number);                 // String to int conversion using valueOf() method of Integer class         rank out = Integer.valueOf(integer);         System.out.println("String to int Conversion instance using valueOf  : " + number);                 String negative = "-123";         System.out.println("Converting negative String to int inward Java");         System.out.println("String to Integer Constructor Example : " + new Integer(negative));         System.out.println("String to Integer parseInt Example : " + Integer.parseInt(negative));         System.out.println("String Integer valueOf Example : " + Integer.valueOf(negative));         }      }  Output: Integer created from String inward Java : 123 String to int using parseInt()  : 123 String to int Conversion instance using valueOf  : 123 Converting negative String to int inward Java String to Integer Constructor Example : -123 String to Integer parseInt Example : -123 String Integer valueOf Example : -123

That's all on How to convert String to int or Integer inward Java. By the way, converting int to Integer is ridiculously slow inward Java in addition to done automatically past times Java platform, from Java five onwards. As said inward best agency to convert String to rank out inward Java, yous tin select betwixt parseInt() in addition to valueOf() for String to int conversion. Integer.valueOf() is preferred because it offers caching in addition to eventually delegate telephone phone to parseInt for String to int conversion, if integer value is non available inward cache.

Further Learning
Complete Java Masterclass
How to convert String to Date inward Java

How To Separate String Inwards Coffee Using Regular Expression

String shape provides split() method to dissever String inward Java, based upon whatsoever delimiter, e.g. comma, colon, infinite or whatsoever arbitrary method. split() method splits the string based on delimiter provided, in addition to render a String array, which contains private Strings. Actually, split() method takes a regular expression, which inward simplest instance tin live on a unmarried word. split() is too overloaded method inward java.lang.String shape in addition to its overloaded version bring a boundary parameter which is used to command how many times blueprint volition live on applied during splitting process. if this boundary is positive n, hence the blueprint volition live on applied at virtually n-1 times, if it's negative or nix hence dissever performance is applied whatsoever release of time. For example, if nosotros dissever String "First,Second,Third" on comma in addition to render boundary every bit ii hence blueprint volition run i time, in addition to split() volition render String array amongst ii Strings, "First" in addition to "Second,Third". 

Since this method accepts a Java regular expression, it throws PatternSyntaxException, if the syntax of the regular human face is invalid.


String Split Example inward Java

String Split illustration inward Java. In the offset example, nosotros volition dissever a colon separated String on colon every bit a delimiter, in addition to inward the 2nd example, nosotros volition dissever comma separated String. 



In the 3rd example, nosotros volition dissever String using the regular expression, which truly splits a String on infinite every bit delimiter. \\s is a regular human face to notice spaces. \s is truly used to gibe whatsoever white space grapheme including newline, tab, shape feed e.g. \t, \n, \r, in addition to \f. \\ is to escape backward slash which is an escape grapheme inward Java. 


If you lot are familiar amongst Java Regular Expression, hence split(regex) method is like to Pattern.compile(regex).split().

package test;  /**  * Java programme to dissever String inward Java using delimiter.  * This String Split illustration shows how to dissever String inward Java using comma, colon in addition to infinite every bit delimiter.  * Splitting String yesteryear infinite uses regular human face \\s to dissever String.  *  * @author http://java67.blogspot.com  */ public class StringSplitExample {       public static void main(String args[]) {        //Splitting colon separated String inward Java       String colon = "Java:J2EE:JavaFX:JavaME";             String[] strings = colon.split(":");             System.out.println("Original Colon Separated String : " + colon);       System.out.println("String splitted using Split() method of java.lang.String inward Java");             for(String str : strings){           System.out.println(str);       }             //Splitting comma separated String inward Java       String comma = "Android,Windows 8,iOS,Symbian";       String[] strs = comma.split(",");       System.out.println("Original comma separated String : " + comma);       System.out.println("Splitting String using split() method inward Java");            for(String str: strs){           System.out.println(str);       }             //Splitting String on infinite every bit delimiter inward Java       String infinite = "String Split Example inward Java";       String[] words = space.split("\\s");       System.out.println("Space separated String earlier dissever : " + space);       System.out.println("Space separated String later split");             for(String word: words){           System.out.println(word);       }          }      } Output: Original Colon Separated String : Java:J2EE:JavaFX:JavaME String splitted using Split() method of java.lang.String inward Java Java J2EE JavaFX JavaME Original comma separated String : Android,Windows 8,iOS,Symbian Splitting String using split() method inward Java Android Windows 8 iOS Symbian Space separated String earlier dissever : String Split Example inward Java Space separated String later dissever String Split Example inward  Java

That's it on How to dissever String inward Java using delimiter in addition to regular expression. The split(regex) method is rattling powerful, in addition to all its ability comes from the regular expression. Though it's non required to know regular human face to dissever String inward Java, only if you lot know regex, it is solely going to aid you.

Further Learning
Data Structures in addition to Algorithms: Deep Dive Using Java
How to supervene upon String inward Java amongst example

How To Override Equals, Hashcode Together With Compareto Method Inward Java

Though modern IDE similar Eclipse, IntelliJ or Netbeans allows you lot to generate equals, hashCode too compareTo methods for your value classes, it's as important, you lot know how to exercise that yesteryear hand. By overriding equals too hashcode method yesteryear yourself, you lot know how they work, what form of errors you lot tin get, too most importantly, it's expected shape you, as a Java programmer inwards whatever core Java interview. More often, you lot would run into a coding query inwards Java, which enquire you lot to override equals(), hashcode(), compare() too compareTo() methods for a value class. Since I convey already shared about tips on How to override compareTo method inwards Java, too pair of instance of writing your ain Comparator inwards Java, hither I am sharing about other uncomplicated instance of overriding equals too hashCode methods. If you lot know rules of overriding equals too hashCode, you lot mightiness know that, whenever you lot override equals, you lot must convey to override hashCode, otherwise your object volition non bear properly on diverse collection classes e.g. Map or Set, which uses equals, compareTo, hashCode to implement at that topographic point invariants e.g. Set implementations should non allow whatever duplicates.



Overriding Equals, HashCode too CompareTo inwards Java

NullPointerException



See this post service for detailed tips on overriding equals method inwards Java. For overriding hashCode, you lot postulate to select a prime, commonly 31, but you lot tin besides select other prime numbers e.g. 37, 17 etc. The argue for choosing these prime numbers are to generate a uniquely distributed hashcode, which eventually helps to avoid collision, when used inwards hash based collections similar Hashtable too HashMap

Another worth noting affair is using all variables, used inwards equals, inwards hashCode method to proceed equals too hashCode consistent, too adhere to rules of overriding hashCode inwards Java. I convey already discussed almost Comparable too compareTo method, piece sorting listing of objects inwards Java

A uncomplicated implementation of compareTo must render negative let on if electrical flow object is lesser than provided object, positive if electrical flow object is greater inwards gild than provided too null if both objects are equal. Another worth noting indicate is that, compareTo() too equals() must last consistent amongst each other, otherwise your object volition non bear properly on Collection classes, which uses compareTo() for sorting e.g. TreeSet or TreeMap. Anyway, hither is a uncomplicated instance of overriding equals, hashcode too compareTo inwards Java.



Sample implementation of Equals, HashCode too CompareTo inwards Java

In this sample instance of overriding equals, hashcode too compareTo method, nosotros volition locomote a shape named Person which has 3 properties String name, int id too Date to stand upward for appointment of birth.  We volition besides locomote Generics along amongst Comparable to supply a type rubber implementation. Remember nosotros convey used getClass() method instead of instanceof operator, which agency a Person shape cannot last equal to its subclass, this could exercise occupation if you lot are using this shape inwards EJB or whatever application server, where at that topographic point is a adventure that same shape is loaded yesteryear 2 split upward shape loader. On those cases it's ameliorate to locomote instanceof operator because it volition allow a Class to last equal to its subclass if residue of properties matched. This is besides truthful for framework similar Hibernate, which provides proxy implementation, which is essentially sub shape of entity classes. In short, locomote instanceof if your shape tin last loaded yesteryear multiple shape loader or it tin last used yesteryear framework to exercise proxies.
/**  * Simple Java Class to stand upward for Person amongst name, id too appointment of birth.  *  * @author Javin Paul  */ public class Person implements Comparable<Person>{    private String name;    private int id;    private Date dob;      public Person(String name, int id, Date dob) {         this.name = name;         this.id = id;         this.dob = dob;     }       @Override    public boolean equals(Object other){        if(this == other) return true;               if(other == null || (this.getClass() != other.getClass())){            return false;        }               Person invitee = (Person) other;        return (this.id == guest.id) &&               (this.name != null && name.equals(guest.name)) &&               (this.dob != null && dob.equals(guest.dob));    }        @Override    public int hashCode(){        int effect = 0;        effect = 31*result + id;        effect = 31*result + (name !=null ? name.hashCode() : 0);        effect = 31*result + (dob  !=null ? dob.hashCode() : 0);               return result;    }      @Override     public int compareTo(Person o) {         return this.id - o.id;     }    }



Sample JUnit examine instance for testing Equals too HashCode

Here is simplest of uncomplicated examine instance to verify equals too hashCode inwards Java. Remember this unit of measurement examine is non enough, if you lot desire to verify all properties of equals too hashCode. If you lot should write examine cases to banking concern check if it verify cardinal properties of equals too hashcode method e.g. if a equal b too thence b should besides last equal to a,  or if a a equals b too b equals c too thence a too c should besides last equal to each other. You must besides verify whether compareTo() render 0 for equal object too render non null value for non equal objects. 
import java.util.Date; import org.junit.Test; import static org.junit.Assert.*;  /**  * Simple instance of using equals too hashCode method  * @author Javin Paul  */ public class EqualsAndHashCodeTest {           @Test    public void testEquals(){        Person james = new Person("James", 21, new Date(1980,12, 1));        Person same = new Person("James", 21, new Date(1980,12, 1));        Person similar = new Person("Harry", 21, new Date(1981,12,1));               assertTrue(james.equals(same));        assertTrue(james.hashCode() == same.hashCode());             assertFalse(james.equals(null));        assertFalse(james.equals(similar));        assertTrue(james.hashCode() != similar.hashCode());    }     }


That's all on this simple instance of overriding equals, hashcode too compareTo method inwards Java. As I said, these examine are merely to verify that equals too hashCode methods are working, you lot tin add together to a greater extent than examine to verify compareTo, too other behaviors of all 3 methods.

Further Learning
Complete Java Masterclass
Core Java Interview Questions for 2 to iv years experienced Programmers

Friday, March 27, 2020

Difference Betwixt Comparator As Well As Comparable Inwards Coffee - Interview Question

Comparator together with Comparable are 2 interfaces inwards Java API, which is used to compare 2 objects inwards Java. Though both are used for comparing at that spot are or hence differences betwixt them, a major divergence betwixt Comparable and Comparator is that sometime is used to define the natural ordering of object e.g. lexicographic guild for java.lang.String, spell later on is used to define whatever choice ordering for an object.  The principal usage of java.lang.Comparable together with java.util.Comparator interface is for sorting a listing of objects inwards Java. For instance to kind a listing of Employee by their Id, nosotros tin utilisation Comparable interface together with render additional sorting capability, nosotros tin define multiple comparators e.g. AgeComparator to compare the historic menstruum of the employee, SalaryComparator to compare the salary of employees etc.  This brings or hence other important divergence betwixt Comparator together with Comparable interface inwards Java, you lot tin conduct keep solely 1 ordering via Comparable e.g. natural ordering spell you lot tin define multiple Comparator for choice ordering every bit discussed above.

Coming to Interviews, this query is rattling mutual inwards 2 to three years sense Java interviews, together with you lot only can't afford to non gear upward this. It's definitely possible to gain years of sense inwards Java, without writing your ain Comparator or Comparable, peculiarly if you lot are non doing active evolution or coding, but fifty-fifty though, you lot must know basics e.g. equals together with hashcode, compareTo() and compare().

In this article, nosotros volition come across or hence notable divergence betwixt Comparator vs Comparable inwards Java from interview perspective. If you lot are preparing for Java Interview, you lot may similar to come across this squeamish book, Java Programming Interview Exposed past times Markham, an splendid mass alongside Java interview questions for both intermediate together with experienced Java programmers.




Comparator vs Comparable inwards Java

During interviews, you lot tin expression upward this query differently, if you lot are giving telephonic circular hence it's generally fact based i.e. you lot demand to cite cardinal points close both interfaces, spell inwards expression upward to expression upward interviews or during written test, you lot powerfulness hold upward asked to write code to kind objects using Comparator together with Comparable e.g. sorting employee past times shout out or branch. I conduct keep already discussed the instant role of this query hither together with nosotros volition solely come across fact based differences inwards this post.

1. Comparator interface is inwards java.util package, which implies it's a utility class, spell Comparable interface is kept on java.lang package, which agency it's essential for Java objects.

2. Based on syntax, 1 divergence betwixt Comparable together with Comparator inwards Java is that sometime gives us compareTo(Object toCompare), which accepts an object, which straightaway uses Generics from Java 1.5 onwards, spell Comparator defines compare(Object obj1, Object obj2) method for comparing 2 object.

3. Continuing from the previous difference betwixt Comparator vs Comparable later on is used to compare electrical flow object, represented past times this keyword, alongside or hence other object, spell Comparator compares 2 arbitrary objects passed to compare() method inwards Java.

4. One of the cardinal divergence betwixt Comparator and Comparable interface inwards Java is that, You tin solely conduct keep 1 compareTo() implementation for an object, spell you lot tin define multiple Comparator for comparing objects on dissimilar parameters e.g. for an Employee object, you lot tin utilisation compareTo() method to compare Employees on id,  known every bit natural ordering, spell multiple compare() method to guild employee on age, salary, shout out together with city. It's too a best do to declare Comparator every bit nested static classes inwards Java, because they are closely associated alongside objects they compare.

5. Many Java classes, which brand uses of Comparator and Comparable defaults to Comparable together with provided overloaded method to function alongside arbitrary Comparator instance e.g. Collections.sort() method, which is used to sort Collection inwards Java has 2 implementation, 1 which kind object based on natural guild i.e. past times using java.lang.Comparable together with other which accepts an implementation of java.util.Comparator interface.

6. One to a greater extent than cardinal thing, which is non a divergence but worth remembering is that both compareTo() together with compare() method inwards Java must hold upward consistent alongside equals() implementation i.e. if 2 methods are equal past times equals() method than compareTo() together with compare() must render zero. Failing to adhere this guideline, your object may interruption invariants of Java collection classes which rely on compare() or compareTo() e.g. TreeSet together with TreeMap.


 Comparator together with Comparable are 2 interfaces inwards Java API Difference betwixt Comparator together with Comparable inwards Java - Interview QuestionThat's all on difference betwixt Comparator together with Comparable inwards Java. Always retrieve that java.lang.Comparable is used to define natural ordering of an object, spell java.util.Comparator tin hold upward used to define whatever ordering based upon your requirements. You tin define solely 1 ordering alongside Comparable but tin conduct keep multiple Comparators. I strongly propose to await my instance of comparator vs comparable to gain to a greater extent than insight on how to utilisation actually utilisation it inwards code. From Java interview betoken of view, I think, you lot are proficient to larn if you lot know this much details.

Further Learning
Data Structures together with Algorithms: Deep Dive Using Java
Difference betwixt List, Set, together with Map inwards Java
  • Difference betwixt HashMap together with HashSet inwards Java
  • Difference betwixt Path together with Classpath inwards Java
  • When to extend thread together with implement Runnable inwards Java
  • Difference betwixt hold back together with slumber method inwards Java
  • Thursday, December 12, 2019

    How To Convert Java.Util.Date To Java.Sql.Date - Example

    There are 2 appointment classes inwards Java, i inwards java.util package as well as other inwards the java.sql package. Though both are known every bit Date class, at that spot is some difference betwixt java.util.Date as well as java.sql.Date e.g. Former is used whenever a Date is required inwards Java application piece afterwards is used to read as well as shop DATE SQL type from the database. There is i to a greater extent than of import deviation is, java.util.Date stores both appointment as well as fourth dimension values, piece java.sql.date solely stores appointment information, without whatever fourth dimension part. As per Javadoc, java.sql.date is a sparse wrapper around a millisecond value that allows JDBC to position this every bit an SQL DATE value. To adjust amongst the Definition of SQL DATE, the millisecond values wrapped past times a java.sql.Date instance must last 'normalized' past times setting the hours, minutes, seconds, as well as milliseconds to zippo inwards the detail fourth dimension zone amongst which the instance is associated. See SQL appointment vs Util date for few to a greater extent than differences.

    In this Java tutorial, nosotros volition larn how to convert a java.util.Date to java.sql.Date, every bit nosotros oftentimes require to create this when storing values into database. Since java.util.Date is measure agency to correspond appointment as well as fourth dimension inwards Java, I solely drib dead along java.sql.Date up-to JDBC or DAO Layer, past times the agency if you lot require appointment amongst time, as well as then usage SQL TIMESTAMP type instead of DATE.

    It's likewise notable that java.sql.Date is subclass of java.util.Date, exactly it doesn't hateful you lot tin transcend around this inwards house of java.util.Date, because it violates Liskov Substitution principle.




    All fourth dimension related methods of java.sql.Date throws IllegalArgumentException, every bit shown below


    public int getHours() {     throw  java.lang.IllegalArgumentException(); }   public int getMinutes() {     throw new java.lang.IllegalArgumentException(); }   public int getSeconds() {     throw new java.lang.IllegalArgumentException(); }

    It genuinely an interesting instance of Inheritance, where superclass is to a greater extent than powerful than subclass, as well as instead of extending functionalities of rear class, subclass is genuinely limiting characteristic past times non allowing fourth dimension fields. If you lot receive got a code, which accepts java.util.Date, compiler volition allow a java.sql.Date to last passed to that method, exactly every bit presently every bit you lot run the program, your code volition neglect amongst next mistake :

    Exception inwards thread "main" java.lang.IllegalArgumentException     at java.sql.Date.getHours(Date.java:182)

    That's why, brand certain non to permit java.sql.Date come upwardly exterior of Data Access layer. By the way, because both the flat has same cite Date, you lot tin non usage them together past times their uncomplicated name, you lot require to specify their fully character name, i.e. cite amongst package, every bit shown inwards below example. If nosotros import java.util.Date as well as then compiler volition process whatever Date every bit util appointment as well as non java.sql.Date.


    Java Program to convert java.util.Date to java.sql.Date

    Here is our sample programme for converting a util appointment to sql date. Since both Date classes are based upon long fourth dimension interval, you lot tin easily convert them past times passing value of getTime(), which correspond milliseconds passed from 1st Jan 1970, likewise known every bit EPOCH. Since java.sql.Date solely contains appointment information, whatever fourth dimension information supplied to it are ignored or normalized. This is obvious, when you lot impress values of both appointment classes, java.util.Date prints both appointment as well as fourth dimension component, piece SQL appointment prints solely information inwards dateformat yyyy-MM-dd. You tin likewise encounter telephone telephone to fourth dimension related methods from java.sql.Date e.g. getHours(), getMinutes() as well as getSeconds()  are failed past times throwing java.lang,.IllegalArgumentException. That's why its advised non transcend a SQL appointment to a method, which await a util appointment inwards Java.


    /**  * Java Program to convert java.util.Date into java.sql.Date  * @author http://java67.blogspot.com  */ public class DateConverter {       public static void main(String args[]) {           // contains both appointment as well as fourth dimension information         java.util.Date utilDate = new java.util.Date();         System.out.println("Util appointment inwards Java : " + utilDate);           // contains solely appointment information without time         java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());         System.out.println("SQL appointment inwards Java : " + sqlDate);         System.out.printf("Time :  %s:%s:%s", sqlDate.getHours(), sqlDate.getMinutes(), sqlDate.getSeconds());       }   }   Output: Util appointment inwards Java : Monday February 03 13:26:05 PST 2014 SQL appointment inwards Java : 2014-02-03
    Exception inwards thread "main" java.lang.IllegalArgumentException     at java.sql.Date.getHours(Date.java:182)

    That's all nigh how to convert java.util.Date to java.sql.Date inwards Java. Always usage getTime() method to convert i appointment to other. Also scream back that sql appointment inwards Java solely holds appointment information without time. Though java.sql.Date is a subclass of java.util.Date it violates Liskov commutation principle, as well as tin non last passed where java.util.Date is expected. Compiler volition allow that exactly it volition neglect inwards runtime if you lot telephone telephone whatever fourth dimension related method, they are anyway deprecated, thus don't usage them.

    Further Learning
    Complete Java Masterclass
    Java Fundamentals: The Java Language
    Java In-Depth: Become a Complete Java Engineer!

    Can You Lot Operate Coffee Programme Without Principal Method?

    First affair Java programmers learns is that they demand a primary method to run, but when they drib dead to whatever Interview or college viva too asked can yous run a Java plan without a primary method, they surprised similar hell. Well, in that place are truly dissimilar types of execution model available inwards Java, for example, Applets which run on browser doesn't bring primary method, instead they bring life-cycle methods similar init(), start() too stop(), which controls their execution. Since Applet is a Java program, yous tin response this query inwards Yes. Similarly, nosotros bring Servlet, which runs inwards a Servlet container, comes equally bundled inwards a web server similar Tomcat, or Jetty. Servlet too plant on callback mechanism, it has methods similar init(), service() too destroy(). Container calls init() if Servlet is offset fourth dimension loaded into memory, calls service() if in that place is a asking to procedure too calls destroy() earlier removing it from memory.

    Since Servlet is too a Java program, nosotros tin say that it runs without primary method. Third 1 on this category is MIDlet, which runs on mobile devices e.g. Nokia, Samsung too others. MIDlet has life-cycle methods similar startApp(), pauseApp() too destroyApp(), to start, recess too shut-down mobile applications.

    Ironically J2ME has app inwards their meat method, but it was made pop past times Android too iPhone. Since MIDlets are too Java program, yous tin say they run without primary method.

    Now, if Interviewer persist yous amongst something similar this, Can yous run a Java plan without primary method inwards Core Java, non on managed surroundings similar the instance of Applet, Servlet too MIDlet. Answer is NO, Why? I volition explicate that inwards side past times side paragraph.

    By the way, this is 1 of the many questions related to primary method inwards Java, yous tin come across the amount listing of interview query on primary method here.




    Java plan without Main method

    Many Java programmer gives yous response that they tin run Java plan without primary method past times writing code inwards static initializer block, which is one-half true. Yes, code written inwards static initializer block is executed earlier calling primary method, but yous won't live on able to run a course of written report past times using Java command, or Eclipse or anything else, until it got  public static void main(String args[]) method on it. If yous endeavour to run such programs, yous volition acquire next mistake :

    Error: Main method non institute inwards course of written report JavaAppWithoutMain, delight define the main
     method as:   populace static void main(String[] args)

     First affair Java programmers learns is that they demand a primary method to run Can You Run Java Program Without Main Method?










    Though yous tin run a Java plan amongst empty Main method, inwards which instance entirely code executed volition live on from static initializer block. Following is a uncomplicated Java plan amongst simply about code written on static initializer block, including a impress statement, a variable initialization too starting a thread. As presently equally yous take away the primary method, it volition compile fine but volition throw inwards a higher house error, when yous endeavour to run this plan from command line.

    /**  * Java application to demonstrate whether yous tin run a plan without a primary method  * or not.  * @author http://java67.blogspot.com  */ public class JavaAppWithoutMain {      static {         System.out.println("HelloWorld, Java progarm without primary method");         int x = 20; // Can initialize static variables         System.out.println("Variable x : " + x);          Thread t = new Thread() {             @Override             public void run() {                 System.out.println("Started thread from static initializer block");     System.out.println("Thread Finished");             }         };         t.start();     }      public static void main(String args[]) {           // Empty primary method     }  }

    Here is how the output expect like, when yous run this plan from command prompt amongst empty primary method.

     First affair Java programmers learns is that they demand a primary method to run Can You Run Java Program Without Main Method?









    That's all nearly whether yous tin run a Java plan without primary method inwards Java or not. In short, Yes, yous tin run a Java plan without primary method inwards a managed surroundings e.g. Applet, Servlet, too MIDlet, which runs nether command of browser, server too mobile device, but can't run a meat Java plan without populace static void main(string args[]) method. JVM volition non allow yous to execute those methods.

    Further Learning
    Complete Java Masterclass
    Java Fundamentals: The Java Language
    Java In-Depth: Become a Complete Java Engineer!