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