Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at diehardtechy@gmail.com

Wednesday, June 25, 2014

OCJP Question #24

What will be the output of the following code segment written in Java.




Answer: C

Explanation: 

In segment 'if (valid)' valid must be of type Boolean, but it is a string.

This makes the compilation fail.

Detailed Explanation:

If is a conditional statement it requires Boolean value to be passed , since valid is a type of String not of Boolean, so it will make compilation of the program fail. 

This holds true for while loop also.


More Questions on OCJP : Click here 

More Questions on Hibernate : Click here 

Saturday, June 21, 2014

How to configure Tomcat and run first JSP application. (Without any IDE)

Before you proceed with your first program of JSP, please make sure you have following software's installed.


1.Jdk 1.6+
2.MySQL 5.0+
3.Tomcat 7.0+

Steps to install Tomcat:

1. Download tomcat server from apache's official website.

2. Install the server.

3. Provide port number of your choice or be it default, make a not of whatever the port number you are using.

4. Go to Tomcat 7.0 folder of your installation directory,lib,and add servletapi.jar file in to class path.

5. If you are using MySQL as your database ,make sure to download mysql-connector-java-5.1.30.jar and place it in Tomcat 7.0\lib\ folder.

6. Start the server:

You can start the server in any of the following way.

A. Go to Tomcat 7.0\bin\ directory and right click on Tomcat7 & run as administrator.




this will give you the console view of Tomcat. (Feature to Debug easily. )
Console View of tomcat

B. Search in windows , right click on configure tomcat\ run as administrator.Click start. 




7.Server should start successfully.

8. To check if server is properly installed or not.

A. Open your browser
B. go to http://localhost:portnumber (port number is same which you provided in step 3.)
C. if you have properly installed , you will see the home page of Tomcat.




Write a simple JSP application to add id, first_name, last_name into database.

What you need to do. 


1.Create a folder say (FirstApp) in Tomcat 7\webapps\ directory.

2. Copy WEB-INF folder from Tomcat 7.0\webapps\examples folder and paste it in FirstApp folder which you created above.

3. Create a table say employee with e_id, first_name, last_name column in MySQL database.

4. Create a HTML file (say EmpInfo.html)and place it in Tomcat 7.0\webapps\FirstApp folder.


EmpInfo.html

<html>
<body>
<form action="insert.jsp">
<center>
<table cellspacing="10px" border="2">

<tr>
<td>
Enter Emp. ID:
<td>
<input type="text" name="t1" />
<tr>
<td>
Enter first name:
<td>
<input type="text" name="t" />
<tr>
<td>
Enter last name:
<td>
<input type="text" name="t3"/>
<tr>
<td colspan=2 align="right">
<input type="submit" name="b1" value="Submit" />
</table>
</center>
</form>
</body>

</html>

It will look like this:


EmpInfo.html


5. Write a JSP program (insert.jsp) to insert record in database which user has entered in EmpInfo.html and place it in Tomcat 7.0\webapps\FirstApp folder.


insert.jsp


<%@page language="java" contentType="text/html" import="java.sql.*" %>
<%
String eid=request.getParameter("t1");
String fname=request.getParameter("t2");
String lname=request.getParameter("t3");
int empid=Integer.parseInt(eid);

Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/ttest","root","root");
Statement st=con.createStatement();
int i=st.executeUpdate("INSERT INTO employee (eid,first_name, last_name) values ("+empid+",'"+fname+"','"+lname+"')");
if(i>0)
{
%>

 <h1>"Value added successfully"  </h1>

<%
}
else
{
%>
 <h1>"Value not added successfully"  </h1>
<%
}


%>

How to execute. 

1.Start tomcat server.
2.Launch browser.
3.type http://localhost:portnumber/FirstApp/EmpInfo.html
4.Enter some value and click enter.
5.A page with message as Value added successfully will be displayed. 




If you run into any problem, feel free to ask. (If possible please attach screen shot of problem.)

Wednesday, June 18, 2014

Difference between session.save() and session.persist() method of Hibernate.



What is the difference between session.save() method and session.persist() method of hibernate API.

ses.save() & ses.persist() both methods are used to save/insert the record in database using hibernate specific persistence logic. 


Difference between session.save() and session.persist() method:


1.session.save() method returns generated identity value as the return value of the method call, as its return type is java.io.Serializable. Whereas session.persist() method does not returns anything as its return type is void.

2. Using the return value as result session.save() method call we can get to know what record value has been added into Database, moreover we can check if value has been added in database or not using if...else condition on returned value. 

3. session.save() method is useful on exception handling perspective but it take comparatively more time to execute than session.persist() method.

Example code using session.save() method.


import org.hibernate.*;
import org.hibernate.cfg.*;

class SaveDemo
{
public static void main(String[] args) 
{
Configuration cfg=new Configuration();
cfg=cfg.configure("Hibernate.cfg.xml");
SessionFactory sfactory=cfg.buildSessionFactory();
Session ses=sfactory.openSession();
Transaction tx=ses.beginTransaction();
EmpBean e=new EmpBean();
e.setId(101);
e.setEmail("diehardtechy@gmail.com");
int i=(Integer)ses.save(e);
if(i>0)
{
System.out.println("Record added to database "+" "+"Employee ID is : "+i);
}
else
{
System.out.println("Something strange has happend, need not to panic ! ");
}
tx.commit();
tx.close();
ses.close();
}
}


Example code using session.persist() method.


import org.hibernate.*;
import org.hibernate.cfg.*;

class PersistDemo
{
public static void main(String[] args) 
{
Configuration cfg=new Configuration();
cfg=cfg.configure("Hibernate.cfg.xml");
SessionFactory sfactory=cfg.buildSessionFactory();
Session ses=sfactory.openSession();
Transaction tx=ses.beginTransaction();
EmpBean e=new EmpBean();
e.setId(101);
e.setEmail("diehardtechy@gmail.com");
ses.persist(e); /* Does not return anything */
tx.commit();
tx.close();
ses.close();
}
}

Prototype of save() method: 

public Serializable save(Object object)throws HibernateException

Prototye of persist() method:

public void persist(Object object)throws HibernateException


If you run into problem or got more questions related to hibernate , feel free to ask in comment section. (If possible please attach screen shot of problem.)

Smartphones in range between 15500 to 18000 : Android/Window

In todays date smartphones are the need of everyone, be it student or professionals every one wants to connect with their friends on social networking applications like facebook, whatsapp, wechat, line, skype, instagram etc. 

Smart phone has it all, smartphone provides features like scanner, high definition video recording, connect to office through phone, pdf reader and much more ..

As smart phones are best at their work but they cost fancy too, for people who want to purchase mid range phone say 15500-18000 , choosing a smart phone can be a tedious job.

Well, you dont need to worry about it, we have compiled the list of best available phone in range starting from 15500 to 18000.


#1 Samsung Galaxy S4 Mini 

Samsung is a trusted and most loved brand as of date in India. Samsung offers smart phones with affordable prices & best look. Samsung Galaxy s4 mini is the phone which has all the features starting from latest version of android to support with all the app.





#2 Nokia Lumia 1320

Nokia's windows OS for mobile is what Nokia is most proud of. Nokia Lumia with Awesome look & features is an absolutely good choice for this money range. Lumia have interactive UI adding stars in its look. 





#3 BlackBerry Q5

Blackberry Q5 is for all those who want style with smart phone. A royal look with incomparable feature makes black berry stand out of queue.  Those who prefer keypad over touch screens, this phone is one they are looking for.





#4 HTC Desire SV

HTC Desire will always be in demand for its touch quality along with all the features which every other smart phone provides. A unique shape of phone makes HTC choice of thousand customers world wide.



#5 LG G Pro Lite D686

LG : LG g pro lite phone is slim, good looking , wide smart phone. Big in size with Android v4.1 (Jelly Bean) operating system LG is all the way right choice for your money . It has 1 GHz Dual Core processor with 8 Megapixel camera. 




Comment your views , keep visiting us.

Ocjp practice question #23

  What will be the output of the following java Program ?


Explanation: 


Within main z is assigned 6. z is printed. Output: 6


Within doStuff z is assigned 5. DoStuff2 locally sets z to 4 (but MyScope.z is set to 4), but in Dostuff z is still 5. z is printed. Output: 5


Again z is printed within main (with local z set to 6). Output: 6 


Finally MyScope.z is printed. MyScope.z has been set to 4 within doStuff2(). Output: 4

Answer A is correct choice.


How to run first program of Hibernate : A beginner's guide

Before we proceed further on how to start with hibernate and how to execute your first hibernate program.Please make sure that you have following software ready.

1. Java 1.6 or +
2. MySQL 5 or +/Oracle 10G

Make sure you have Employee table with eid, first_name, last_name. email column. 

Step by step procedure of how to run first hibernate program

  1. Download latest version of hibernate software (jar files) from http://sourceforge.net/projects/hibernate/

  2. Unzip the zip file which you downloaded in step 1.

  3. Add all jar files of hibernate-search-4.5.1.Final\dist\lib\required folder to class path,separated by semi colon.

  4. Add jar files of hibernate-search-4.5.1.Final\dist folder to class path, separated by semi colon.

  5. If you are using Oracle as your database then also add oracle related jar file to class path.

  6. Create a directory for all hibernate related programs you will practice from here onward.
Your directory structure should look like this.


  • EmpBean.java is a simple Java file which have getter and setter methods.(All members of this class should be non-static only)

  • Hibernate.cfg.xml is a hibernate configuration file, which contains property related information.Like DB software related url, driver information etc.

  • Hibernate.map.xml is a hibernate mapping file, which is used to map java pojo class(EmpBean.java) members with Database table column.

  • FirstProgram.java is a java file which contains hibernate based persistence logic.

Download above mentioned all 4 file here: 

Compile both java file and run.

If you run into any problem , feel free to ask .(If possible attach screen shot of the problem)

Monday, June 16, 2014

OCJP practice question #21


OCJP PRACTICE QUESTION: 

What will be the output of given OCJP question below.







Explanation :
Option E is the correct answer.

Option E is correct as the code fails to compile. In the main method signature, we have declared the argument as “String[] a” and also we have tried to create for loop with int variable named as "a" but it is illegal because we have already declared variable with name "a" (as main method argument).

This will cause a compile time error since we can't declare two variables with same name inside a same scope.
Here both method argument and the variable declared inside the for loop belong to the same local scope.

Option A, B, C and D are incorrect as code fails to compile. However option B could be correct if we changed the variable name of argument variable or for loop variable.

REFERENCE:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html

The correct answer is: Compilation fails.

What is the eligibility to take oracle java certification, exam price and everything you need to know.

Hello ,

This article is about what is the eligibility criteria for OCA Java SE 7 programmer, exam fees,
exam topics, topics in detail and everything else you need to know about the program.

Oracle certified associate is the first step to take any other java certification. When you are OCA certified , you are recognized, your programming skills are appreciated.

Basic exam details:


Exam Number:

1Z0-803
Associated Certifications:Oracle Certified Associate, Java SE 7 Programmer
Exam Product Version:Java Standard edition
Prerequisites
Exam Price:
No prerequisites
Rs 8769
 

Duration:120 minutes
Number of Questions:70
Passing Score:63% 
Validated Against:This exam has been validated against SE 7.
format:Multiple Choice

Exam syllabus:


Java Basics
  • Define the scope of variables
  • Define the structure of a Java class
  • Create executable Java applications with a main method
  • Import other Java packages to make them accessible in your code
Working With Java Data Types
  • Declare and initialize variables
  • Differentiate between object reference variables and primitive variables
  • Read or write to object fields
  • Explain an Object's Lifecycle (creation, "dereference" and garbage collection)
  • Call methods on objects
  • Manipulate data using the StringBuilder class and its methods
  • Creating and manipulating Strings
Using Operators and Decision Constructs  
  • Use Java operators
  • Use parenthesis to override operator precedence
  • Test equality between Strings and other objects using == and equals ()
  • Create if and if/else constructs
  • Use a switch statement
Creating and Using Arrays
  • Declare, instantiate, initialize and use a one-dimensional array
  • Declare, instantiate, initialize and use multi-dimensional array
  • Declare and use an ArrayList
Using Loop Constructs
  • Create and use while loops
  • Create and use for loops including the enhanced for loop
  • Create and use do/while loops
  • Compare loop constructs
  • Use break and continue  
Working with Methods and Encapsulation
  • Create methods with arguments and return values
  • Apply the static keyword  to methods and fields  
  • Create an overloaded method
  • Differentiate between default and user defined constructors
  • Create and overload constructors
  • Apply access modifiers
  • Apply encapsulation principles to a class
  • Determine the effect upon object references and primitive values when they are passed  into methods that change the values
Working with Inheritance
  • Implement inheritance
  • Develop code that demonstrates the use of polymorphism
  • Differentiate between the type of a reference and the type of an object
  • Determine when casting is necessary
  • Use super and this to access objects and constructors
  • Use abstract classes and interfaces
Handling Exceptions
  • Differentiate among checked exceptions, RuntimeExceptions and Errors
  • Create a try-catch block and determine how exceptions alter normal program flow
  • Describe what Exceptions are used for in Java
  • Invoke a method that throws an exception
  • Recognize common exception classes and categories

Friday, June 13, 2014

10 OCJP questions to puzzle you

We are compiling 10 OCJP question with explanation for every question.
Use the basic java concept to answer all the below questions.


Question :1 

Explanation:

Choice B is correct.


When we compile above code we wont get any error as it is legal to write class in 

interface.


Question :2

Explanation:

Choice A is correct.


private members of a class can be accessed with in the class. According to this statement 

the inner class can also access the private member of a outer class


Question :3


Explanation:

Choice A is correct.


Arrays are objects because of which we will get true. InstanceOf can be used as variable 

so 10 will be printed


Question :4


Explanation:

Choice B is correct.


Creating File instance will not create a file, once we say createNewFile() with file instance 

then only a file will be created. so first f.exists() will give false and second f.exists() will 

give true

Question :5



Question :6

Explanation:

Choice C is correct.


Index based remove() method will return element at the specified position in this list.


Question :7


Explanation:

Choice A is correct.


Thread prioriy will have same priority as the priority of thread created it.

Question :8


Explanation:

Choice D is correct.


Character class don't have constructor which accepts String as argument.

Question :9



Question :10



You can check more questions on SCJP here.