JSP Implicit Objects

  • Implicit objects in jsp are the objects that are created by the container automatically and the container makes all these 9 implicit objects to the developer.
  • We do not need to create them explicitly, since these objects are created and automatically by container and are accessed using standard variables(objects) are called implicit objects.
  • The following are of implicit variables available in the JSP.  

9 Jsp implicit Objects

1.out
2.request
3.response
4.config
5.application
6.session
7.pagecontext
8.page
9.exception



1.out:

  •  out is one the implicit object to write the data to the buffer and send output to the client in response.
  • out object allows us to access the servlets output stream and has a pagescope.
  • out.print("");
  • out is the object of javax.servlet.jsp.JspWriter class.
  • While working with servlet we need printWriter object
  • PrintWriter out=response.getWriter();   
  • In servlet we are used PrintWriter to send the output to the client. In JSP we use JSPWriter. 

Difference between JspWriter and PrintWriter:

  • Every JSPWriter is associated with 8KB of internal Buffer. Where as PrintWriter doesn’t associated with any Buffer.
  • The methods of the JspWriter class are designed to throw java.io.IOException where as the methods of PrintWriter class are not throw Exception.
  • JspWriter is an abstract class present in javax.servlet package.
  • PrintWriter is a class defined in java.io package.
  1. public class PrintWriter extends Writer { 
  2. // .....
  3. }
  4.  
  5. public abstract class JspWriter extends Writer {
  6. //....
  7. }

JspWriter out object in jsp:

  1. <html> 
  2. <body> 
  3. <%
  4.     int a = 10;
  5.     int b = 20;
  6.     out.print(“A value is:”+a);
  7.     out.write(“B value is:”+b);
  8. %>
  9. </body> 
  10. </html> 



Printwriter object in servlet:

  1. PrintWriter out=response.getWriter();  

2.request:

  • request implicit object is the object of  type  HttpServletRequest.
  • request object will be created by the container for every request.
  • It will be used to get request information like parameter , header information ,server name server port etc.
  • By using request object we can able to set ,get and remove attributes from request scope.
  • It uses the getPareameter() method to access request parameter.
  • The container passes this object to the _jspService() method.


  1. <form action="welcome.jsp">  
  2. <input type="text" name="username">  
  3. <input type="submit" value="submit"><br/>  
  4. </form> 

  1. <%   
  2. String name=request.getParameter("userid");  
  3. out.print("welcome "+name);  
  4. %> 

  1. out.println(request.getMethod()+”<br>”);
  2. out.println(request.getRequestURI()+”<br>”);
  3. out.println(request.getProtocol()+”<br>”);
  4. out.println(request.getHeader(“User Agent”)+”<br>”);
  5. out.println(request.getHeader(“Accept-language”)+”<br>”);

3.response:

  • response is an instance of class which implements the HttpServletResponse interface.
  • Container generates this object and passes to the _jspService() method as parameter.
  • response object will be created by the container for each request.
  • It represents the response that to be given to the client. 
  • The response implicit object is  used to content type, add cookie and redirect the response to another resource.

1.set content type.

  1. response.setContextType(“text/xml”);
  2. out.println(“<employee>”);
  3. out.println(“<eno>|</eno>”);
  4. out.println(“</employee>”);

2.Redirect response:

  1. <%  
  2.     response.sendRedirect("http://www.instanceofjava.com"); 
  3. %>

3. To send the error message directly to the client:

  1. <%  response.sendError(537,”xyz”); %>

4.config

  • config is one of the implicit object of type javax.servlet.ServletConfig.
  • config object is created by the web container for each jsp page.
  • config object used to get initialization parameters from web.xml file.


  1. <web-app>
  2.  
  3. <servlet>  
  4. <servlet-name>instanceofjava</servlet-name>  
  5. <jsp-file>/welcome.jsp</jsp-file>  
  6. <init-param>  
  7. <param-name>dname</param-name>  
  8. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>  
  9. </init-param>  
  10. </servlet>  
  11.  
  12. <servlet-mapping>  
  13. <servlet-name>instanceofjava</servlet-name>  
  14. <url-pattern>/welcome</url-pattern>  
  15. </servlet-mapping>  
  16.  
  17. </web-app> 

  1. <%   
  2. String driver=config.getInitParameter("dname");  
  3. out.print("driver name="+driver);  
  4. %> 

  • servletConfig is an object used by servlet container to pass the information during initialization.
  • Once if we get the ServletConfig object, we can find the name of the servlet which is configured in web.xml file by using a method getServletName() method.

  1. <%
  2. String name = config.getServletName();
  3. oput.println(name);
  4. %>


5.application:

  • application is one of the implicit object of type javax.servlet.ServletContext.
  • application object is created by the web container one per application when the application gets deployed.
  • application object used to get context parameters from web.xml file.
  • ServletContext object contains set of methods which are used to interact with ServletContainer. By using these methods we can find the information about ServletContainer.
  • When ever sun micro system releases a new version of API. It is the responsibility of server vender to provide the implementation to the latest API. 
  • For example when servlet 2.5 is released Tomcat guys has provided the implementation and integrated it in Tomcat 6.0 the latest version of servlet API is 3.0 this version is integrated in Tomcat 7.0.
     

  1. <web-app>
  2.  
  3. <servlet>  
  4. <servlet-name>instanceofjava</servlet-name>  
  5. <jsp-file>/index.jsp</servlet-class>  
  6. </servlet>  
  7.  
  8. <servlet-mapping>  
  9. <servlet-name>instanceofjava</servlet-name>  
  10. <url-pattern>/index</url-pattern>  
  11. </servlet-mapping> 
  12.  
  13. <context-param>  
  14. <param-name>dname</param-name>  
  15. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>  
  16. </context-param>  
  17.  
  18. </web-app>

  1. <%   
  2. String driver=application.getInitParameter("dname");  
  3. out.print("driver name="+driver);  
  4. %> 

6.session

  • session implicit object is holding HttpSession object.
  • session object used to set, get, and remove attributes to the session scope and also used to get session information.

index.html

  1. <html>  
  2. <body>  
  3. <form action="/welcome">  
  4. <input type="text" name="uname">  
  5. <input type="submit" value="submit"><br/>  
  6. </form>  
  7. </body>  
  8. </html>   

welcome.jsp

  1. <html>  
  2. <body>  
  3. <%   
  4. String name=request.getParameter("uname");  
  5. out.print("Welcome "+name);  
  6. session.setAttribute("user",name);  
  7. <a href="showuserinfo.jsp">showuser details</a>  
  8. %>  
  9. </body>  
  10. </html>   

showuserinfo.jsp

  1. <html>  
  2. <body>  
  3.  
  4. <%   
  5. String name=(String)session.getAttribute("user");  
  6. out.print("Hello "+name);  
  7. %>  
  8.  
  9. </body>  
  10. </html> 
  11. %> 

7.pagecontext:

  • pagecontext implicit object is type of  PageContext.
  • pagecontext object used to set , get and remove attributes in particular scope
  1. page scope
  2. request scope
  3. session scope
  4. application scope

  1. pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);
  2.  String name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE); 

8.page

  • Page implicit variable hold the currently executes Servlet object for the corresponding JSP.
  • Acts as this object for current jsp page
  1.  <%=page.getClass().getName() %>
  2.   <%=page.getServlestInfo()%> 

9.exception

  • The implicit variable can be used only in Error pages. When we try to use this variable in a JSP which is not an Error page we get an Error message.

  1.  <%@ page isErrorPage="true" %>  
  2. <html>  
  3. <body>   
  4.  
  5. <%= exception %>  
  6.  
  7. </body>  
  8. </html> 


Java 8 Interface Static and Default Methods


Java 8 interface static and default methods

  • Java 8 introduced two new methods in interface they are
    1.default methods
    2.static methods
  • By this interfaces and abstract class are same but still having lot differences like abstract class can have a constructor etc will discuss more before that we need to know about these Java 8 features of interfaces.
  • Defaults methods are also called as defender methods can be implemented inside the interface
  • Like normal class now with java 8 we can declare static methods in side a interface.
  • Lets jump deep into Java 8 default and static methods 

  

1.Interface Default Methods in Java 8


  • Before Java 8 in interfaces we can and able to declare only abstract methods only.
  • If we declare a method without abstract that will be treated as abstract by default.
  • As we know all methods in interfaces are by default abstract methods.
  • These methods wont have body means implementations
  • The class which is implementing this interface need to provide body / implementation for this abstract methods.
  • Now with java 8 default methods we can add methods to interface without disturbing existing functionality.
  • So instead of overriding now we can inherit these default methods from interfaces

  • Defaults methods are also  known as defender methods or virtual extension methods
  • Default methods will help us to avoid utility classes.
  • We can define utility methods inside the interface and use it in all classes which is implementing.
  • One of the major reason to introduce this default methods in java 8 is to support lambda expressions in collections API and to enhance.


  1. package com.instanceofjava;
  2. interface Java8Interface{
  3.  
  4. abstract void show();
  5.   
  6. default void display(){
  7.  
  8. System.out.println("default method of interface");
  9.  
  10. }
  11.  
  12. }

  1. package com.instanceofjava;
  2. class Sample implements Java8Interface {
  3.  
  4. void show(){
  5. System.out.print("overridden method ")
  6.  }
  7. public static void main(String[] args){
  8.   
  9. Sample obj= new Sample();
  10.  
  11. obj.show(); // calling implemented method
  12. obj.display(); // calling inherited method
  13. Java8Interface.display(); calling using interface name
  14.  
  15. }
  16.  
  17. }



Output:

 

  1. overridden method
  2. default method of interface
  3. default method of interface


How to call default methods:

 

  • We can all these default methods by using interface name and also by using object of the class which is implementing.
  • From above example
  • obj.show(); // calling implemented method
  • obj.display(); // calling inherited method
  • Java8Interface.display(); calling using interface name

Can we override java 8 default method

  • As we discussed above default methods in interfaces are implemented methods with bodies
  • Yes we can override same method in class which is implementing this interface.
  • Lets see one sample program how to override and what happens if we override


  1. package com.instanceofjava;
  2. interface InterfaceWithDefault{
  3.  
  4. default void defMethod(){
  5.  
  6. System.out.println("default method of interface");
  7.  
  8. }
  9.  
  10. }

  1. package com.instanceofjava;
  2. class Demo implements InterfaceWithDefault{
  3.  
  4. void defMethod(){
  5.  
  6. System.out.print("overridden method in class Demo ") 
  7.  
  8.  }
  9. public static void main(String[] args){
  10.   
  11. Demo obj= new Demo();
  12.  
  13. obj.defMethod(); // calling overridden method
  14. Java8Interface.defMethod(); calling using interface name : interface defMethod will be called
  15.  
  16. }
  17.  
  18. }

Output:


  1. overridden method in class Demo
  2. default method of interface

What happens if we implement two interfaces having same default methods

  • Now lets see if a class implementing two interfaces which are having same default methods
  • Whatever the implementation in the two interfaces defined if we implementing two interfaces which are having a default method in both then compilation error will come if two methods have same signature. works fine if two methods have same name with different arguments.
  • Check the below example programs to understand more.


  1. package com.instanceofjava;
  2. interface A{
  3.  
  4. default void defMethod(){
  5.  
  6. System.out.println("default method of interface: A");
  7.  
  8. }
  9.  
  10. }

  1. package com.instanceofjava;
  2. interface B{
  3.  
  4. default void defMethod(){
  5.  
  6. System.out.println("default method of interface: B");
  7.  
  8. }
  9.  
  10. }

  1. package com.instanceofjava;
  2. class Demo implements A, B{ // compilation error will come
  3.  
  4. public static void main(String[] args){
  5.   
  6. Demo obj= new Demo();
  7.  
  8.  
  9. }
  10.  
  11. }


  • If we implement two interfaces which are having same method with same parameters then compilation error will occur.
  • Duplicate default methods named "defMethod" with the parameters () and () are inherited from the types A and B.
  • If we define two methods with different type of parameters then we can work with both interfaces.



  1. package com.instanceofjava;
  2. interface A{
  3.  
  4. default void defMethod(){
  5.  
  6. System.out.println("Default method of interface: A");
  7.  
  8. }
  9.  
  10. }

  1. package com.instanceofjava;
  2. interface B{
  3.  
  4. default void defMethod(String str){
  5.  
  6. System.out.println("Default method of interface: B");
  7. System.out.println(str);
  8.  
  9.  
  10. }
  11.  
  12. }

  1. package com.instanceofjava;
  2. class Demo implements A, B{ // compilation error will come
  3.  
  4. public static void main(String[] args){
  5.   
  6. Demo obj= new Demo();
  7. obj.defMethod();
  8. obj.defMethod("Java 8")
  9.  
  10.  
  11. }
  12.  
  13. }

Output:

  1. Default method of interface: A
  2. Default method of interface: B 
  3. Java 8


1.Interface Static Methods in Java 8

  • Another Java 8 interface method is static method.
  • Now we can define static methods inside interface but we can not override these static methods.
  • These static method will act as helper methods.
  • These methods are the parts of interface not belongs to implementation class objects.

  1. package com.instanceofjava;
  2. interface StaticInterface{
  3.  
  4. Static void print(String str){
  5.  
  6. System.out.println("Static method of interface:"+str);
  7.  
  8. }
  9. }

  1. package com.instanceofjava;
  2. class Demo implements StaticInterface{
  3.  
  4. public static void main(String[] args){
  5.   
  6.  StaticInterface.print("Java 8")
  7.  
  8. }
  9.  
  10. }

Output:

  1. Static method of interface: Java 8


8 New Java 8 Features



Java 8 features

  1. Default and Static methods in Interface
  2. Lambda Expressions
  3. Optional
  4. Streams
  5. Method References
  6. Data Time API
  7. Nashorn Javascript Engine
  8. Parallel Arrays

 

 

 

1.Default and Static methods in Interface :

  • Java 8 introduces new features to interfaces.
  • Before java 8 interface having only abstract methods but now java 8 added two more type of methods to interface !.
  • First one is default method. A method which is having a default keyword with method body.
  • Actually interfaces wont have any implemented methods  but now with java 8 default method we can add a method with default implementation by using "default " keyword.
  • The classes which are implementing this interface can use these default method and same time it can override the existing method. But its not mandatory to override.

  1. package com.instanceofjava;
  2. interface Java8InterfaceDemo{
  3.  
  4. abstract void add();
  5.   
  6. default void display(){
  7.  
  8. System.out.println("default method of interface");
  9.  
  10. }
  11.  
  12. }


  • The second new method introduced in java 8 is static method.
  • Yes like in classes now we can define a static methods inside interface by using "static".
  • Basically static methods which are defined in interface are interface level only. if we want to call these static methods which are defined in interfaces we need to use interface name so that we can access these methods.

  1. package com.instanceofjava;
  2. interface Java8InterfaceDemo{
  3.  
  4. abstract void add();
  5.   
  6. default void display(){
  7.  
  8. System.out.println("default method of interface");
  9.  
  10. }
  11.  
  12. public static void show(){
  13.  
  14. System.out.println("static method of interface");
  15.  
  16. }
  17.  
  18. }

2.Lambda Expressions 

  • One of the most awaited and biggest release in java 8 is lamda expressions.
  • Ability to pass functionality/ behavior  to methods as arguments.
  • Allows us to write a method in the same place we are going to use it.

  1. package com.instanceofjava;
  2. interface JavalamdaExpression{
  3.  
  4. public static void main(String[] args){
  5.  
  6.  Arrays.asList( "j", "a", "v" ,"a","8").forEach( e -> System.out.print( e ) );
  7.  // java8
  8. }
  9.  
  10. }



3.java.util.Optional:

  • One of the best and cool feature of java 8 is Optional class. Which is a final calls from java.util package.
  • The major repeating statement in every project is checking "NullPointerException". Before using any object we need to check whether it is null or not if its not null then only we need to proceed.
  • Optional is just like a container which holds a value of type <T> or "null". By using isPresent() method of Optional class we can check particular object is null not not.


  1. package com.instanceofjava;
  2. import java.util.Optional:
  3. class Java8OptionalDemo{
  4.  

  5.  
  6. public static void main(String[] args ){
  7.  
  8.  Optional< String > str = Optional.ofNullable( null );
  9.  System.out.println( "str having value ? " + str.isPresent() ); // output : str having value ? false
  10.  
  11. }
  12.  
  13. }



4.Streams:

  • One of the excellent feature from java 8 as java.util.stream.
  • Stream API  introduces real-world functional-style programming into the Java.
  • Provides functional operations on stream of elements such as list , set and map 
  • Supports filtering, mapping and removal of duplicates of elements in collections, are implemented lazily.
  • Now we can get Streams from collections, arrays and bufferedReaders etc.


  1. package com.instanceofjava;
  2. import java.util.Arrays;
  3. class Java8StreamsDemo{
  4.  
  5. public static void main(String[] args ){
  6.  
  7.   Arrays.stream(new int[] {1, 2, 3,4,5})
  8.     .map(n -> 2 * n + 1) 
  9.    .average()
  10.     .ifPresent(System.out::println); // output: 7.0
  11.  
  12.  
  13. }
  14.  
  15. }

5.Method Reference:

  • We can use lambda expressions to create anonymous methods. 
  • Sometimes, however, a lambda expression does nothing but call an existing method.
    In those cases, it's often clearer to refer to the existing method by name.
  • Using Method references refer to the existing method by name, they are compact, easy-to-read lambda expressions for methods that already have a name


  1. package com.instanceofjava;
  2. import java.util.Arrays;
  3.  
  4. class Java8MethodRef{
  5.  
  6.   public  void show(String str){
  7.  
  8.         System.out.println(str);
  9.  
  10.    }
  11.  
  12. public static void main(String[] args ){
  13.  
  14.    Arrays.asList("a", "b", "c").forEach(new A()::show); // a b c

  15.  
  16. }
  17.  
  18. }

6.Data Time API  

  • The next cool feature from java 8 is new date time API(jsr 310) added within java.time package.
  • Before java 8 if we want to format dates we use SimpleDateFormatter class in java 8 while declaring date itself it has constructor to pass format of date.
  •  Some of the new classes introduced in java 8 date time are as follows.
  1. LocalTime
  2. LocalDate 
  3. LocalDateTime
  4. OffsetDate
  5. OffsetTime
  6. OffsetDateTime




  1. package com.instanceofjava;
  2. import java.util.Arrays;
  3.  
  4. class Java8DateTimeAPI{
  5.  
  6. public static void main(String[] args ){
  7.          
  8.     LocalDate currentDate = LocalDate.now();
  9.     System.out.println(currentDate);
  10.     
  11.     LocalDate twentyMarch2015 = LocalDate.of(2015, Month.MARCH, 06);
  12.     System.out.println(twentyMarch2015);  //2015-03-06
  13.  
  14.      LocalDate firstApril2015 = LocalDate.of(2015, 4, 1);
  15.      System.out.println(firstApril2015);//2015-04-01

  16.  
  17. }
  18.  
  19. }

 

7.Nashorn Javascript Engine


  •  Java 8 come with new Nashorn Javascript Engine which is allowing us to develop and run JavaScript applications.


  1. package com.instanceofjava;
  2.  
  3. import javax.script.ScriptEngine;
  4. import javax.script.ScriptEngineManager;
  5. import javax.script.ScriptException;
  6.  
  7. import java.util.Arrays;
  8.  
  9. class Java8JavaScript{
  10.  
  11. public static void main(String[] args ){
  12.          
  13.   ScriptEngineManager manager = new ScriptEngineManager();
  14.   ScriptEngine engine = manager.getEngineByName( "JavaScript" );
  15.   System.out.println( engine.getClass().getName() );
  16.   System.out.println( "output:" + engine.eval( "function show() { return 10; }; show();" ) );
  17.  
  18. }
  19.  
  20. }

  1. jdk.nashorn.api.scripting.NashornScriptEngine
  2. output:10


8.Parallel Array Sorting

  • As of now java 7 we already having Arrays.sort() method to sort objects now java 8 introduced parallel sorting which has more speed than arrays.sort() and follows Fork/Join framework introduced in Java 7 to assign the sorting tasks to multiple threads that are available in the thread pool.
  • Java 8 added parallel sorting functionalities to java.util.Arrays to take advantage of multithread machines 


  1. package com.instanceofjava;
  2. import java.util.Arrays;

  3. class Java8JavaScript{
  4.  
  5. public static void main(String[] args ){
  6.          
  7.          int arr[]={1,4,2,8,5};
  8.          Arrays.parallelSort(arr);
  9.  
  10.          for(int i:arr){  
  11.              System.out.println(i);  
  12.            } 
  13.  
  14. }
  15.  
  16. }



You might like:

Method and Type of methods


Method:

 

  • Method is a sub block of a class that contains logic of that class.
  • logic must be placed inside a method, not directly at class level, if we place logic at class level compiler throws an error.
  • So class level we are allowed to place variables and methods.
  • The logical statements such as method calls, calculations and printing related statements must be placed inside method, because these statements are considered as logic.



  1. package com.instanceofjava;
  2. class sample{
  3.  
  4. int a;
  5. int b;
  6.  
  7. System.out.println("instance of java"); // compiler throws an error.
  8.  
  9. }
  10.  

  1. package com.instanceofjava;
  2. class sample{
  3.  
  4. static int a=10;
  5.    
  6. public static void main(String args[]){

  7. System.out.println(a); // works fine,prints a value:10
  8.  
  9.  }
  10. }

Method Terminology:

1.Method Prototype:

  • The head portion of the method is called method prototype.
  1. package com.instanceofjava;
  2. class sample{
  3.  
  4. static int b=10;
  5.    
  6. public static void main(String args[]) // ->method prototype.
  7. {

  8. System.out.println(b); 
  9.  
  10.  }

2.Method body and logic:

  • The "{ }" region is called method body, and the statements placed inside method body is called logic.

  1. package com.instanceofjava;
  2. class sample{

  3. public static void main(String args[]) // ->method prototype.
  4.  
  5.   int a=10,b=20; // method logic
  6.   int c=a+b;  // method logic
  7.   System.out.println(c);  // method logic
  8.  
  9.  }
  10. }



3.Method parameters and arguments:

  • The variables declared in method parenthesis "( )" are called parameters.
  • We can define method with 0 to n number of parameters.
  • The values passing to those parameters are called arguments.
  • In method invocation we must pass arguments according to the parameters order and type.

  1. package com.instanceofjava;
  2. class sample{

  3. public void add(int a, int b) // ->method prototype. int a, int b are parameters
  4.  
  5.   int c=a+b;  // method logic
  6.   System.out.println(c);  // method logic
  7.  
  8.  }
  9.  
  10. public static void main(String args[]) // ->method prototype.
  11.  
  12.   sample obj= new sample();
  13.   
  14.  obj.add(1,2); //method call , here 1, 2 are arguments.

  15. }
  16. }

4:Method signature:

  • The combination of method "name + parameters "  is called method signature

  1. package com.instanceofjava;
  2. class sample{

  3. public void add(int a, int b) // ->method prototype. int a, int b are parameters
  4.  
  5.   int c=a+b;  // method logic
  6.   System.out.println(c);  // method logic
  7.  
  8.  }
  9.  
  10. public static void main(String args[]) // ->method prototype.
  11.  
  12.   sample obj= new sample();
  13.   
  14.  obj.add(1,2); //method call , here 1, 2 are arguments.

  15. }
  16. }

  • In the above program add(int a, int b) and  main(String args[]) are method signatures.

5. Method return type:

  • The keyword that is placed before method name is called method return type.
  • It tells to compiler and JVM about the type of the value is returned from this method after its execution
  • If nothing is return by method then we can use "void" keyword which specifies method returns nothing.

  1. package com.instanceofjava;
  2. class sample{

  3. public int add(int a, int b) // ->method prototype. int a, int b are parameters
  4.  
  5.   int c=a+b;  // method logic
  6.   return c;
  7.  }
  8.  
  9. public static void main(String args[]) // ->method prototype.
  10.  
  11.   sample obj= new sample();
  12.   
  13. int x= obj.add(1,2); //method call , here 1, 2 are arguments.
  14. System.out.println(x);

  15. }
  16. }

Type of declaration of methods based on return type and arguments:

1.Method with out return type  and without arguments.


  1. package com.instanceofjava;
  2. class sample{
  3.  
  4. public void add(){
  5.  
  6. int a=10;
  7. int b=10;
  8. int c=a+b;
  9. System.out.println(c);
  10.  
  11. }

  12. public static void main(String args[]) // ->method prototype.
  13.  
  14. sample obj= new sample();
  15. obj.add();
  16.  
  17.  
  18.  }
  19. }

2.Method with out return type and with arguments.


  1. package com.instanceofjava;
  2. class sample{
  3.  
  4. public void add(int a, int b){
  5.  
  6. int c=a+b;
  7. System.out.println(c);
  8.  
  9. }

  10. public static void main(String args[]) // ->method prototype.
  11.  
  12. sample obj= new sample();
  13. obj.add(1,2);
  14.  
  15.  
  16.  }
  17. }

3.Method with return type  and without arguments.


  1. package com.instanceofjava;
  2. class sample{
  3.  
  4. public int add(){
  5. int a=20;
  6. int b=30;
  7. int c=a+b;
  8. return c;
  9. }

  10. public static void main(String args[]) // ->method prototype.
  11.  
  12. sample obj= new sample();
  13. int x=obj.add(); 
  14. System.out.println(x);
  15.  
  16.  }
  17. }


4.Method with return type and with arguments.

 

  1. package com.instanceofjava;
  2. class sample{
  3.  
  4. public int add(int a, int b){
  5.  
  6. int c=a+b;
  7. return c;
  8. }

  9. public static void main(String args[]) // ->method prototype.
  10.  
  11. sample obj= new sample();
  12.  
  13. int x=obj.add(1,2);
  14. System.out.println(x);
  15.  
  16.  }
  17. }

Method terminology : main method

  • Lets take main method and identify method parts
Java Methods






















1.Method Creation with body:

  • The process of creating method with body is called method definition.
  • Technically this method called concrete method.


  1. class A{
  2.  
  3. public void add(){
  4.  
  5. }
  6.  
  7. }

2.Method Creation without body:

  • Creating a method without body is called  "Declaring a method" or "Method declaration".
  • Technically this method called "abstract method".
  • In method declaration the modifier "abstract" is mandatory and also should be terminated with ";".
  • Example : public void add();
  • And only abstract class can have abstract method. (in interface we can use , by default all methods are abstract  )

  1. abstract class A{
  2.  
  3. abstract  public void add();
  4.  
  5. }

Static and non static methods:

  • If a method has static keyword in its definition then that method called static method.
  • We can call static method directly from main method.
  • If method does not have static keyword in its definition then it is a non static method. 
  • If we want to call a non static method from main method we need object of that class
  • if we want to call static method outside the class we can call by using classname.method();



  1. class A{
  2.  
  3. public static void show(){    // static method
  4.  System.out.println("static method");
  5.  
  6. public void display(){      //non static method
  7.  System.out.println("non static method");
  8.  
  9. public static void main(String[] args){
  10. show(); // static method call
  11. A obj= new A();
  12. obj.display(); // non static method call
  13. }
  14. }

Java Data Types

Need of Data Types

  • Data Types are used to store data temporarily in computer through a program
  • The data type will specify the type of data that will be stored into a memory location. 

Definition: 

  • The data type is something which gives information about
  • Size of the memory location and range of the data that can be accommodated inside that location.
  • Possible legal operations those can be performed on that location.
  • What type of result come out from an expression when we use these types inside that expression.
  • Whichever the keyword gives these semantics is treated as "data type".
  • The java language provides different categories of data types.

Different Java Data Types:

  • In java mainly we have two types of data types.
  1. Primitive data types or Fundamental data types.
  2. Referenced data types or Derived data types.

Data types in java


1.Primitives Data types:

  • The primitive data types are the predefined data types given by the programming language and they are meant for storing a single value.
  • Based on the type and range of data, primitive types are divided into 8 types.

1.Integer category: 

  • This category can be used for storing numbers which can be either positive value  or negative value without decimal points.
  • In this category we have 4 primitive data types whose memory sizes are different. 
  • All the 4 types under this category are used for storing same data. But there ranges are different. The java language is providing 4 types under Integer category. So that the memory is utilized efficiently. 
  1. byte  
  2. short
  3. int
  4. long
  •  Default value for all these types is "0".
Java Data types

 


2.Floating point category: 

  • This category can be used for storing numbers which can be either +VE or –VE with decimal point. In the floating point category we have two types whose size is different. The two data types are float and double.
  • Both the data types under the floating point category are used for storing same data but there range is different. The java language provide as two data types under floating point category so that memory is utilized efficiently. 
  • Default value of float is 0
  • Default value of double is 0.0 
  1. float
  2. double

Java Data types










3.Character category: 

  • This category can be used for storing a single character. A character can be represented by alphabets, a digit and special symbols. 
  • This category contains only one data type an it is char.
  • Default value of char is "one space"
  1. char
Java Data type






4.Boolean category: 

  • This category can be used for storing either true or false. Under the Boolean category only one data type an it is Boolean. The size is dependent on JVM to JVM.
Boolean data type








Limitations of primitive data types:

  • Using primitive data types we can not store multiple values in continuous memory locations
  • Due to this limitation we have to face 2 problems.

#1:

  • For instance if we want to store multiple values, for example 1 to 100 , we must create 100 variables. All those variables created across JVM at different locations as shown below.
  • Hence it takes more time to retrieve values.

Java data types memory allocation












#2: 

  • Also using variables we can not pass all values to the remote computer with single network call, which increases burden on network and also increase lines of code in program.

Referenced data types:

  • To solve above two problems, values must be stored in continuous memory locations with single variable name .
  • This can be possible using referenced types.
  • Referenced types are given to store values in continuous memory locations with single variable name to retrieve data in quick time and to pass all values with single network call.
  1. Array
  2. Class
  3. Interface

Coding Standards and Naming conventions

  • Coding Standards(CS) and Naming conventions(NC) are suggestions given by sun(Oracle).
  • CS and NC help developers to develop projects with more readability and understandability

Why Coding Standards? 

  • A program is written once , but read many times
    1. During debugging
    2. When adding to the program
    3. When updating the program
    4. When trying to understand the program
  • Anything that makes a program readable and understandable saves lots of time , even in the shot run.

Naming Conventions: 

1.Naming a class:

  • Class name should be "noun", because it represents things
  • Class name should be in title case , means Every word first letter should be capital letter.
  • This is also known as UpperCamelCase.
  • Choose descriptive and simple names.
  • Try to avoid acronyms and abbreviations.


  1. package com.instanceofjava
  2. public JavaDemo{
  3.  
  4.  }

2.Naming a Variable:

  • Variable name also should be noun, because it represents values.
  • Variable name should be start with small letter. 
  • Use lowerCamelCase.
  • Example: firstName, lastName, age.
  • For final variable all its letters should be capital and words must be connected with "_".
  • Example:  MAX_COUNT, MIN_COUNT.

  1. package com.instanceofjava
  2. public JavaDemo{
  3.  
  4.  String topicName;
  5.  String post;
  6.  int postNumber;
  7.  final static int MIN_WORDS=300;

  8.  }

3.Naming Method:

  • Method name should be verb because it represents action.
  • Use lowerCamelCase for naming methods
  • Example: setFirstName(), getFirstName(), getLastName().

  1. package com.instanceofjava
  2. public JavaDemo{
  3.  
  4.  String topicName;
  5.   
  6. public void setTopicName(String topicName) {
  7. this.topicName=topicName;
  8.  }
  9.  
  10. public void getTopicName() {
  11. return topicName;
  12.  }
  13.  
  14.  }

4.Naming a package:

  • All letters should be small 
  • like in java io, util, applet
  • Example com.instanceofjava

  1. package com.instanceofjava
  2. public JavaDemo{
  3.  }
  • If you do not follow all above naming conventions compiler wont any Error or exception.
  • But naming conventions are  useful in project and need to follow.
  • But we need to follow some identifier rules as follows.

Identifiers:

  • Identifier is the name of the basic programming elements.
  • class names, methods names , object names and variables names are identifiers
  • If we define a basic program without a name , compiler throws compile time error.
  • Compilation Error : <identifier> expected.
  • if we take a class without name then compile time error will come : Syntax error on token "class", Identifier expected after this token.

  1. package com.instanceofjava
  2. public {   //  Syntax error on token "class", Identifier expected after this token.
  3.  }

Rules in defining identifier:

  • While defining identifier we must follow bellow rules, else it leads to compile time error.


1.Identifier should only contain :

  1. Alphabets(a -z and A-Z)
  2. Digits (0-9)
  3. Special Characters ( _ and $)

2.Identifier should not start with a digit:

  • A digit can be used from second character onwards.
  • Example : 
  • 1strank : throws error
  • No1Rank : works fine

3.Identifier should not contain special characters except "-" and "$":

  • Example : 
  • first_name : works fine
  • first#name : throws error

4.Identifier is case sensitive :

  • identifier is case sensitive
  • For example a and A are different a!=A.

5.keyword cannot be used as user defined identifier :

  • we can not use keywords as our identifiers
  • For example int class; // Syntax error on token "class", invalid VariableDeclarator.

Note:

  • we can use predefined class names as identifiers
  • example : int String;
  • There is no limit in identifier length.

Java comments:

  • A description about a basic programming element is called comment.
  • Comments are meant for developer, to understand purpose.

Types of comments:

  • Java supports 3 types of comments
  1. Single line comments  - //
  2. Multiline comments  - /* */
  3. Document comment - /** */

Top 10 uses of Java Keywords

Keyword:

  • Keywords are predefined identifiers available directly throughout the JVM.
  • They have a special meaning inside java source code and outside of comments and strings.
  • For Example : public, static, void

Rules:

  • Keywords can not be used as user defined identifier by the programmer either for variable or method or class names, because keywords are reserved for their intended use.
  • All characters in keyword must be used in lower case.

Need of keywords:

  • Basically keywords are used to communicate with compiler and JVM about the operation we perform in java application.
  • In java we perform 10 different operations using keywords
  • They are:
  1. Creating Java file
  2. Storing data temporary
  3. Creating memory locations
  4. Controlling calculations
  5. Setting accessibility permissions
  6. Modifying default properties
  7. Object representation
  8. Establishing relations between classes
  9. Grouping classes
  10. Handling user mistakes
  • In java we have 50 keywords to perform all above 10 operations
  • Among them 47 introduced in java 1.0
  • In Java 1.2 new keyword "strictfp" was added.
  • In Java 1.4 new keyword "assert" was added
  • In Java 5 new keyword "enum" was added
  • Among 50 keywords 2 keywords are reserved words they can not be used in java program, because they defined but they are not implemented , those two are,
  1. goto
  2. const
     

1.Java Files

1.class
2.interface
3.enum

2.Data Types

4.byte
5.short
6.int
7.long
8.float
9.double
10.char
11.boolean
12.void

3.Memory Location

13.static
14.new

4.Control Statements

1.conditional

15.if
16.else
17.switch
18.case
19.default

2.loop

20.while
21.do
22.for

3.transfer

23.break
24.continue
25.return

5.Accessibility Modifiers

26.private
27.protected
28.public

6.Modifiers

28.static // used as modifier and class level memory allocation
29.final
30.abstract
31.native
32.transient
33.volatile
34.synchronized
35.strictfp

7.Object Representation

36.this
37.super
38.instanceof

8.Inheritance Relationship

39.extends
40.implements

9.Package

41.package
42.import

10.Exception Handling

43.try
44.catch
45.finally
46.throw
47.throws
48.assert

11.Unused keywords

49.const
50.goto


Default literals:

1.referenced literal
  ->null
2.boolean literals
->true
->false

Reading data from file using FIleInputStream

1.Reading the data from a file:

  • FileInputStream class is used to read data from a file.
  • It is two step process.
  1. Create  FileInputStream class object by using its available constructors.
  2. Then call read() method on this object till control reach end of file.
  • Means read() method must be called in loop, because it returns only one byte at a time .
  • Hence it must be called in loop for each byte available in the file till it returns "-1".
  • It returns  -1 if control reached end of the file.
FileInputStream class has below constructors to create its object:

  1.  public FileInputStrean(String name) throws FileNotFoundException
  2.  public FileInputStream(File file)  throws FileNotFoundException
  3.  public FileInputStream(FileDescriptor fd)

Rule:

  • To Create FileInputStream class object the file must be with the passed argument name . else this constructor throws java.io.FileNotFoundException.
  • FileInputStream  class constructor throws FileNotFoundException in below situations.
  • If the file is not existed with the passed name.
  • Passed file name is a directory rather than is a regular file.
  • If file does not have reading permissions.

 Java Program to read data from a file:

  1.  Create a file with name test.txt. with text "hello world" this is for example you can write any text.
  2. Creating stream object connecting to test.txt file.
    FileInputStream fis= new FileInputStream("test.txt");
  3. Reading all bytes from the file till control reaches end of file.
    int i=fis.read();
  4. Printing returned character.
    System.out.println(i);

Program #1: 

  1. package com.instanceofjava;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6.  
  7. public class FISDemo {
  8.  
  9.  public static void main(String[] args) throws FileNotFoundException, IOException
  10. {
  11.  
  12.       FileInputStream fis= new FileInputStream("E:\\test.txt");
  13.  
  14.         int i;
  15.         while((i=fis.read())!=-1){
  16.            System.out.println((char)i);
  17.         }
  18.  
  19.     }
  20. }

Output:

  1. h
  2. e
  3. l
  4. l
  5. o
  6.  
  7. w
  8. o
  9. r
  10. l
  11. d

Program #2: Using read() method

  1. package com.instanceofjava;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6.  
  7. public class FISDemo {
  8.  
  9.  public static void main(String[] args) throws FileNotFoundException, IOException
  10. {
  11.  
  12.       FileInputStream fis= new FileInputStream("E:\\test.txt");
  13.  
  14.        byte[] b=new byte[fin.available()];
  15.  
  16.        // Read data into the array
  17.         fin.read(b);
  18.         for (int i = 0; i < b.length; i++) {
  19.  
  20.             System.out.println((char)b[i]);
  21.  
  22.         }
  23.  
  24.     }
  25. }

Output:

  1. h
  2. e
  3. l
  4. l
  5. o
  6.  
  7. w
  8. o
  9. r
  10. l
  11. d

Program #3: Using read(destination, start-index, last-index) method

  1. package com.instanceofjava;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6.  
  7. public class FISDemo {
  8.  
  9.  public static void main(String[] args) throws FileNotFoundException, IOException
  10. {
  11.  
  12.       FileInputStream fis= new FileInputStream("E:\\test.txt");
  13.  
  14.       byte b1[]=new byte[fin.available()];
  15.       fin.read(b1,0,b1.length);
  16.  
  17.                     for(int i=0;i<b1.length;i++)
  18.                     {
  19.                     System.out.print((char)b1[i]);
  20.                     }
  21.  
  22.     }
  23. }



Output:

  1. hello world

Create Thread without extending Thread and implementing Runnable

Using AnonymousThread:

  1. package com.instanceofjava;
  2.  
  3. public class AnonymousThread
  4. {
  5.  
  6. public static void main(String[] args)
  7.     {
  8.         new Thread(){
  9.  
  10.             public void run(){
  11.  
  12.                 for (int i = 0; i  <=10; i++) {
  13.                    System.out.println("run"+i);
  14.                 }
  15.  
  16.             }
  17.  
  18.         }.start();
  19.  
  20.         for (int i = 0; i  <=10; i++) {
  21.             System.out.println("main:"+i);
  22.         }
  23. }
  24. }

Output:

  1. main:0
  2. run:0
  3. main:1
  4. run:1
  5. main:2
  6. run:2
  7. main:3
  8. run:3
  9. main:4
  10. run:4
  11. main:5
  12. run:5
  13. main:6
  14. run:6
  15. main:7
  16. run:7
  17. main:8
  18. run:8
  19. main:9
  20. run:9
  21. main:10
  22. run:10

 

Using AnonymousRunnable:

  1. package com.instanceofjava;
  2.  
  3. public class AnonymousRunnable
  4. {
  5.  
  6. public static void main(String[] args)
  7.     {
  8.         new Thread(new Runnable(){
  9.  
  10.  
  11.     public void run(){
  12.  
  13.                 for (int i = 0; i  <=10; i++) {
  14.                    System.out.println("run"+i);
  15.                 }
  16.  
  17.             }
  18.  }
  19. ).start();
  20.  
  21.         for (int i = 0; i  <=10; i++) {
  22.             System.out.println("main:"+i);
  23.         }
  24. }
  25. }


Output:

  1. main:0
  2. run0
  3. main:1
  4. run1
  5. main:2
  6. run2
  7. main:3
  8. run3
  9. main:4
  10. run4
  11. main:5
  12. run5
  13. main:6
  14. run6
  15. main:7
  16. run7
  17. main:8
  18. run8
  19. main:9
  20. run9
  21. main:10
  22. run10
Select Menu