Monday, 30 October 2017

Package in Java

Package in Java

A package is a collection of similar types of classes, interfaces and sub-packages.

Purpose of package

The purpose of package concept is to provide common classes and interfaces for any program separately. In other words if we want to develop any class or interface which is common for most of the java programs than such common classes and interfaces must be place in a package.
Package in java
Packages in Java are the way to organize files when a project has many modules. Same like we organized our files in Computer. For example we store all movies in one folder and songs in other folder, here also we store same type of files in a particular package for example in awt package have all classes and interfaces for design GUI components.
Package in java

Advantage of package

  • Package is used to categorize the classes and interfaces so that they can be easily maintained
  • Application development time is less, because reuse the code
  • Application memory space is less (main memory)
  • Application execution time is less
  • Application performance is enhance (improve)
  • Redundancy (repetition) of code is minimized
  • Package provides access protection.
  • Package removes naming collision.

Type of package

Package are classified into two type which are given below.
  1. Predefined or built-in package
  2. User defined package

Predefined or built-in package

These are the package which are already designed by the Sun Microsystem and supply as a part of java API, every predefined package is collection of predefined classes, interfaces and sub-package.

User defined package

If any package is design by the user is known as user defined package. User defined package are those which are developed by java programmer and supply as a part of their project to deal with common requirement.

Rules to create user defined package

  • package statement should be the first statement of any package program.
  • Choose an appropriate class name or interface name and whose modifier must be public.
  • Any package program can contain only one public class or only one public interface but it can contain any number of normal classes.
  • Package program should not contain any main class (that means it should not contain any main())
  • modifier of constructor of the class which is present in the package must be public. (This is not applicable in case of interface because interface have no constructor.)
  • The modifier of method of class or interface which is present in the package must be public (This rule is optional in case of interface because interface methods by default public)
  • Every package program should be save either with public class name or public Interface name
package in java

Compile package programs

For compilation of package program first we save program with public className.java and it compile using below syntax:

Syntax

javac -d . className.java

Syntax

javac -d path className.java
Explanations: In above syntax "-d" is a specific tool which is tell to java compiler create a separate folder for the given package in given path. When we give specific path then it create a new folder at that location and when we use . (dot) then it crate a folder at current working directory.
Note: Any package program can be compile but can not be execute or run. These program can be executed through user defined program which are importing package program.

Example of package program

Package program which is save with A.java and compile by javac -d . A.java

Example

package mypack;
public class A
{
public void show()
{
System.out.println("Sum method");
}
}
Import above class in below program using import packageName.className

Example

import mypack.A;
public class Hello
{
public static void main(String arg[])
{
A a=new A();
a.show();
System.out.println("show() class A");
}
}
Explanations: In the above program first we create Package program which is save with A.java and compiled by "javac -d . A.java". Again we import class "A" in class Hello using "import mypack.A;" statement.

Difference between Inheritance and package

Inheritance concept always used to reuse the feature within the program between class to class, interface to interface and interface to class but not accessing the feature across the program.
Package concept is to reuse the feature both within the program and across the programs between class to class, interface to interface and interface to class.

Difference between package keyword and import keyword

Package keyword is always used for creating the undefined package and placing common classes and interfaces.
import is a keyword which is used for referring or using the classes and interfaces of a specific package.

StringTokenizer in Java

StringTokenizer in Java

It is a pre defined class in java.util package can be used to split the given string into tokens (parts) based on delimiters (any special symbols or spaces).
Suppose that we have any string like "Features of Java_Language" when we use stringTokenizer this string is split into tokens whenever spaces and special symbols present. After split string are :

Example

Features
of 
Java
Language

Methods of StringTokenizer

  • hasMoreTokens()
  • nextToken()

hasMoreTokens()

It is predefined method of StringTokenizer class used to check whether given StringTokenizer having any elements or not.

nextToken()

Which can be used to get the element from the StringTokenizer.

Example of StringTokenizer:

Example of StringTokenizer

import java.util.*;
class Stringtokenizerdemo
{
public static void main(String args[])
{
String str="He is a gentle man";
StringTokenizer st=new StringTokenizer(str," ");
System.out.println("The tokens are: ");
while(st.hasMoreTokens())
{
String one=st.nextToken();
System.out.println(one);
}
}
}

Output

The tokens are:
He
is
a
gentle
man

Scanner Class in Java

Java Scanner Class in Java

Scanner is one of the predefined class which is used for reading the data dynamically from the keyboard.
Import Scanner class

Import Scanner Class in Java

java.util.Scanner

Constructor of Scanner Class

Scanner(InputStream)

This constructor create an object of Scanner class by talking an object of InputStream class. An object of InputStream class is called in which is created as a static data member in the System class.

Syntax of Scanner Class in Java

Scanner  sc=new  Scanner(System.in);
Here the object 'in' is use the control of keyboard
scanner class in javascanner class in java

Instance methods of Scanner Class

MethodDescription
1public byte nextByte()Used for read byte value
2public short nextShort()Used for read short value
3public int nextInt()Used for read integer value
4public long nextLong()Used for read numeric value
5public float nextLong()Used for read numeric value
6public double nextDouble()Used for read double value
7public char nextChar()Used for read character
8public boolean nextBoolean()Used for read boolean value
9public String nextLine()Used for reading any kind of data in the form of String data.
Method 1 to 8 are used for reading fundamental values from the keyboard. Method 9 (public String nextLine() ) is used for reading any kind of data in the form of String data.

For Remember all above methods

From method 1 to 8 combindly we represent as public xxx nextxxx(). Here xxx represents any fundamental data type. These methods are used for reading the fundamental data from keyboard.

Accept two values dynamically from the keyboard and compute sum.

Example of Scanner Class in Java

import java.util.Scanner
public class ScannerDemo
{
public static void main(String args[])
{
Scanner  s=new  Scanner(System.in);
System.out.println("Enter first no= ");
int num1=s.nextInt();
System.out.println("Enter second no= ");
int num2=s.nextInt();
System.out.println("Sum of no is= "+(num1+num2));
}
}

Output

Enter first no=4
Enter second no=5
Sum of no is=9

Program which is accept two number as a string and compute their sum.

Example

import java.util.Scanner;
class Dataread 
{
public static void main(String[] args) 
{
Scanner s=new Scanner(System.in);
System.out.println("Enter first number: ");
String s1=s.nextLine();
System.out.println("Enter second number: ");
String s2=s.nextLine();
int res=Integer.parseInt(s1) + Integer.parseInt(s2);
System.out.println("Sum= "+res);
}
}

Output

Enter first number: 5
Enter second number: 6
Sum= 11

Volatile Keyword in Java

Volatile Keyword in Java

If the variable keep on changing such type of variables we have to declare with volatile modifier. Volatile is a modifier applicable only for variables but not for method and class.
If a variable declared as volatile then for every thread a separate local copy will be created. Every intermediate modification performed by that thread will takes place in local copy instead of master copy. Once the value got finalized just before terminating the thread the master copy value will be updated with local stable value.

Advantage of Volatile

The main advantage of Volatile keyword is we can resolve data inconsistency problems.

Dis-Advantage of Volatile

The main dis-advantage of Volatile keyword is, crating and maintaining a separate copy for every thread, increases complexity of the programming and effects performance of the system. Hence if there is no specific requirement it is never recommended to use volatile keyword, and it is almost outdated keyword.
Note: Volatile variable means its value keep on changing where as final variable means its value never changes. Hence final-Volatile combination is illegal combination for variables.

Synchronized Keyword in Java

                                                               

Synchronized Keyword in Java

Synchronized Keyword is used for when we want to allowed only one thread at a time then use Synchronized modifier. If a method or block declared as a Synchronized then at a time only one thread is allowed to operate on the given object.
Synchronized Keyword in Java
Synchronized is a Modifier which is applicable for the method or block, we can not declare class or variable with this modifier.

Advantage of Synchronized

The main advantage of Synchronized keyword is we can resolve data inconsistency problem.

Dis-Advantage of Synchronized

The main dis-advantage of Synchronized keyword is it increased the waiting time of thread and effect performance of the system, Hence if there is no specific requirement it is never recommended to use synchronized keyword.

How to use Static keyword in java

                                                                     

Static keyword in java

The static keyword is used in java mainly for memory management. It is used with variables, methods, blocks and nested class. It is a keyword that are used for share the same variable or method of a given class. This is used for a constant variable or a method that is the same for every instance of a class. The main method of a class is generally labeled static.
No object needs to be created to use static variable or call static methods, just put the class name before the static variable or method to use them. Static method can not call non-static method.

In java language static keyword can be used for following

  • variable (also known as class variable)
  • method (also known as class method)
  • block
  • nested class

Static variable

If any variable we declared as static is known as static variable.
  • Static variable is used for fulfill the common requirement. For Example company name of employees,college name of students etc. Name of the college is common for all students.
  • The static variable allocate memory only once in class area at the time of class loading.

Advantage of static variable

Using static variable we make our program memory efficient (i.e it saves memory).

When and why we use static variable

Suppose we want to store record of all employee of any company, in this case employee id is unique for every employee but company name is common for all. When we create a static variable as a company name then only once memory is allocated otherwise it allocate a memory space each time for every employee.

Syntax for declare static variable:

public static variableName;

Syntax for declare static method:

public static  void methodName()
{
.......
.......
}
Syntax for access static methods and static variable

Syntax

className.variableName=10;
className.methodName();

Example

public static final double PI=3.1415;
public static void main(String args[])
{
......
......
}

Difference between static and final keyword

static keyword always fixed the memory that means that will be located only once in the program where as final keyword always fixed the value that means it makes variable values constant.
Note: As for as real time statement there concern every final variable should be declared the static but there is no compulsion that every static variable declared as final.

Example of static variable.

In the below example College_Name is always same, and it is declared as static.

Example

class Student
{
int roll_no;
String name;
static String College_Name="ITM";
}
class StaticDemo
{
public static void main(String args[])
{
Student s1=new Student();
s1.roll_no=100;
s1.name="abcd";
System.out.println(s1.roll_no);
System.out.println(s1.name);
System.out.println(Student.College_Name); 
Student  s2=new  Student();
s2.roll_no=200;
s2.name="zyx";
System.out.println(s2.roll_no);
System.out.println(s2.name);
System.out.println(Student.College_Name); 
}
}

Example

Output:
100
abcd
ITM
200
zyx
ITM
In the above example College_Name variable is commonly sharable by both S1 and S2 objects.
variable declaration
In the above image static data variable are store in method are and non static variable is store in java stack. Read more about this in JVM Architecture chapter

why main method is static ?

Because object is not required to call static method if main() is non-static method, then jvm create object first then call main() method due to that face the problem of extra memory allocation.

Data Conversion in java

Data Conversion In java programming we have six data conversion technique they are:. 1 Converting numeric string type data into numeri...