Welcome To The World Of Java

This site will teach you the basics of Java. It is not necessary to have any prior programming experience.
class ConsInfo {
 public static void main(String[] args) {
  if (args.length == 0) {
   System.out.println("PLEASE PASS THE CLASS NAME..!");
  } else {
   try {
    Class c = Class.forName(args[0]);
    printConsts(c);
   } catch (ClassNotFoundException cnfe) {
    System.out.println(args[0] + " DOES NOT EXISTS");
   }
  }
 }
 static void printConsts(Class c) {
  java.lang.reflect.Constructor Cons[] = c.getConstructors();
  System.out.println("NUMBER OF CONSTRUCTORS:" + Cons.length);
  System.out.println("NAME OF THE CONSTRUCTOR:"+c.getName());
  for (int i = 0; i < Cons.length; i++) {
   System.out.print(c.getName() + "(");
   Class cp[] = Cons[i].getParameterTypes();
   for (int j = 0; j < cp.length; j++) {
    System.out.print(cp[j].getName() + ")");
   }
   System.out.println("\b" + ")");
  }
 }
}
A name in the program is an identifier it may be class name or method name, variable name or label name.


Rules for defining Identifiers

1) A java identifier is a sequence of characters, where each character may be a letter from a-z or A-Z or a digit form 0-9 or currency symbol $ or connecting punctuation – , if we are using any other symbol we will get Compile time error “IllegalCharacter”.

2) Identifier should not be starts with digit.

3) There is no length limit for java identifiers but it is not recommended to take more than 15
length.

4) Java Identifiers are case sensitive

Example:

class FundaDemo 
{
    public static void main(String[] args)
    {
        int String = 10;
        System.out.println(String);
    }
}

Output- 10


Exercise- Which of the following are valid Identifiers

1) total#
2) all@hands
3) 123total
4) break
5) String
6) total_number
7) $_$
8) $ca$h

Ans- 5,6,7,8
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.io.*;
public class DbServ extends HttpServlet {
 ServletConfig sc = null;
 public void init(ServletConfig sc) throws ServletException {
  super.init(sc);
  this.sc = sc;
 }
 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  res.setContentType("text/html");
  PrintWriter pw = res.getWriter();
  String dname = sc.getInitParameter("dname");
  String url = sc.getInitParameter("url");
  String tab = sc.getInitParameter("tab");
  try {
   Class.forName(dname);
   Connection con = DriverManager.getConnection(url, "scott", "tiger");
   Statement st = con.createStatement();
   ResultSet rs = st.executeQuery("select * from " + tab);
   while (rs.next()) {
    pw.println("<h2>" + rs.getString(1) + "" + rs.getString(2) + "" + rs.getString(3) + "</h2>");
   }
   con.close();
  } catch (Exception e) {
   res.sendError(503, "PROBLEM IN DATABASE...");
  }
 }
}



web.xml:


<web-app>

<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>DbServ</servlet-class>
<init-param>
<param-name>dname</param-name>
<param-value>oracle.jdbc.driver.OracleDriver ()</param-value>
</init-param>
<init-param>
<param-name>url</param-name>
<param-value>jdbc:oracle:thin:@localhost:1521:Hanuman</param-value>
</init-param>
<init-param>
<param-name>tab</param-name>
<param-value>emp</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/dbdata</url-pattern>
</servlet-mapping>
</web-app>
package ddrs;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.io.*;
public class RetrieveDataBaseServ extends HttpServlet {
 public void doGet(HttpServletRequest req, HttpServletResponse res) {
  res.setContentType("text/html");
  PrintWriter pw = res.getWriter();
  try {
   DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
   Connection con = DriverManager.getConnection("oracle:jdbc:thin:@localhost:1521:Hanuman ", "scott ","tiger ");
    Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select * from emp");
    while (rs.next()) {
     pw.println(rs.getString(1) + " " + rs.getString(2));
    }
   } catch (Exception e) {
    res.sendError(504, "PROBLEM IN SERVLET...");
   }
  }
 }



<web-app>
<servlet>
<servlet-name>Babu</servlet-name>
<serclet-class>ddrs.RetrieveDataBaseServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Babu</servlet-name>
<url-pattern>Dinesh</url-pattern>
</servlet-mapping>
</web-app>
import javax.servlet.*;
import java.io.*;
public class First extends GenericServlet {
 public First() {
  System.out.println("I AM FROM DEFAULT CONSTRUCTOR...");
 }
 public void init() {
  System.out.println("I AM FROM init METHOD...");
 }
 public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
  System.out.println("I LOVE MY MOM...");
  System.out.println("I AM FROM service METHOD...");
 }
 public void destroy() {
  System.out.println("I AM FROM destroy METHOD...");
 }
}
1- Introduction 
2- OOPS
3- Interfaces
4- Packages
5- java.lang.String 
6- Wrapper classes 
7- Java.io 
8- Exception Handling 
9- MultiThreading 
10- Nested classes 
11- Enumaration & GC 
12- Collections 
13- Java.net 
14- Java.awt 
15- Swings 
16- JVM
import java.sql.*;
class ScrollResultSet {
 public static void main(String[] args) {
   try {
    Class.forName("Sun.jdbc.odbc.JdbcOdbcDriver");
    System.out.println("DRIVERS LOADED...");
    Connection con = DriverManager.getConnection("jdbc:odbc:oradsn", "scott", "tiger");
    System.out.println("CONNECTION ESTABLISHED...");
    Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    ResultSet rs = st.executeQuery("select * from emp");
    System.out.println("RECORDS IN THE TABLE...");
    while (rs.next()) {
     System.out.println(rs.getInt(1) + " " + rs.getString(2));
    }
    rs.first();
    System.out.println("FIRST RECORD...");
    System.out.println(rs.getInt(1) + " " + rs.getString(2));
    rs.absolute(3);
    System.out.println("THIRD RECORD...");
    System.out.println(rs.getInt(1) + " " + rs.getString(2));
    rs.last();
    System.out.println("LAST RECORD...");
    System.out.println(rs.getInt(1) + " " + rs.getString(2));
    rs.previous();
    rs.relative(-1);
    System.out.println("FIRST RECORD...");
    System.out.println(rs.getInt(1) + " " + rs.getString(2));
    con.close();
   } catch (Exception e) {
    System.out.println(e);
   }
  } // main
}; // ScrollResultSet
import java.sql.*;
import java.io.*;
import java.util.*;
class RBFConcept {
 public static void main(String[] args) {
   try {
    FileInputStream fis = new FileInputStream("rbfdb.prop");
    Properties p = new Properties();
    p.load(fis);
    String dname = (String) p.get("Dname");
    String url = (String) p.get("URL");
    String username = (String) p.get("Uname");
    String password = (String) p.get("Pwd");
    String tablename = (String) p.get("Tablename");
    // loading drivers and obtaining connection
    Class.forName(dname);
    System.out.println("DRIVERS LOADED...");
    Connection con = DriverManager.getConnection(url, username, password);
    System.out.println("CONNECTION CREATED...");
    // executing query
    Statement st = con.createStatement();
    ResultSet rs = st.executeQuery("select * from" + tablename);
    ResultSetMetaData rsmd = rs.getMetaData();
    // printing column names
    System.out.println("=================================");
    for (int i = 1; i <= rsmd.getColumnCount(); i++) {
     System.out.print(rsmd.getColumnName(i) + " ");
    }
    System.out.println("");
    System.out.println("=================================");
    // printing the data
    while (rs.next()) {
     for (int j = 1; j <= rsmd.getColumnCount(); j++) {
      System.out.print(rs.getString(j) + " ");
     }
    }
    con.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  } // main
}   // RSFConcept
import java.sql.*;
class XSelect {
 public static void main(String[] args) {
   try {
    DriverManager.registerDriver(new 
    Sun.jdbc.odbc.JdbcOdbcDriver());
    System.out.println("DRIVERS LOADED...");
    Connection con = DriverManager.getConnection("jdbc:odbc:xldsn");
    System.out.println("CONNECTION ESTABLISHED...");
    Statement st = con.createStatement();
    ResultSet rs = st.executeQuery("select * from [student$]");
    while (rs.next()) {
     System.out.println(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3));
    }
    con.close();
   } catch (SQLException sqle) {
    sqle.printStackTrace();
   }
  } // main
} // XSelect
Assertions has introduced in 1.4 version. The main objective of assertions is to perform debugging. The traditional way of debugging is to use System.out.println’s. But the main disadvantage of this approach is compulsory we should remove these S.O.P’s after fixing the problem other wise these will execute at run time. Which may effect performance of the system. It may reduce readability of the code and disturbs logging mechanism.

To resolve all these problems sun people has introduces Assertions concept in 1.4 version. The main advantage of assertions is we can enable or disable assertions based on our requirement. But by default assertions are disabled.
Assertions concept we have to use in Test environment or in Development environment but not in the production.


Identifier Vs Keyword
Assert keyword has introduced in 1.4 version hence from 1.4 version on words we are not allowed to use assert as identifier.
Example:-

class Test {
 public static void main(String[] args) {
  int assert = 10;
  System.out.println("assert");
 }

}

in 1.4 or 1.5 if we compile javac assert.java then we will get the following C.E as of release 1.4 assert is a keyword and may not used as an identifier.

javac –source 1.3 assert.java
java Test


Types of assert statement
1) simple assert.
2) Augmented assert.

Simple assert
Syntax: assert <boolean expression> ;
assert(b);

If b is true then normal continuation follows. Else the program will terminate abnormally can rise assertion error.
Example:-

class Test {
 public static void main(String[] args) {
  int x = 10;
  :
  :
  assert(x > 10)
  System.out.println(x);
 }

}

1) javac Test.java
2) java Test
in this case assert statement won’t be executed because it is disable by default.
3) java –ea Test

Then generates assertion error.
Augmented Version Syntax: assert <boolean expression> : <message expression> ;
Assert e1:e2;
‘e1’ - should be boolean type.
‘e2’ - any thing is allowed including method calls also
Example:-

class Test {
 public static void main(String[] args) {
  int x = 10;
     ;
     ;
  assert(x > 10): "here the value of x should be > 10 but it is " + x;
  System.out.println(x);
 }

}

javac Test.java
java –ea Test

Note: assert e1:e2
Here ‘e2’ will be executed iff ‘e1’ is false.

Example:-

class Test {
 public static void main(String[] args) {
  int x = 10;;;
  assert(x == 0): ++x;
  System.out.println(x);
 }

}

javac Test.java
java –ea Test


assert(e1):e2;

for e2 any thing is allowed including method calls also But void return type method calls are not allowed. Violation leads to compile time error.
Example:-

class Test {
 public static void main(String[] args) {
  int x = 10;;;
  assert(x > 0): m1();
  System.out.println(x);
 }
 public static void m1() {
  return;
 }
}

javac Test.java
java –ea Test


Various Run Time Flags
1) -ea - To enable assertions in every non-system class(i.e user defined
class)
2) -enableassertions - To enable assertions in every non-system class(Exactly similar
to -ea)
3) -da - To disable assertions in every non-system class.
4) -isableassertions - To disable assertions in every non-system class.(Exactly similar to -da)
5) -esa - To enable assertions in every system class
6) -enablesystemassertion - similar to -esa
7) –dsa - To disable assertions in every system class.
8) -disablesystemassertions - similar to ‘-dsa’
Ex:-
java –ea –esa –da –dsa –ea Test
All the flags will execute from left to right and there is no priority difference b/w enabling and disabling

- To enable assertions only in the ‘A- Class’
java -ea:Pack1.A
- To enable assertions only in B and D
java -ea:Pack1.B -ea:Pack1.Pack2.D
- To enable assertion in all classes of Pack1 and its sub package classes also.
java –ea:Pack1…
- To enable assertions in all classes present in pack1 but not those present in pack2
java -ea:Pack1… -da:Pack1.Pack2…
Note:- we can enable assertions either class wise or package wise also.

Proper and Improper Use of assertions
1) It is improper to use assert statement for validating the arguments of a public method.

public void withdraw(double amount) {
 assert(amount >= 100);
}

C.E:- No C.E, R.E it is improper use.

2) It is improper to use assertions for validating command line argument also, because these are arguments
to public main method.
3) It is proper to use assertions for validating private method argument.
4) It is improper to mix programming language with assert statement.
5) In our code if there is any place where the control is not allowed to reach. It is the best place to use the
assert statement.
Pack1
A.class
B.class
C.class
D.class
Pack2

Ex:-

switch (month) {
 case 1:
  ....
  ....
  case 2:
   ....
   ....
  case 3:
   ....
   ....
  case 4:
   ....
   ....:
   :
   :
   case 12:
  ....
  ....
  default:
   assert(false);
}

AssertionError
It is the child class of Error and it is unchecked.
It is not recommended to catch AssertionError by using catch Block. It is stupid type of activity.
Example:-

class Test {
 public static void main(String arg[]) {
  int x = 10;;;;
  try {
   assert(x > 10);
  } catch (AssertionError e) {
   System.out.println("I am stupid...Because I am catching
    Assertion ");
   }
  }
 }
1. Simple:-
Java is a simple programming language because:
a- Java technology has eliminated all the difficult and confusion oriented concepts like pointers, multiple inheritance in the java language.
b- The c,cpp syntaxes easy to understand and easy to write. Java maintains C and CPP syntax mainly hence java is simple language.
c- Java tech takes less time to compile and execute the program.


2. Object Oriented:-
Java is object oriented technology because to represent total data in the form of object. By using object reference we are calling all the methods, variables which is present in that class. The total java language is dependent on object only hence we can say java is a object oriented technology.


3. Platform Independent :-
Compile the Java program on one OS (operating system) that compiled file can execute in any OS(operating system) is called Platform Independent Nature. The java is platform independent language. The java applications allows its applications compilation one operating system that compiled (.class) files can be executed in any operating system.





4. Architectural Neutral:-

Java tech applications compiled in one Architecture (hardware----RAM, Hard Disk) and that Compiled program runs on any hardware architecture(hardware) is called Architectural Neutral.

5. Portable:-
In Java tech the applications are compiled and executed in any OS(operating system) and any Architecture(hardware) hence we can say java is a portable language.

6. Robust:-
Any technology if it is good at two main areas it is said to be ROBUST

1 Exception Handling
2 Memory Allocation

JAVA is Robust because

a. JAVA is having very good predefined Exception Handling mechanism whenever we are getting exception we are having meaning full information.
b. JAVA is having very good memory management system that is Dynamic Memory (at runtime the memory is allocated) Allocation which allocates and deallocates memory for objects at runtime.

7. Secure:-
To provide implicit security Java provide one component inside JVM called Security Manager.

To provide explicit security for the Java applications we are having very good predefined library in the form of java.Security.package.

Web security for web applications we are having JAAS(Java Authentication and Authorization Services) for distributed applications.

8. Dynamic:-
Java is dynamic technology it follows dynamic memory allocation(at runtime the memory is allocated) and dynamic loading to perform the operations.

9. Distributed:-
By using JAVA technology we are preparing standalone applications and Distributed applications.

Standalone applications are java applications it doesn’t need client server architecture. web applications are java applications it need client server architecture.

Distributed applications are the applications the project code is distributed in multiple number of jvm’s.

10. Multithreaded: -
Thread is a light weight process and a small task in large program.

If any tech allows executing single thread at a time such type of technologies is called single threaded technology.

If any technology allows creating and executing more than one thread called as Multithreaded technology called JAVA.

11. Interpretive:-
JAVA tech is both Interpretive and Completive by using Interpretator we are converting source code into byte code and the interpretator is a part of JVM.

12. High Performance:-
If any technology having features like Robust, Security, Platform Independent, Dynamic and so on then that technology is high performance.
1- Core Java Notes Naresh Tech-      Download

2- Core Java Notes Satya Technology- Download

3- Core Java Notes Ratan Sir-        Download