Friday, March 15, 2019

Database Connectivity with MySQL

  1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
  2. Connection URL: The connection URL for the mysql database is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running, we may also use IP address, 3306 is the port number and sonoo is the database name. We may use any database, in such case, we need to replace the sonoo with our database name.
  3. Username: The default username for the mysql database is root.
  4. Password: It is the password given by the user at the time of installing the mysql database. In this example, we are going to use root as the password.
  1. create database sonoo;  
  2. use sonoo;  
  3. create table emp(id int(10),name varchar(40),age int(3));

Database Connectivity with Oracle

  1. Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver.
  2. Connection URL: The connection URL for the oracle10G database is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database, thin is the driver, localhost is the server name on which oracle is running, we may also use IP address, 1521 is the port number and XE is the Oracle service name. You may get all these information from the tnsnames.ora file.
  3. Username: The default username for the oracle database is system.
  4. Password: It is the password given by the user at the time of installing the oracle database.
create table emp(id number(10),name varchar2(40),age number(3));  

Jar File Creation

Steps for jar file:- --->jar -cvf MyJarFile.jar CreateAJarFile.class //This is for jar file creation
The benefit of storing your class file in a jar file is that you can execute your class from any location on the file system. To illustrate this important point, navigate to the directory above the one where the class file is stored.
--->java -cp ./create-a-jar-file-in-java/MyJarFile.jar CreateAJArFile // Successfully executed the class file
Execute the Java runtime launcher with the cp (classpath) option. Notice that the path specified on the classpath option references the directory that contains the jar file.

Create war file

1.Go to your project open folder opened.
2.But, out side of WEB-INF, war file should be created OK.
3.Now upload war file.

Steps for war file:-
--->jar -cvf projectname.war (Press Enter) //This is for war file creation
--->jar -xvf projectname.war (Press Enter) //This is for war file extraction

Create java Documentation for file or project:-

On the command prompt, you need to write:

javadoc M.java
to generate the document api. Now, there will be created a lot of html files.
Open the index.html file to get the information about the classes.

Java System exit() Method

Java System exit() Method

The exit() method of System class terminates the current Java virtual machine running on system. This method takes status code as an argument.
  • Note: Status - exit(0) - indicates Successful termination
  • Status - exit(-1) - indicates unsuccessful termination with Exception
  • Status - exit(1) - indicates Unsuccessful termination

Syntax

  1. public static void exit(int status)  

Parameter

status - It is the exit status.

Returns

This method does not return any value.

Exception

If security manager exist and his checkexit method doesn't approve exit with specified status then a SecurityException is thorwn.

Example 1

  1. import java.lang.*;  
  2. public class SystemExitExample1 {  
  3.   
  4.     public static void main(String[] args) {  
  5.         int a[]= {9,8,7,6,5,4,3,2,1};  
  6.         for(int i=0;i<a.length;i++)  
  7.         {  
  8.             if(a[i]>5)  
  9.             {  
  10.             System.out.println("array["+i+"]="+a[i]);  
  11.             }  
  12.             else  
  13.             {  
  14.                 System.out.println("terminating jvm,exiting");  
  15.                 System.exit(0);//Treminatejvm  
  16.             }  
  17.         }  
  18.     }  
  19. }  
Test it Now
Output:
array[0]=9
array[1]=8
array[2]=7
array[3]=6
terminatingjvm,exiting

Example 2

  1. public class SystemExitExample2 {  
  2.   
  3.     public static void main(String[] args) {  
  4.         System.out.println("program will terminate when i is 1");  
  5. for(int i=10;i>0;i--)    {         
  6. System.out.println("your no is "+i);  
  7. if(i==1){  
  8. System.out.println("Value is 1 now terminating your program");  
  9. System.exit(1); //exit program  
  10.             }  
  11.             }  
  12.     }  
  13. }  
Test it Now
Output:
program will terminate when i is 1
your no is 10
your no is 9
your no is 8
your no is 7
your no is 6
your no is 5
your no is 4
your no is 3
your no is 2
your no is 1
Value is 1 now terminating your program

3 streams System.in, System.out, and System.err

Java IO: System.in, System.out, and System.error

The 3 streams System.inSystem.out, and System.err are also common sources or destinations of data. Most commonly used is probably System.out for writing output to the console from console programs.

These 3 streams are initialized by the Java runtime when a JVM starts up, so you don't have to instantiate any streams yourself (although you can exchange them at runtime).

Simple System.out + System.err Example:

Here is a simple example that uses System.out and System.err:
try {
  InputStream input = new FileInputStream("c:\\data\\...");
  System.out.println("File opened...");

} catch (IOException e){
  System.err.println("File opening failed:");
  e.printStackTrace();
}

Exchanging System Streams

Even if the 3 System streams are static members of the java.lang.System class, and are pre-instantiated at JVM startup, you can change what streams to use for each of them. Just set a new InputStream for System.in or a new OutputStream for System.out or System.err, and all further data will be read / written to the new stream.
To set a new System stream, use one of th emethods System.setIn()System.setOut() or System.setErr(). Here is a simple example:
OutputStream output = new FileOutputStream("c:\\data\\system.out.txt");
PrintStream printOut = new PrintStream(output);

System.setOut(printOut);
Now all data written to System.out should be redirected into the file "c:\\data\\system.out.txt". Keep in mind though, that you should make sure to flush System.out and close the file before the JVM shuts down, to be sure that all data written to System.out is actually flushed to the file.

printStackTrace Examples

Java Throwable printStackTrace() method
The printStackTrace() method of Java Throwble class is used to print the Throwable along with other details like classname and line number where the exception occurred.

Syntax


  1. public void printStackTrace()  

Example 1


  1. import java.lang.Throwable;  
  2. public class ThrowablePrintStackTraceExample1 {  
  3.     public static void main(String[] args) throws Throwable {  
  4.    try{  
  5.        int i=4/0;  
  6.    }catch(Throwable e){  
  7.        e.printStackTrace();  
  8.        System.err.println("Cause : "+e.getCause());  
  9.    }  
  10. }  
  11. }  
Output:

java.lang.ArithmeticException: / by zero
 at ThrowablePrintStackTrace.main(ThrowablePrintStackTrace.java:5)
Cause : null


Example 2

  1. public class ThrowablePrintStackTraceExample2 {  
  2.     public static void main(String[] args)throws Throwable {  
  3.         try{  
  4.             exceptionTest();  
  5.         }catch(Throwable t){  
  6.             t.printStackTrace();  
  7.         }  
  8. }  
  9.     public static void exceptionTest() throws Exception{  
  10.         System.out.println("Inside exceptionTest() method");  
  11.         throw new Exception("Throwing localized message!");  
  12.     }  
  13. }  

Output:
Inside exceptionTest() method
java.lang.Exception: Throwing localized message!
 at ThrowablePrintStackTraceExample2.exceptionTest(ThrowablePrintStackTraceExample2.java:11)
 at ThrowablePrintStackTraceExample2.main(ThrowablePrintStackTraceExample2.java:4)

Access Modifiers

ClassExceptions

ClassNotFoundException:

ClassNotFoundException is a runtime exception that is thrown when an application 
triesto load a class at runtime using the: 
Class.forName() or loadClass() or findSystemClass() methods ,
and the class with specified name are not found in the classpath.

For example, the below program will throw ClassNotFoundException 
if the mentioned class “oracle.jdbc.driver.OracleDriver” is not found 
in the classpath.
public class MainClass

{

main

    {

        try

        {

Class

ClassNotFoundException

        {

e

        }

    }

}



o/p:-
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDrive

NoClassDefFoundError:
NoClassDefFoundError is an error that is thrown when the Java Runtime System tries to load the definition of a class, and that class definition is no longer available. The required class definition was present at compile time, but it was missing at runtime.


class A

{

  // some code

}


public class B

{

main

    {

A

    }



}



When you compile the above program, two .class files will be generated. 

One is A.class and another one is B.class

If you remove the A.class file and run the B.class file, Java Runtime System will throw NoClassDefFoundError like below:

o/p:-
Exception in thread "main" java.lang.NoClassDefFoundError: A
at MainClass.main(MainClass.java:10)
Caused by: java.lang.ClassNotFoundException: A


printStackTrace():-
It's a method on Exception instances that prints the stack trace of the instance to System.err.
It's a very simple, but very useful tool for diagnosing an exceptions. It tells you what happened and where in the code this happened.
Here's an example of how it might be used in practice:

try {
    // ...
} catch (SomeException e) { 
    e.printStackTrace();
}