Category Archives: Core Java

java – Access Modifiers

The communication between the classes,variables,methods and constructors are defined by the Access Modifiers.There are types in Access Modifiers.They are,

  • public
  • protected
  • private
  • default
Access Modifier
Access Modifier

Public:

The members with public access modifier are accessible by any class or member of class in java.These public variables,methods,classes and constructors are visible to all classes in java.

Protected:

The protected variables and methods cannot be inherited by interface and classes.It cannot be used as modifiers to methods and variables inside the interface.These members can be accessed by the sub-class of different package and classes of same package.

Private:

The private variables and methods cannot be inherited by interface and classes.It cannot be used as modifiers to methods and variables inside the interface Private members are only accessible inside the class in which it is declared.

Note: Best strategy to access the private members is by using Getter and Setter methods.It is called as Encapsulation


Default:

When no access modifier is specified to a member,it will be considered as default access modifier member.The member with default access modifier can be accessed by Sub-Class of Same package or Classes of Same Package but not outside the package.

Example Code 1 – Sub Class within Same Package

  • Class: ModifierSetter.java


package p1;
public class ModifierSetter
{
public int a=100;
protected int b=200;
private int c=300;
int d=10;

public void setA(int a)
{
this.a = a;
}
public int getA()
{
return a;
}
private void setC(int c)
{
this.c = c;
}
private int getC()
{
return c;
}

protected void setB(int b)
{
this.b = b;
}
protected int getB()
{
return b;
}
void setD(int d)
{
this.d = d;
}

int getD()
{
return d;
}
}

  • Class: SubClassinSamePackage

  • package p1;
    public class SubClassinSamePackage extends ModifierSetter
    {
    public static void main(String args[])
    {
    ModifierSetter obj = new ModifierSetter();

    System.out.println("Value of A:"+obj.a);
    System.out.println("Value of B:"+obj.b);
    System.out.println("Value of D:"+obj.d);
    obj.setA(10);
    obj.setB(20);
    obj.setD(40);

    System.out.println("Value of A after Set:"+obj.getA());
    System.out.println("Value of B after Set:"+obj.getB());
    System.out.println("Value of D after Set:"+obj.getD());

    /*
    Below Lines raise error as we are trying to access private members
    */
    //System.out.println("Value of C:"+obj.c);
    //obj.setC(30);
    //System.out.println("Value of C after Set:"+obj.getC());
    }
    }

    Output:

    Value of A:100
    Value of B:200
    Value of D:10
    Value of A after Set:10
    Value of B after Set:20
    Value of D after Set:40

    Example Code 2 – Sub Class in Different Package

  • Class: ModifierSetter.java
  • package p1;
    public class ModifierSetter
    {
    public int a=100;
    protected int b=200;
    private int c=300;
    int d=10;

    public void setA(int a)
    {
    this.a = a;
    }
    public int getA()
    {
    return a;
    }
    private void setC(int c)
    {
    this.c = c;
    }
    private int getC()
    {
    return c;
    }
    protected void setB(int b)
    {
    this.b = b;
    }
    protected int getB()
    {
    return b;
    }
    void setD(int d)
    {
    this.d = d;
    }
    int getD()
    {
    return d;
    }
    }

  • Class: SubClassinDifferentPacakage.java

  • package p1;
    public class SubClassinDifferentPacakage
    {
    public static void main(String args[])
    {
    ModifierSetter obj = new ModifierSetter();

    System.out.println("Value of A:"+obj.a);
    System.out.println("Value of B:"+obj.b);
    System.out.println("Value of D:"+obj.d);
    obj.setA(10);
    obj.setB(20);
    obj.setD(40);

    System.out.println("Value of A after Set:"+obj.getA());
    System.out.println("Value of B after Set:"+obj.getB());
    System.out.println("Value of D after Set:"+obj.getD());
    /*
    * Below Lines raise error as we are trying to access private members
    //System.out.println("Value of C:"+obj.c);
    //obj.setC(30);
    //System.out.println("Value of C after Set:"+obj.getC());

    }
    }

    Output:

    Value of A:100
    Value of B:200
    Value of D:10
    Value of A after Set:10
    Value of B after Set:20
    Value of D after Set:40

    Example Code 3 – Super Class from Different Pacakage

  • Class: ModifierSetter.java

  • package p1;
    public class ModifierSetter
    {
    public int a=100;
    protected int b=200;
    private int c=300;
    int d=10;

    public void setA(int a)
    {
    this.a = a;
    }
    public int getA()
    {
    return a;
    }
    private void setC(int c)
    {
    this.c = c;
    }
    private int getC()
    {
    return c;
    }
    protected void setB(int b)
    {
    this.b = b;
    }
    protected int getB()
    {
    return b;
    }
    void setD(int d)
    {
    this.d = d;
    }
    int getD()
    {
    return d;
    }
    }

  • Class: ClassInDifferentPackage.java

  • package p2;
    import p1.ModifierSetter;
    public class ClassInDifferentPackage
    {
    public static void main(String args[])
    {
    ModifierSetter obj = new ModifierSetter();
    System.out.println("Value of A:"+obj.a);
    obj.setA(10);

    /*
    * Below Lines raise error(private and protected members are not accessible by a Super class from different package)
    */
    // System.out.println("Value of b:"+obj.b);
    // System.out.println("Value of D:"+obj.d);
    // System.out.println("Value of c:"+obj.c);
    // obj.setB(20);
    // obj.setD(40);
    // obj.setC(30);
    // System.out.println("Value of c after Set:"+obj.getC());
    // System.out.println("Value of B after Set:"+obj.getB());
    // System.out.println("Value of D after Set:"+obj.getD());
    }
    }

    Output:

    Value of A:100

    Java – Java Variable Types

    In Java all variables must be declared before the use.basic declaration will be like,

    Syntax:

    ‘ DataType VariableName; ‘

    Example:

    int a;

    float b;

    Continuous declaration also allowed like ‘int a,b,c;’.

    There are three types of variables in java.they are,

    • Local Variable.
    • Instance Variable.
    • Class/Static Variable.

    Local Variable:

    • Local variables are declared inside the method,constructor or block.
    • They are visible only inside the block in which they are declared.
    • Local variables do not have a default value so it must be declared  and initialized before the first use.
    • Access modifiers cannot be implemented for local variables.
    • Local variables are destroyed immediately after exits the block.

    Example Code:

    public class Age {

    public void printAge()

    {

    int ageCount = 0;        // ageCount is a Local Variable

    ageCount = ageCount + 5;

    System.out.println(“Age is “+ageCount);

    }

    public static void main(String args[])

    {

    Age object1 = new Age();

    object1.printAge();

    }

    }

    Instance Variable:

    • Instance variables are declared outside the method and constructor or block.
    • Memory will be created in the heap when the instance variable is created.
    • Instance variable is created when an object is created using the ‘new’ keyword.
    • Access modifiers can be applied to these variables.but however ‘private’ is advisable.If the variables needs to be accessed by the subclasses then the visibility can be modified.
    • Instance variables have their default values.So it is not a must to declare and instantiate.Example: int a;
      Here the variable ‘a’ holds 0 as its default value.
    • Instance variables holds values that must be referenced by more than one method,constructor or block.State should be maintained throughout the class.
    • They can be directly called by their name inside the class.Subclasses have to use the qualified name.Example: ‘ObjectName.VariableName’

    Example Code:

    public class Employee {

    public String employeeName;     // employeeName and employeeSalary are Instance Variables

    public int employeeSalary;

    public Employee(String name)

    {

    employeeName = name;

    }

    public void setEmployeeValues(int pay)

    {

    employeeSalary = pay;

    System.out.println(“Employee Name is “+employeeName+” and Employee Salary is “+employeeSalary);

    }

    public static void main(String args[])

    {

    Employee employee = new Employee(“Manishankar”);

    employee.setEmployeeValues(50000);

    }

    }

    Class/Static Variable:

    • Class variables are also called as Static variables.Variables are declared with a ‘Static’ keyword outside the method,constructor or block.
    • There will be only one copy of the static variable.
    • Static variables can have access modifiers.
    • Static variables starts when the program starts and destroyed when the program stops.
    • Static variables have static memory.
    • Static variables can be accessed by calling the variable with its class name.Example: ‘ClassName.VariableName’

    Example Code:

    public class Test {

    // Salary is a private static variable

    private static int salary;

    // Name is a constant variable

    private static final String name = “Manishankar”;

    public static void main(String args[])

    {

    salary = 50000;

    System.out.println(“Salary is “+salary+” and Name is “+name);

    }

    }

    Java – Objects and Classes…

    Java is an Object Oriented Language.It supports Object Oriented features like,

    • Polymorphism
    • Inheritance
    • Classes
    • Objects
    • Abstraction
    • Encapsulation
    • Overloading
    • Overriding
    • Reusability

    Objects in Java:

    Object Oriented concepts are implemented to match the real life entities.Object can be a man,desk,car or anything which has a

    • State
    • Identity
    • Behaviour

    Classes in Java:

    A class is an collection of objects which holds the properties of the objects.Its is an blue print of the objects behaviour.

    Example:

    A clear definition of a class would be,consider a class as a car.

    • Identity – A car has a color,number and unique body.
    • Behaviour – A car can move,move backward etc.
    • State – Car is idle,moving etc.

    Creating a Class:

    public Class Car

    {

    String carName;

    int carNumber;

    String carColor;

    void moving();

    void stop();

    }

    A Class can contain any number of variables,methods and objects.Here moving() and stop() are methods remaining things would fall as variables.There are types in variables we gonna have them later.

    Creating an Object:

    Object can hold values.It is used to match real time entities as i said earlier.Objects can be created using the ‘new’ keyword.Here the ‘new’ refers to a new memory allocation.

    Object can be created in several ways.They are,

    1.Declaration

    2.Instantiation

    3.Initialization

    Declaration:

    Syntax: ‘ClassName ObjectName;’

    Instantiation:

    Syntax: ‘ClassName ObjectName = new ClassName();’

    Initialization:

    Syntax: ‘ClassName ObjectName = new ClassName(“Value”);’

    Java – Sample method in java

    After the simple ‘HelloWorld’ program this is going to be easy too.

    Method:

    A method is a collection of coding which is specified by its name and signature.It is called to perform a specific task.

    Code:

    public class Cars

    {
    public static void sampleMethod()     //this is a method which prints some message
     {
            System.out.println(“This is a method”);
     }
    public static void main(String args[])
    {
        sampleMethod();                             // calling the method sampleMethod
    }
    }

    Note:

    • Here the method modifier is static because everything inside the static field will be static.So to call the method inside the main method ‘public static void main(String args[])’ we defined it as static.

    Java – Basic Data Types in java..

    A data type is used to specify the compiler about the type of value will be stored in the variable.

    Example:text,numbers etc.

    There are two data types available in Java:

    1. Primitive Data Types
    2. Reference/Object Data Types

    Primitive Data Types:

    There are eight primitive data types supported by Java. Primitive data types are predefined by the language and named by a key word. Let us now look into detail about the eight primitive data types.

    byte:

    • Byte data type is a 8-bit signed two’s complement integer.
    • Minimum value is -128 (-2^7)
    • Maximum value is 127 (inclusive)(2^7 -1)
    • Default value is 0
    • Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an int.
    • Example : byte a = 100 , byte b = -50

    short:

    • Short data type is a 16-bit signed two’s complement integer.
    • Minimum value is -32,768 (-2^15)
    • Maximum value is 32,767(inclusive) (2^15 -1)
    • Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an int
    • Default value is 0.
    • Example : short s= 10000 , short r = -20000

    int:

    • Int data type is a 32-bit signed two’s complement integer.
    • Minimum value is – 2,147,483,648.(-2^31)
    • Maximum value is 2,147,483,647(inclusive).(2^31 -1)
    • Int is generally used as the default data type for integral values unless there is a concern about memory.
    • The default value is 0.

    Example : int a = 100000, int b = -200000.

    long:

    • Long data type is a 64-bit signed two’s complement integer.
    • Minimum value is -9,223,372,036,854,775,808.(-2^63)
    • Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
    • This type is used when a wider range than int is needed.
    • Default value is 0L.
    • Example : int a = 100000L, int b = -200000L

    float:

    • Float data type is a single-precision 32-bit IEEE 754 floating point.
    • Float is mainly used to save memory in large arrays of floating point numbers.
    • Default value is 0.0f.
    • Float data type is never used for precise values such as currency.
    • Example : float f1 = 234.5f

    double:

    • double data type is a double-precision 64-bit IEEE 754 floating point.
    • This data type is generally used as the default data type for decimal values. generally the default choice.
    • Double data type should never be used for precise values such as currency.
    • Default value is 0.0d.
    • Example : double d1 = 123.4

    boolean:

    • boolean data type represents one bit of information.
    • There are only two possible values : true and false.
    • This data type is used for simple flags that track true/false conditions.
    • Default value is false.
    • Example : boolean one = true

    char:

    • char data type is a single 16-bit Unicode character.
    • Minimum value is ‘\u0000’ (or 0).
    • Maximum value is ‘\uffff’ (or 65,535 inclusive).
    • Char data type is used to store any character.
    • Example . char letterA =’A’

    Reference Data Types:

    • Reference variables are created using defined constructors of the classes. They are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example, Employee, Puppy etc.
    • Class objects, and various type of array variables come under reference data type.
    • Default value of any reference variable is null.
    • A reference variable can be used to refer to any object of the declared type or any compatible type.
    • Example : Animal animal = new Animal(“giraffe”);

    iPhone – HelloWorld program in java..

    Welcome to the java world.This is an simple HelloWorld example.

    If you are new to programs ,Basic Terms you should know before the code:

    Class:

    Class is an collection of objects.it is an wrapper for the objects.

    Example:Classroom(Classroom contains benches,boards etc)

    Object

    Everything is considered to be an object.Especially in java everything is an object.Remember java is used for platform independent and real life entity mapping too.

    Example:pen,bike,cap….

    Method:

    Method is a collection of code which are called to do a specific task.

    Example:Brakes in a vehicle…

    Variable:

    Variable are used to store values which are used later for computations.

    Example:Wallet,box…

    CODE:

    public class HelloWorld {

    public static void main(String[] args) {

     System.out.println(“HelloWorld”);
        }
    }

    OUTPUT:

    Explanation:

    public class HelloWorld {

    • HelloWorld is the class name and its access specifier is public so it can be accessed from any other classes.

    public static void main(String[] args) {

    • Here public is the access specifier so the is accessible for other class.
    • It is static so it has only single memory.
    • void is the return type of this method so the method wont return any values.
    • String[] args is the parameter passed to this method.

    System.out.println(“HelloWorld”);

    • This line prints the value ‘HelloWorld’.
    • Here println() is a method.
    • out is an object.
    • System is a class name.

    Java – Birth of java!!

    Hi everyone if somebody who is new to the terms ‘Programming’ asks me a question

    “Which programming language shall i learn ?” ….My answer will be Louder its “JAVA”.yes java is one of the efficient programming language which everyone can learn.okay let me explain the birth of java baby,

      James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. Java was originally designed for interactive television, but it was too advanced for the digital cable television industry at the time. The language was initially called Oak after an oak tree that stood outside Gosling’s office; it went by the name Green later, and was later renamed Java, fromJava coffee, said to be consumed in large quantities by the language’s creators. Gosling aimed to implement a virtual machine and a language that had a familiar C/C++ style of notation.

    Sun Microsystems released the first public implementation as Java 1.0 in 1995. It promised “Write Once, Run Anywhere” (WORA), providing no-cost run-times on popular platforms. Fairly secure and featuring configurable security, it allowed network- and file-access restrictions. Major web browsers soon incorporated the ability to run Java applets within web pages, and Java quickly became popular. With the advent of Java 2 (released initially as J2SE 1.2 in December 1998–1999), new versions had multiple configurations built for different types of platforms. For example, J2EE targeted enterprise applications and the greatly stripped-down version J2ME for mobile applications (Mobile Java). J2SE designated the Standard Edition. In 2006, for marketing purposes, Sun renamed new J2 versions asJava EEJava ME, and Java SE, respectively.

    In 1997, Sun Microsystems approached the ISO/IEC JTC1 standards body and later the Ecma International to formalize Java, but it soon withdrew from the process. Java remains a de factostandard, controlled through the Java Community Process. At one time, Sun made most of its Java implementations available without charge, despite their proprietary software status. Sun generated revenue from Java through the selling of licenses for specialized products such as the Java Enterprise System. Sun distinguishes between its Software Development Kit (SDK) and Runtime Environment (JRE) (a subset of the SDK); the primary distinction involves the JRE’s lack of the compiler, utility programs, and header files.

    On November 13, 2006, Sun released much of Java as free and open source software, (FOSS), under the terms of the GNU General Public License (GPL). On May 8, 2007, Sun finished the process, making all of Java’s core code available under free software/open-source distribution terms, aside from a small portion of code to which Sun did not hold the copyright.

    Sun’s vice-president Rich Green said that Sun’s ideal role with regards to Java was as an “evangelist.”Following Oracle Corporation’s acquisition of Sun Microsystems in 2009–2010, Oracle has described itself as the “steward of Java technology with a relentless commitment to fostering a community of participation and transparency”. This did not hold Oracle, however, from filing a lawsuit against Google shortly after that for using Java inside the Android SDK. Java software runs on laptops to data centers, game consoles to scientific supercomputers. There are 930 million Java Runtime Environment downloads each year and 3 billion mobile phones run Java.On April 2, 2010, James Gosling resigned from Oracle.