Saturday, June 13, 2015

Difference Between Get And Load Methods in java

Q. What is the difference between hibernate get and load methods?

A. The load() method is older; get() was added to Hibernate’s API due to user request. The difference is trivial: 


The following Hibernate code snippet retrieves a User object from the database:  User user = (User) session.get(User.class, userID); 


The get() method is special because the identifier uniquely identifies a single instance of a class. Hence it’s common for applications to use the identifier as a convenient handle to a persistent object. Retrieval by identifier can use the cache when retrieving an object, avoiding a database hit if the object is already cached.
Hibernate also provides a load() method:  User user = (User) session.load(User.class, userID);
If load() can’t find the object in the cache or database, an exception is thrown. The load() method never returns null. The get() method returns 


null if the object can’t be found. The load() method may return a proxy instead of a real persistent instance. A proxy is a placeholder instance of a runtime-generated subclass (through cglib or Javassist) of a mapped persistent class, it can initialize itself if any method is called that is not the mapped database identifier getter-method. On the other hand, get() never returns a proxy. Choosing between get() and load() is easy: If you’re certain the persistent object exists, and nonexistence would be considered exceptional, load() is a good option. If you aren’t certain there is a persistent instance with the given 


identifier, use get() and test the return value to see if it’s null. Using load() has a further implication: The application may retrieve a valid reference (a proxy) to a persistent instance without hitting the database to retrieve its persistent state. So load() might not throw an exception when it doesn’t find the persistent object
in the cache or database; the exception would be thrown later, when the proxy is accessed.

Hibernate Interview Questions


Q. What type of transaction management is supported in hibernate? 
A. Hibernate communicates with the database via a JDBC Connection; hence it must support both managed and non-managed transactions.
    non-managed in web containers:
 
<bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager">
    <property name="sessionFactory">
        <ref local="sessionFactory"/>
    </property>
</bean>
 
    managed in application server using JTA:
 
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager.">
    <property name="sessionFactory">
        <ref local="sessionFactory"/>
    </property>
</bean>



Q. What is lazy loading and how do you achieve that in hibernate?
 
A. Lazy setting decides whether to load child objects while loading the Parent Object. You need to specify parent class.Lazy = true in hibernate mapping file. By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent. In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object. But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database. Examples: Address child of User class can be made lazy if it is not required frequently. But you may need to load the Author object for Book parent whenever you deal with the book for online bookshop.
Hibernate does not support lazy initialization for detached objects. Access to a lazy association outside of the context of an open Hibernate session will result in an exception



Q. What are the different fetching strategy in Hibernate?
 
A. Hibernate3 defines the following fetching strategies:
 
Join fetching - Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN.
Select fetching - a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.
Subselect fetching - a second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.Batch fetching - an optimization strategy for select fetching - Hibernate retrieves a batch of entity instances or collections in a single SELECT, by specifying a list of primary keys or foreign keys.



Q. What are different types of cache hibernate supports ?
 
A. Caching is widely used for optimizing database applications. Hibernate uses two different caches for objects: first-level cache and second-level cache. First-level cache is associated with the Session object, while second-level cache is associated with the Session Factory object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will

generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications. To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level between transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided. In addition, you can use a query-level cache if you need to cache actual query results, rather than just persistent objects. The query cache should always be used in conjunction with the second-level cache. Hibernate supports the following open-source cache implementations out-of-the-box: 


 


  • EHCache is a fast, lightweight, and easy-to-use in-process cache. It supports read-only and read/write caching, and memory- and disk-based caching. However, it does not support clustering.
  • OSCache is another open-source caching solution. It is part of a larger package, which also provides caching functionalities for JSP pages or arbitrary objects. It is a powerful and flexible package, which, like EHCache, supports read-only and read/write caching, and memory- and disk-based caching. It also provides basic support for clustering via either JavaGroups or JMS.
  • SwarmCache is a simple cluster-based caching solution based on JavaGroups. It supports read-only or nonstrict read/write caching (the next section explains this term). This type of cache is appropriate for applications that typically have many more read operations than write operations.
  • JBoss TreeCache is a powerful replicated (synchronous or asynchronous) and transactional cache. Use this solution if you really need a true transaction-capable caching architecture.
  • Commercial Tangosol Coherence cache.  
    Q. What are the different caching strategies?
    A. The following four caching strategies are available:
    • Read-only: This strategy is useful for data that is read frequently but never updated. This is by far the simplest and best-performing cache strategy.
    • Read/write: Read/write caches may be appropriate if your data needs to be updated. They carry more overhead than read-only caches. In non-JTA environments, each transaction should be completed when Session.close() or Session.disconnect() is called.
    • Nonstrict read/write: This strategy does not guarantee that two transactions won't simultaneously modify the same data. Therefore, it may be most appropriate for data that is read often but only occasionally modified.
    • Transactional: This is a fully transactional cache that may be used only in a JTA environment.
     
  • . How do you configure 2nd level cach in hibernate?
  •  
    A. To activate second-level caching, you need to define the hibernate.cache.provider_class property in the hibernate.cfg.xml file as follows: <hibernate-configuration>
        <session-factory>
            <property  
    >
  • name="hibernate.cache.provider_class">org.hibernate.cache.EHCacheProvider</property>
        </session-factory>
    </hibernate-configuration>
    By default, the second-level cache is activated and uses the EHCache provider.
    To use the query cache you must first enable it by setting the property hibernate.cache.use_query_cache to true in hibernate.properties.
     
    Q. What is the difference between sorted and ordered collection in hibernate?

    A. A sorted collection is sorted in-memory using java comparator, while order collection is ordered at the database level using order by clause.
     
    Q. What are the types of inheritence models and describe how they work like vertical inheritence and horizontal?

    A. There are three types of inheritance mapping in hibernate :
     
    Example: Let us take the simple example of 3 java classes. Class Manager and Worker are inherited from Employee Abstract class.
    1. Table per concrete class with unions : In this case there will be 2 tables. Tables: Manager, Worker [all common attributes will be duplicated]
    2. Table per class hierarchy: Single Table can be mapped to a class hierarchy. There will be only one table in database called 'Employee' that will represent all the attributes required for all 3 classes. But it needs some discriminating column to differentiate between Manager and worker;
    3. Table per subclass: In this case there will be 3 tables represent Employee, Manager and Worker

STRUCTS INTERVIEW QUESTION AND ANSWERS



Q 1. What is MVC?
 
Model-View-Controller (MVC) is a design pattern put together to help control change. MVC decouples interface from business logic and data.
Model: The model contains the core of the application's functionality. The model enca psulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller.
View: The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur.
Controller: The controller reacts to the user input. It creates and sets the model. 

Q 2. What is a framework?
Framework is made up of the set of classes which allow us to use a library in a best possible way for a specific requirement.

3. What is Struts framework?

Struts framework is an open-source framework for developing the web applications in Java EE, based on MVC-2 architecture. It uses and extends the Java Servlet API. Struts is robust architecture and can be used for the development of application
of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java. Struts provides its own Controller component and integrates with other technologies to provide the Model and the View. For the Model, Struts can interact with standard data access technologies, like JDBC and EJB, as well as most any third-party packages, like Hibernate, iBATIS, or Object Relational Bridge. For the View, Struts works well with JavaServer Pages, including JSTL and JSF, as well as Velocity Templates, XSLT, and other presentation systems.

Q 4. What is Jakarta Struts Framework?
Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.
Q 5. What is ActionServlet?
The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the server
 goes through the controller. Controller is responsible for handling all the requests.

ABSTRACT CLASSES in Java

ABSTRACT CLASSES:

In JAVA we have two types of classes. They are concrete classes and abstract classes.
• A concrete class is one which contains fully defined methods. Defined methods are also
known as implemented or concrete methods. With respect to concrete class, we can create
an object of that class directly.

For example:
class C1
{
int a,b;
void f1 ()
{
…………;
…………;
}
void f2 ()
{
…………;
…………;
}
};

To call the above method:

C1 O1=new C1 ();
O1.f1 ();
O1.f2 ();

An abstract class is one which contains some defined methods and some undefined
methods. Undefined methods are also known as unimplemented or abstract methods.
Abstract method is one which does not contain any definition. To make the method as
abstract we have to use a keyword called abstract before the function declaration.

Syntax for ABSTRACT CLASS:

abstract return_type method_name (method parameters if any);

For example:

Abstract void sum ();
The abstract methods make us to understand what a method can do but it does not give
how the method can be implemented. Every abstract method belongs to a class under class is known
as abstract class, to make the class as abstract we use a keyword called abstract before the class
specification.

Syntax for ABSTRACT CLASS:

abstract class <clsname>
{
Abstract return_type method_name (method parameters if any);
};
For example:
abstract class Op
{
abstract void sum ();
};
With respect to abstract class we cannot create an object direct but we can create
indirectly. An object abstract class is equal to an object of that class which extends that abstract
class.

For example:

class CC extends AC
{
…………;
…………;
};
AC Ao=new AC (); //invalid
AC Ao=new CC ();
or
AC Ao;
Ao=new CC ();


Write a JAVA program for computing sum of two integers and floats using abstract classes?
Answer:
abstract class Op
{
abstract void sum ();
};
class isum extends Op
{
void sum ()
{
int a,b,c;
a=10;
b=20;
c=a+b;
System.out.println ("INT VALUE = "+c);
}
};
class fsum extends Op
{
void sum ()
{
float f1,f2,f3;
f1=10.26f;
f2=20.32f;
f3=f1+f2;
System.out.println ("FLOAT VALUE = "+f3);
}
};
class AbDemo
{
public static void main (String k [])
{
// Op o1=new Op (); invalid
Op o2;
o2=new isum ();
o2.sum ();
o2=new fsum ();
o2.sum ();
}
};

Abstract classes should not be final, since, they are always reusable. Abstract classes are
basically used to implement polymorphism; we use the concept of dynamic binding. Hence,
abstract classes, polymorphism and dynamic binding will improve the performance of JAVA J2EE
applications by reducing amount of memory space.

Whenever we inherit ‘n’ number of class, if the derived class defines all ‘n’ concrete class. If the derived class methods then the derived classwe use a keyword called abstract An abstract base class is one
An abstract derived class is one inherited from abstract base class

Implement the above diagram by using abstract class’s polymorphism and dynamic binding.


Answer:
abstract class C1
{
abstract void f1 ();
abstract void f2 ();
};
abstract class C2 extends C1
{
void f1 ()
{
System.out.println
}
};
class C3 extends C2
{
void f1 ()
{
super.f1 ();
System.out.println ("f1
}
void f2 ()

abstract methods from abstract base class number of abstract methods then the is not defining at least one abstract method out of ‘n’ abstract is known as abstract derived class and to make that class abstract
abstract.which contains physical representation of abstract methodswhich contains logical declaration of abstract methods which areclass.

An object of either concrete base class or abstract base class contains the details about
those methods which are available in that class only but this object (concrete base class or abstract
base class) does not contains details of those methods which are specially defined in derived
class’s.

‘Super’ keyword using in java

 Super keyword

Super keyword is used for differentiating the base class features with derived class features.
Super keyword is placing an important role in three places. They are at variable level, at method
level and at constructor level.
• Super at variable level
Whenever we inherit the base class members into derived class, there is a possibility that
base class members are similar to derived class members.
In order to distinguish the base class members with derived class members in the derived
class, the base class members will be preceded by a keyword super.
Syntax for super at VARIABLE LEVEL:
super. base class member name

For example:

class Bc
{
int a;
};
class Dc extends Bc
{
int a;
void set (int x, int y)
{
super.a=x;
a=y; //by default 'a' is preceded with 'this.' since 'this.' represents current class
}
void sum ()
{
System.out.println ("SUM = "+(super.a+a));
}
};
class InDemo1
{
public static void main (String k [])
{
int n1=Integer.parseInt (k[0]);
int n2=Integer.parseInt (k[1]);
Dc do1=new Dc ();
do1.set (n1, n2);
do1.sum ();
}
};

• Super at method level

Whenever we inherit the base class methods into the derived class, there is a possibility that
base class methods are similar to derived methods.
To differentiate the base class methods with derived class methods in the derived class, the
base class methods must be preceded by a keyword super.
Syntax for super at method level: super. base class method name

For example:

class Bc
{
void display ()
{
System.out.println ("BASE CLASS - DISPLAY...");
}
};
class Dc extends Bc
{
void display ()
{
super.display (); //refers to base class display method
System.out.println ("DERIVED CLASS");
}
};
class InDemo2
{
public static void main (String k [])
{
Dc do1=new Dc ();
do1.display ();
}
};

RELATIONSHIPS ,Inheritance in Java


 TYPES of RELATIONSHIPS in java

Based on reusing the data members from one class to another class in JAVA we have three
types of relationships. They are is-a relationship, has-a relationship and uses-a relationship.

• Is-a relationship is one in which data members of one class is obtained into another class
through the concept of inheritance.
• Has-a relationship is one in which an object of one class is created as a data member in
another class.
• Uses-a relationship is one in which a method of one class is using an object of another class.
Inheritance is the technique which allows us to inherit the data members and methods from
base class to derived class.
• Base class is one which always gives its features to derived classes.
• Derived class is one which always takes features from base class.
A Derived class is one which contains some of features of its own plus some of the data
members from base class.

Syntax for INHERITING the features from base class to derived class:

class <clsname-2> extends <clsname-1>
{
Variable declaration;
Method definition;
};

Here, clsname-1 and clsname-2 represents derived class and base class respectively.
Extends is a keyword which is used for inheriting the data members and methods from base class to
the derived class and it also improves functionality of derived class.

NOTE:

• Final classes cannot be inherited.
• If the base class contains private data members then that type of data members will not be
inherited into derived class.
Whenever we develop any inheritance application, it is always recommended to create an object
of bottom most derived class. Since, bottom most derived class contains all the features from its
super classes.
• One class can extend only one class at a time. Since, JAVA does not support multiple
inheritance.
Whenever we inherit the base class members into derived class, when we creates an object of
derived class, JVM always creates the memory space for base class members first and later memory
space will be created for derived class members.

For example:

class c1;
{
int a;
void f1()
{
…………;
}
};
class c2 extends c1
{
int b;
void f2()
{
…………;
}
};
NOTE:
• Whatever the data members are coming from base class to the derived class, the base class
members are logically declared in derived class, the base class methods are logically defined
in derived class.
• Private data members and private methods of the base class will not be inherited at all.

Write a JAVA program computes sum of two numbers using inheritance?
Answer:
class Bc
{
int a;
};
class Dc extends Bc
{
int b;
void set (int x, int y)
{
a=x;
b=y;
}
void sum ()
{
System.out.println ("SUM = "+(a+b));
}
};
class InDemo
{
public static void main (String k [])
{
int n1=Integer.parseInt (k [0]);
int n2=Integer.parseInt (k [1]);
Dc do1=new Dc ();
do1.set (n1, n2);
do1.sum ();
}
};
For every class in JAVA we have a super class called object class. The purpose of object class
is that it provides garbage collector for collecting unreferenced memory locations from the derived
classes.

Friday, June 12, 2015

this () key word

this () key word: 

this () is used for calling current class default constructor from current class parameterized
constructors.
this (…): this (…) is used for calling current class parameterized constructor from other category
constructors of the same class.

Rule for ‘this’:
Whenever we use either this () or this (…) in the current class constructors, that statements
must be used as first statement only.
The order of the output containing this () or this (...) will be in the reverse order of the input
which we gave as inputs.
For more clarity refer the above program.

For example we need output as follows:

I AM FROM DEFAULT CONSTRUCTOR… ---1
VALUE OF a = 1
VALUE OF b = 2
I AM FROM SINGLE PARAMETERIZED CONSTRUCTOR… ---2
VALUE OF a = 100
VALUE OF b = 200
I AM FROM DOUBLE PARAMETERIZED CONSTRUCTOR… ---3
VALUE OF a = 10
VALUE OF b = 10

We must write in the following order as input:

Test (10); ---3
Test (100, 200); ---2
Test (); ---1

NOTE:

Whenever we refer the data members which are similar to formal parameters, the JVM
gives first preference to formal parameters whereas whenever we write a keyword this before the
variable name of a class then the JVM refers to data members of the class.
this methods are used for calling current class constructors.
NOTE:
• If any method called by an object then that object is known as source object.
• If we pass an object as a parameter to the method then that object is known as target
object

For example:

SOURCE OBJECT. METHOD NAME (TARGET OBJECT);
t1. display (t2); // written in main

In the definition of display method t1 data members are referred by this. Data member names
(this. a & this. b) whereas t2 object data members are referred by formal object name. Data member
names (T. a & T. b).
void display (Test T) //T is formal object member
{
System.out.println (“VALUE OF a BELONGS TO DATA MEMBER =”+this.a);
System.out.println (“VALUE OF b BELONGS TO DATA MEMBER =”+this.a);
System.out.println (“VALUE OF a BELONGS TO FORMAL OBJECT MEMBER =”+T.a);
System.out.println (“VALUE OF b BELONGS TO FORMAL OBJECT MEMBER =”+T.a);
}

Write a JAVA program which computes sum of two objects by accepting the data from command
prompt?


Answer:

class Test
{
int a,b;
Test ()
{
a=b=0;
}
Test (int a, int b)
{
this.a=a;
this.b=b;
}
Test sum (Test T)
{
Test T11=new Test ();
T11.a=this.a+T.a;
T11.b=this.b+T.b;
return (T11);
}
void display ()
{
System.out.println ("VALUE OF a = "+a);
System.out.println ("VALUE OF b = "+b);
}
};
class SumDemo1
{
public static void main (String k[])
{
int n1=Integer.parseInt (k[0]);
int n2=Integer.parseInt (k[1]);
int n3=Integer.parseInt (k[2]);
int n4=Integer.parseInt (k[3]);
Test t1=new Test (n1,n2);
Test t2=new Test (n3,n4);
Test t3=new Test ();
// t3=t1+t2; invalid statement
t3=t1.sum (t2);
System.out.println ("t1 VALUES ARE AS FOLLOWS...");
t1.display ();
System.out.println ("t2 VALUES ARE AS FOLLOWS...");
t2.display ();
System.out.println ("t3 VALUES ARE AS FOLLOWS...");
t3.display ();
}
};

CONSTRUCTORS in java

CONSTRUCTORS in java

A constructor is a special member method which will be called by the JVM implicitly
(automatically) for placing user/programmer defined values instead of placing default values.
Constructors are meant for initializing the object.
ADVANTAGES of constructors:
1. A constructor eliminates placing the default values.
2. A constructor eliminates calling the normal method implicitly.
RULES/PROPERTIES/CHARACTERISTICS of a constructor:
1. Constructor name must be similar to name of the class.
2. Constructor should not return any value even void also (if we write the return type for the
constructor then that constructor will be treated as ordinary method).
3. Constructors should not be static since constructors will be called each and every time
whenever an object is creating.
4. Constructor should not be private provided an object of one class is created in another class
(constructor can be private provided an object of one class created in the same class).
5. Constructors will not be inherited at all.
6. Constructors are called automatically whenever an object is creating.

Based on creating objects in JAVA we have two types of constructors. They are
default/parameter less/no argument constructor and parameterized constructor.
• A default constructor is one which will not take any parameters.
Syntax:
class <clsname>
{
clsname () //default constructor
{
Block of statements;
………………………………;
………………………………;
}
………………………;
………………………;
};

For example:
class Test
{
int a, b;
Test ()
{
System.out.println ("I AM FROM DEFAULT CONSTRUCTOR...");
a=10;
b=20;
System.out.println ("VALUE OF a = "+a);
System.out.println ("VALUE OF b = "+b);
}
};
class TestDemo
{
public static void main (String [] args)
{
Test t1=new Test ();
}
};

Note:
Whenever we create an object only with default constructor, defining the default
constructor is optional. If we are not defining default constructor of a class, then JVM will call
automatically system defined default constructor (SDDC). If we define, JVM will call
user/programmer defined default constructor (UDDC).

• A parameterized constructor is one which takes some parameters.
Syntax:
class <clsname>
{
…………………………;
…………………………;
<clsname> (list of parameters) //parameterized constructor
{
Block of statements (s);
}
…………………………;
…………………………;
}
For example:
class Test
{
int a, b;
Test (int n1, int n2)
{
System.out.println ("I AM FROM PARAMETER CONSTRUCTOR...");
a=n1;
b=n2;
System.out.println ("VALUE OF a = "+a);
System.out.println ("VALUE OF b = "+b);
}
};
class TestDemo1
{
public static void main (String k [])
{
Test t1=new Test (10, 20);
}
};

RULE-2:
Whenever we create an object using parameterized constructor, it is mandatory for the
JAVA programmer to define parameterized constructor otherwise we will get compile time error.
• Overloaded constructor is one in which constructor name is similar but its signature is
different. Signature represents number of parameters, type of parameters and order of
parameters. Here, at least one thing must be differentiated.
For example:
Test t1=new Test (10, 20);
Test t2=new Test (10, 20, 30);
Test t3=new Test (10.5, 20.5);
Test t4=new Test (10, 20.5);
Test t5=new Test (10.5, 20);
RULE-3:
Whenever we define/create the objects with respect to both parameterized constructor and
default constructor, it is mandatory for the JAVA programmer to define both the constructors.
NOTE:
When we define a class, that class can contain two categories of constructors they are single
default constructor and ‘n’ number of parameterized constructors (overloaded constructors).

Write a JAVA program which illustrates the concept of default constructor, parameterized
constructor and overloaded constructor?


Answer:

class Test
{
int a, b;
Test ()
{
System.out.println ("I AM FROM DEFAULT CONSTRUCTOR...");
a=1;
b=2;
System.out.println ("VALUE OF a ="+a);
System.out.println ("VALUE OF b ="+b);
}
Test (int x, int y)
{
System.out.println ("I AM FROM DOUBLE PARAMETERIZED CONSTRUCTOR...");
a=x;
b=y;
System.out.println ("VALUE OF a ="+a);
System.out.println ("VALUE OF b ="+b);
}
Test (int x)
{
System.out.println ("I AM FROM SINGLE PARAMETERIZED CONSTRUCTOR...");
a=x;
b=x;
System.out.println ("VALUE OF a ="+a);
System.out.println ("VALUE OF b ="+b);
}
Test (Test T)
{
System.out.println ("I AM FROM OBJECT PARAMETERIZED CONSTRUCTOR...");
a=T.a;
b=T.b;
System.out.println ("VALUE OF a ="+a);
System.out.println ("VALUE OF b ="+b);
}
};
class TestDemo2
{
public static void main (String k [])
{
Test t1=new Test ();
Test t2=new Test (10, 20);
Test t3=new Test (1000);
Test t4=new Test (t1);
}
};

Prime Number Program

Write a JAVA program to check weather the given number is prime or not?

Answer:

class Prime
{
int n;
void set (int x)
{
n=x;
}
String decide ()
{
int i;
for (i=2; i<n; i++)
{
if (n%i==0)
{
break;
}
}
if (i==n)
{
return "PRIME";
}
else
{
return "NOT"+"PRIME";
}
}
};
class PrimeDemo
{
public static void main (String k [])
{
int n=Integer.parseInt (k [0]);
Prime po=new Prime ();
po.set (n);
String so=po.decide ();
System.out.println (so);
}
};

HUNGARIAN NOTATION:

HUNGARIAN NOTATION:

Hungarian Notation is the naming convention followed by SUN (Stanford University
Network) micro system to develop their predefined classes, interfaces, methods and data
members.

Hungarian rule for CLASS or INTERFACE:

If a class object interface contains more than one word then we must write all the first
letters must be capital.

For example:

System, NumberFormatException, ArrayIndexOutOfBoundException
Hungarian rule for METHOD:
If a method name contains more than one word then first word letter is small and rest of
the words first letters must be capital.

For example:

println (), actionPerformed (), adjustmentValueChanged ()
Hungarian rule for DATA MEMBERS:
All the data members are the predefined classes and interfaces must be represented used as
capital letters.

For example:

PI, MAX_VALUE, and MIN_VALUE
All the data members in the predefined classes and interfaces are belongs to public static
final XXX data members. XXX represents data type, variable name and variable value. Every final
data member must belong to static data member but reverse may or may not be applicable.

PRINT STATEMENTS in java

System.out.println (“”);

• This statement is used for displaying the data or messages on to the consol (monitor).
• Here, println is the predefined instance method of print stream class.
• To call this method we require an object called print stream class.
• The object of print stream class is called out is created as a static data member in system
class (system is a predefined class).
• Hence to call the println method we must use the following statement:
System.out.println (“WELCOME TO JAVA”);
• Print stream class is a predefined class which contains nine overloaded instance println

methods and nine overloaded instance print methods and whose prototypes are as follows:

Public void println (byte);
Public void println (short);
Public void println (int);
Public void println (long);
Public void println (float);
Public void println (double);
Public void println (char);
Public void println (Boolean);
Public void println (string);
Public void print (byte);
Public void print (short);
Public void print (int);
Public void print (long);
Public void print (float);
Public void print (double);
Public void print (char);
Public void print (Boolean);
Public void print (string);

For example 1:

Int a=40000;
System.out.println (a); //40000
System.out.println (“value of a=” + a); //value of a=40000
System.out.println (a + “is the value of a”); //40000 is the value of a

For example 2:

Int a=10, b=20, c;
C = a + b;
System.out.println (c); //30
System.out.println (“sum=” + c); //sum=30
System.out.println (c + “is the sum”); // 30 is the sum
System.out.println (“sum of” + a + “and” + b + “=” + c); //sum of 10 and 20 is 30

For example 3:

System.out.println (“WELCOME TO JAVA”);

CONSTANTS IN JAVA

CONSTANTS in java

“Constant is an identifier whose value cannot be changed during execution of the program”.

• In JAVA to make the identifiers are as constants, we use a keyword called final.
• Final is a keyword which is playing an important role in three levels. They are at variable
level, at method level and at class level.

i. When we don’t want to change the value of the variable, then that variable must be
declared as final.

Syntax for FINAL VARIABLE INITIALIZATION:

Final data type v1=val1, v2=val2 … vn=valn;

For example:
Final int a=10;
a=a+20; //invalid
a=30; //invalid

ii. When the final variable is initialized, no more modifications or assignments are possible.

Syntax for FINAL VARIABLE DECLARATION:

Final data type v1, v2………vn;

For example:

Final int a;
a=a+1; //invalid
a=30+2; //invalid
a=400; //valid for 1st time
a=500; //invalid
Whenever a final variable is declared first time assignment is possible and no more
modification and further assignments are not possible. Hence, final variables cannot be modified.

Variables in java

VARIABLES in java

“A variable is an identifier whose value will be changed during execution of the program”.
Rules for writing variables:
i. First letter must be an alphabet.
ii. The length of the variable should not exceed more than 32 characters.
iii. No special symbols are allowed except underscore.
iv. No keywords should use as variable names.
Types of variables in JAVA:
• Whenever we develop any JAVA program that will be developed with respect to class only.
• In a class we can use ‘n’ number of data members and ‘n’ number of methods.
• Generally in JAVA, we can use two types of data members or variables. They are
instance/non-static variables and static variables.



INSTANCE/NON-STATIC VARIABLES

1) An instance variable is one whose
memory space is creating each and
every time whenever an object is
created.
2) Programmatically instance variable
declaration should not be preceded
by keyword static.
3) Data type v1, v2…vn;
4) Instance variable must be accessed
with respect to object name i.e.,
objname.varname;
5) Value of instance variable is not
sharable.
6) Instance variable are also known as
object level data members since they
are dependent on objects.

STATIC VARIABLES

1) Static variables are whose memory
space is creating only once when the
class is loaded by class loader
subsystem (a part of JVM) in the main
memory irrespective of number of
objects.
2) Programmatically static variable
declaration must be preceded by
keyword static.
3) Static data type v1, v2…vn;
4) Static variables must be accessed
with respect to class name i.e.,
classname.varname;
5) Value of static variable is always
recommended for sharable.
6) Static variable are also known as class
level data members since they are
dependent on classes.

Inner Classes

Inner Classes:A class within another class is called inner class

code without inner classes is more maintainable and readable.when you access private data members of the outer class,the JDK comploier creates package-access member functions in the outer class for the inner class to access the private members.This Leaves a a security hole.IN general we should avoid using inner classes.Use inner class only when an inner class is only relevant in the context of the outer class and/or inner class can be amde privatge so that only outer class can acess it. Inner classes are used primarly to implement helper classes like iterators,comparators etc. when are used in the context of an outer class.

     You can use public access specifier befor a class

  • you can use public access specifier before a class
  • you cannot use private access specifier before a class
  • only inner classes can be declare a the private 
  • Directly you cannot create objects to the inner class
  • we can create objects to the outer classes
  • inner classes objects can be created only its outer class.
  • outer class is acting as a firewall.
Types of Inner Classes:

  1. Annonymous Classes
  2. Static Inner Classes
  3. Non-Static Inner Classes
  4. Method-local Inner Classes


Conditions,loops,switch statements with Examples

Control Flow Statements

The control flow statements are used to control the flow of execution of the program. In java programming language there are three types of control flow statement available.
  • Decision making or selection statement (if, if-else, switch)
  • Looping or Iteration statement (while, for, do-while)
  • Breaking or Jumping statement (break, continue)

Decision Making Statements

Decision making statement statements is also called selection statement. That is depending on the condition block need to be executed or not while is decided by condition. If the condition is "true" statement block will be executed, if condition is "false" then statement block will not be executed.
In this section we are discuss about if-then, if-then-else, and switch statement. In java there are three types of decision making statement.
  • if
  • if-else
  • switch
if condition :


if  is most basic statement of Decision making statement. It tells to program to execute a certain part of code only if particular condition or test is true.

 syntax:

if(condition)
 {
   Statement(s)
 }

  • Constructing the body if always optional, that is recommended to create the body when we are having multiple statements.
  • For a single statement, it is not required to specify the body.
  • If the body is not specified, then automatically condition part will be terminated with next semicolon ( ; ).

Else

  • It is a keyword, by using this keyword we can create a alternative block for "if" part.
  • Using else is always optional i.e, it is recommended to use when we are having alternate block of condition.
  • When we are working with if else among those two block at given any point of time only one block will be executed.
  • When if condition is false then else part will be executed, if part is executed then automatically else part will be ignored.


if-else statement

In general it can be used to execute one block of statement among two blocks, in java language if and else are the keyword in java.

Syntax:

if(condition)
 {
  Statement(s)
 }
 else
 {
  Statement(s)
 }
Statement(s)

In the above syntax whenever condition is true all the if block statement are executed remaining statement of the program by neglecting else block statement If the condition is false else block statement remaining statement of the program are executed by neglecting if block statements.

 Example:

import java.util.*;
class num
{
 public static void main(String args[])
 {
  int  c;
  System.out.println("Enter any two num");
  Scanner scanner=new Scanner(System.in);
  int a=scanner.next();
  int b=scanner.next();
  if(a>b)
  {
   c=a+b;
  }
  else
  {
   c=a-b;
  }
  System.out.println("Result="+c);
 }
}

Switch Statement

A switch statement work with byte, short, char and int primitive data type, it also works with enumerated types and string.

Syntax:

switch(expression/variable)
{
 case  value:
 //statements
 // any number of case statements
 break;  //optional
 default: //optional
 //statements
}

Rules for apply switch statement

With switch statement use only byte, short, int, char data type. You can use any number of case statements within a switch. Value for a case must be same as the variable in switch .

Limitations of switch statement

Logical operators cannot be used with switch statement. For instance

case k>=30

is not allowed
Switch case variables can have only int and char data type. So float data type is not allowed. For instance in the switch syntax given below:

switch(ch)
 {
  case 1:  
  statement-1;
  break;
  case 2:
  statement-2;
  break;
 } 

In this ch can be integer or char and cannot be float or any other data type.

Looping statement

These are the statements execute one or more statement repeatedly several number of times. In java programming language there are three types of loops are available, that is, while, for and do-while.
Advantage with looping statement
  • Length on the developer is reducing.
  • Burden on the developer is reducing.
  • Burden of memory space is reduced time consuming process to execute the program is reduced.

Difference between conditional and looping statement

Conditional statement executes only once in the program where as looping statements executes repeatedly several number of time.

While loop

  • When we are working with while loop always pre-checking process will be occurred.
  • Pre-checking process means before evolution of statement block condition part will be executed.
  • While loop will be repeats in clock wise direction.
:   while(condition)
      {
                       Statement(s)
                       Increment / decrements (++ or --);
       }

Example:

class  whileDemo
{
 public static void main(String args[])
 {
 int i=0;
 while(i<10)
 {
  System.out.println(+i);
  i++;
 }

for loop

for loop is a statement which allows code to be repeatedly executed. For loop contains 3 parts.
  • Initialization
  • Condition
  • Increment or Decrements
 Syntax:

                         for ( initialization; condition; increment )
                           {
                                                 statement(s);
                           }


                                      for(  a=2;     a<=10;    a++)

  • Initialization: step is execute first and this is execute only once when we are entering into the loop first time. This step is allow to declare and initialize any loop control variables.
          Initialization    Example  above syntax        a=2
  • Condition: is next step after initialization step, if it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control goes outside the for loop.
             Condition Example  above syntax        a<=10
  • Increment or Decrements: After completion of Initialization and Condition steps loop body code is executed and then Increment or Decrements steps is execute. This statement allows to update any loop control variables.
           Increment or Decrements  Example  above syntax        a++.a--

Control flow of for loop


  • First initialize the variable
  • In second step check condition
  • In third step control goes inside loop body and execute.
  • At last increase the value of variable
  • Same process is repeat until condition not false.

do-while

  • when we need to repeat the statement block at least 1 then go for do-while.
  • In do-while loop post-checking process will be occur, that is after execution of the statement block condition part will be executed.

 

syntax:

 do
{
Statement(s)

increment/decrement (++ or --)
}while();

 Example:

 


                  class  dowhileDemo
                       {
                                         public static void main(String args[])
                                           {
                                                                 int i=0;
                                                                do
                                                                             {
                                                                                   System.out.println(+i);
                                                                                     i++;

                                                                             } While(i<10);
                                                          
                                              }
                               }















Command line arguments

 Command line arguments

If any input value is passed through command prompt at the time of running of program is known as command line argument by default every command line argument will be treated as string value and those are stored in string array of main() method.

Example of Command Line Argumets:

class CommandLineExample
{
public static void main(String args[])

System.out.println("Argument is: "+args[0]);

}  

compile:

Compile By > Javac  CommandLineExample.java
Run By > Java  CommandLineExample learner

output

Argument is:learner


Example:

class SumDemo
{
public static void main(String args[])

System.out.println("Sum: "+args[0]);

}

Compile By > Javac  SumDemo.java
Run By > Java  SumDemo 20 30

Output:

Sum: 50

When the above statement is executing the following sequence of steps will take place.
  • Class loader sub-system loads SumDemo along with Command line argument(10, 20) and in main memory.
  • JVM take the loaded class SumDemo along with Command line arguments (10, 20) and place the number of values in the length variable that is 2.
  • JVM looks for main() that is JVM will place the Command in the main() in the form of string class that is.

  • Hence all the CMD line arguments of java are sending to main() method available in the form of array of object of String class (every CMD are available or stored in main method in the form of array of object of String class).
  • JVM calls the main() method with respect to loaded class SumDemo that is SumDemo.main().

SOP Statements

In java language print() and println() are the predefined non-static method of printStream class used to display value or message either in the same line or line by line respectively. PrintStream class is having fixed object reference in the System class (existing as a static properties) so that either print() or println() method can be called with following syntax..

Syntax:

    System.out.print("--------------");
    System.out.println("------------");

Note:  "out" is Object reference of printStream class existing in system class as a static property.

Example:

class Hello
{
public static void main(String arg[])
{
System.out.println("Hello Learners");
}
}

output:

Hello Learners






Wednesday, June 10, 2015

Structure of Java Program




Structure of Java Program



Sun Micro System has prescribed the following structure for the java programmers for developing java application.


Syntax:

 package details

class classname
{
                      datamembers;
                     
   
                     public static void main(String [] args)

                         {
                                      block of statements;
                          }


 }

Example program:

class student
{
    public static void main(String[] args)
    {
        System.out.println("Hello World!");
    }
}



  • A package is a collection of classes, interfaces and sub-packages. A sub package contains collection of classes, interfaces and sub-sub packages etc. java.lang.*; package is imported by default and this package is known as default package.
  • Class is keyword used for developing user defined data type and every java program must start with a concept of class.
  • "Classname" represent a java valid variable name treated as a name of the class each and every class name in java is treated as user-defined data type.
  • Data member represents either instance or static they will be selected based on the name of the class.
  • User-defined methods represents either instance or static they are meant for performing the operations either once or each and every time.
  • Each and every java program starts execution from the main() method. And hence main() method is known as program driver.
  • Since main() method of java is not returning any value and hence its return type must be void.
  • Since main() method of java executes only once throughout the java program execution and hence its nature must be static.
  • Since main() method must be accessed by every java programmer and hence whose access specifier must be public.
  • Each and every main() method of java must take array of objects of String.
  • Block of statements represents set of executable statements which are in term calling user-defined methods are containing business-logic.
  • The file naming conversion in the java programming is that which-ever class is containing main() method, that class name must be given as a file name with an extension .java.

Operators

Operators

Operator is a special symbol that tells the compiler to perform specific mathematical or logical Operation. Java supports following lists of operators.
  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Ternary or Conditional Operators


Arithmetic Operators

Given table shows all the Arithmetic operator supported by Java Language. Lets suppose variable A hold 8 and B hold 3.


Operator                                  Example (int A=6, B=4)                                    Result
    +                                           A+B                                        10
    -                                           A-B                                         2
    *                                           A*B                                        24
    /                                           A/B                                         3
   %                                          A%4                                         0.24


Relational Operators

Which can be used to check the Condition, it always return true or false. Lets suppose variable A hold 8 and B hold 3.


Operators                    Example (int A=7, B=3)                                         Result
<                            A<BFalse
<=                           A<=10True
>                           A>BTrue
>=                          A<=BFalse
==                         A== BFalse
!=                               A!=(-4)True

Logical Operator

Which can be used to combine more than one Condition?. Suppose you want to combined two conditions A<B and B>C, then you need to use Logical Operator like (A<B) && (B>C). Here && is Logical Operator.
Operator              Example (int A=7, B=3, C=-11)                              Result
&&                (A<B) && (B>C)                               False
||               (B!=-C) || (A==B)                               True
!                    !(B<=-A)                                True

Truth table of Logical Operator

C1              C2                   C1 && C2         C1 || C2                  !C1                       !C2
TT      T              T                     F                         F
TF      F              T                     F                         T
FT      F              T                     T                           F
FF                             F              F                     T                          T

Assignment operators

Which can be used to assign a value to a variable. Lets suppose variable A hold 8 and B hold 3.
Operator                        Example (int A=9, B=4)                                    Result
+=                          A+=B or A=A+B                                        13
-=                           A-=3 or A=A-3                                        6
*=                        A*=7 or A=A*7                                        63
/=                         A/=B or A=A/B                                        2.25
%=                         A%=5 or A=A%5                                        0.45


Ternary operator

If any operator is used on three operands or variable is known as ternary operator. It can be represented with " ?: "

My Blog List

Powered by Blogger.

 

© 2013 Java Tutorials. All rights resevered. Designed by Templateism

Back To Top