Showing posts with label JavaSE. Show all posts
Showing posts with label JavaSE. Show all posts

Java Programs for Practice



Number Based Logical Programs

1. Java program to find perfect numbers


2. Java program to print perfect numbers from 1 to 1000

3. Java program to split number into digits.

4. Java program to swap two array.

5. Java program to find NCR factor of given number.

6. Java program to find generic root.

7. Add two number without using addition operator.

8. Java program to sum digits of a number.

9. Java program to reverse a number.

Number System and Conversion 

1. Java program for multiplication of two binary numbers.

2. Java program for addition of two binary numbers.

3. Java program for binary to hexadecimal conversion.

4. Java program for binary to decimal conversion.

5. Java program for octal to binary conversion.

6. Java program for octal to decimal.

7. Java program to convert decimal to binary number.

8. Java program to convert decimal to octal number.

9. Java program to convert decimal to hexadecimal number.

Series Based Programs

1. Java program to find out the sum of A.P. series.

2. Java program to calculate the sum of GP series.

3. Java program to find out the sum of given H.P. Series.

4. Print Sum of series 1+ (1+2) + (1+2+3).... (1+2+3+....n)

5. Print Sum of Series (1/1^2) + (1/2^2) + (1/3^2)....1/n^2

6. Print sum of series (1/1^3) – (1/2^3) + (1/3^3)....1/n^3

7. Print Series 1, 11, 111, 1111....n terms in Java.

8. Print Series 1, 12, 123, 1234.....n in Java.

9. Print Series 1, -3, 5, -7.....n terms in Java.

10. Print Series 2, -4, 6, -8....n terms in Java

11. Java program to print Tribonacci Series.

12. Java program to print fibonacci series.

String Based Programs

1. Program to find the frequency of one string in another.

2. Java program to remove vowels from a string.

3. Program to remove common characters from two strings.

4. Program to finding Shortest and Longest Words in a String.

5. Java program to reverse a String without using direct method.

6. Java program to input name, middle name and surname of a person and print only the initials.

7. Program to remove duplicates characters from given String.

8. Java program to count the occurrence of any character in given String.

9. Java program to find palindromic substring in a string.

10. Java program to accept a string and print each character of the string along with its ASCII code.

Common Logical Programs

1. Java program to find whether given no. is Armstrong or not.

2. Generate prime numbers between 1 & given number

3. Calculate Factorial of a number using recursion

4. Java program to check Palindrome Number.

5. Java program to calculate the Simple Interest.

6. Java program to show all function of bank and generate account number dyanamically.

7. Java program to find out the HCF and LCF.

8. Java program to test the Prime number.

9. Java program to Demonstrate Type Casting.

10. Find the average, sum, min and max of the N numbers Using user Input in Java.

Servlet Based Programs

1. Write a servlet which accepts client request and display the client requested data on the browser?

2. Write a servlet which accepts product details from html form and stores the product details into database?

3. Develop a flexible servlet that should display the data of the database irrespective driver name, table name and dsn name?

4. Write a servlet which retrieves the data from database?

5. Write a servlet which illustrate the concept of ServletContext?

6. Write a servlet which displays current system date and time?

7. Write a servlet which displays a message “I LOVE MY MOM”?

8. Write a servlet which retrieves the data from database?

JDBC Based Programs

1. Write a java program to create a table through frontend application?

2. Write a java program which illustrates the concept of Batch processing?

3. Write a java program which illustrates the concept of updatable ResultSet?

4. Write a java program which illustrates the concept of scrollable ResultSet?

5. Write a java program which points the data of a table along with its column names?

6. Write a java program which illustrates the concept of resource bundle file or how to develop a flexible jdbc application along with its metadata?

7. Write a java program which illustrates the concept of DatabaseMetaData and ResultSetMetaData?

8. Write a jdbc program to retrieve the data from excel?

9. Write a java program which illustrates the concept of procedure?

10. Write a java program which illustrates the concept of function?

11. Write a java program to retrieve the records from a specified database by accepting input from keyboard?

12. Write a java program to insert a record in dept database by accepting the data from keyboard at runtime using dynamic queries?

13. Write a java program to retrieve the data from emp database?

14. Write a jdbc program which will insert a record in the Student database?

Reflection Based Programs

1. Write a java program which will de-Serializable from the specified file?

2. Write a java program which will save the Serializable sub class object into a file?

3. Write a java program to print fields or data members of a class?

4. Write a java program to obtain constructors of a class?

5. Write a java program to obtain information about methods which are present in a class?

6. Write a java program to print super class hierarchy at a current class which is passed from command prompt?

7. Write a java program to find name of the class and its super class name by passing the class name at runtime?

8. Write a java program to print name of the current class and its super class name?

Logical Programs

1. How can you determine if String has all Unique Characters.?

2. How to reverse a String without using any direct method.?

3 How to convert String to integer without using any direct method in Java.?

4. How to find the missing values from an sorted array.?

5. How to reverse an array without using any built in method and any other array.?

6. How to remove specific character from an String in Java.?

7. How to find the caller of a method in Java.?

8. How to call private method from another class in java.?

Matrix Based Program

1. Addition , Substraction and trace of two Matrix in Java.

2. Find the Transpose of given Matrix in Java.

3. Program for Matrix multiplication in Java.

4. Calculate the Sum of the Elements of each Row & Column of given Matrix in Java.

5. Check if a given Matrix is an Identity (Unit) Matrix or not in Java

6. Find the Frequency of Odd & Even Numbers in the given Matrix in Java

7. Determine if a given Matrix is a Sparse Matrix in Java.

Pyramid Based Programs

1. Write a program to generate a following #'s triangle:



2. Write a program to generate a following @'s triangle:



3. Write a Java program to print the following triangle:




4. Write a Java program to display the following rhombus symbol structure:



5. Write a Java program to display the following number rhombus structure:



6. Write a Java program to print the following number pyramid:





7. Write a Java program to display the following character rhombus structure:



Develop a flexible servlet that should display the data of the database irrespective driver name, table name and dsn name?



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>


Write a servlet which retrieves the data from database?



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>


Write a servlet which displays a message “I LOVE MY MOM”?



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...");
 }
}


Core Java Tutorial By Durga Sir and Natraj Sir



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


Write a java program which illustrates the concept of scrollable ResultSet?



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


Write a java program which illustrates the concept of resource bundle file or how to develop a flexible jdbc application along with its metadata?



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


Write a jdbc program to retrieve the data from excel?



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


Write a java program to retrieve the records from a specified database by accepting input from keyboard?



import java.sql.*;
import java.io.*;
class SelectDataRun {
 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...");
    PreparedStatement ps = con.prepareStatement("select * from dept where deptno");
    DataInputStream dis = new DataInputStream(System.in);
    System.out.println("ENTER DEPARTMENT NUMBER : ");
    String s1 = dis.readLine();
    int dno = Integer.parseInt(s1);
    ps.setInt(1, dno);
    ResultSet rs = ps.executeQuery();
    while (rs.next()) {
     System.out.print(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3));
    }
    con.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  } // main
}   // SelectDataRun


Write a java program which will de-Serializable from the specified file?



import ep.Emp;
import java.io.*;
class Dserp {
 public static void main(String[] args) throws Exception {
  Emp eo1 = new Emp();
  FileInputStream fis = new FileInputStream("employee");
  ObjectInputStream ois = new ObjectInputStream(fis);
  Object obj = ois.readObject();
  eo1 = (Emp) obj;
  System.out.println("EMP NO : " + eo1.getEmpno());
  System.out.println("EMP NAME : " + eo1.getEname());
  System.out.println("EMP SALARY : " + eo1.getSal());
  ois.close();
  fis.close();
 }
}

Output:

EMP NO : 100
EMP NAME : KVR
EMP SAL : 10000.0


Write a java program which will save the Serializable sub class object into a file?



import java.io.*;
class serp {
 public static void main(String[] args) throws Exception {
  Emp eo = new Emp();
  eo.setEmpno(100);
  eo.setEname("KVR");
  eo.setSal(10000.00 f);
  FileOutputStream fos=new FileOutputStream("employee");
  ObjectOutputStream oos = new ObjectOutputStream(fos);
  oos.writeObject(eo);
  System.out.println("EMPLOYEE OBJECT SAVED SUCCESSFULLY");
  oos.close();
  fos.close();
 }
}

Output:

EMPLOYEE OBJECT SAVED SUCCESSFULLY...


Write a java program to print fields or data members of a class?



import java.lang.reflect.Field;
class Fields {
 void printFields(Class c) {
  Field f[] = c.getFields();
  System.out.println("NUMBER OF FIELDS:"+ f.length);
  for (int i = 0; i < f.length; i++) {
   String fname = f[i].getName();
   Class s = f[i].getType();
   String ftype = s.getName();
   System.out.println(ftype + " " + fname);
  }
 }
}
class FieldsDemo {
 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]);
    Fields fs = new Fields();
    fs.printFields(c);
   } catch (ClassNotFoundException cnfe) {
    System.out.println(args[0] + "NOT FOUND");
   }
  }
 }
}


Write a java program to obtain information about methods which are present in a class?



import java.lang.reflect.*;
class MetInfo {
 public static void main(String[] args) {
  try {
   if (args.length == 0) {
    System.out.println("PLEASE PASS THE CLASS NAME");
   } else {
    Class c = Class.forName(args[0]);
    printMethods(c);
   }
  } catch (ClassNotFoundException cnfe) {
   System.out.println(args[0] + " DOES NOT EXISTS");
  }
 }
 static void printMethods(Class c) {
  Method m[] = c.getMethods();
  System.out.println("NUMBER OF METHODS:"+ m.length);
  System.out.println("NAME OF THE CLASS:"+ c.getName());
  for (int i = 0; i < m.length; i++) {
   Class c1 = m[i].getReturnType();
   String rtype = c1.getName();
   String mname = m[i].getName();
   System.out.print(rtype + " " + mname + "(");
   Class mp[] = m[i].getParameterTypes();
   for (int j = 0; j < mp.length; j++) {
    String ptype = mp[i].getName();
    System.out.print(ptype + ",");
   }
   System.out.println("\b" + ")");
  }
 }
}


Write a java program to obtain constructors of a class?



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" + ")");
  }
 }
}


Assertions in Java



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 ");
   }
  }
 }