Tutorial

by -

Lately we learnt about the Static keyword in Java, which makes methods available for invoking even before creating objects. Very often a method needs to refer to the object that invoked it. Java has come up with a feature/keyword ‘this’ to achieve the desired one. ‘this’ can be used inside any method to refer to the current object. ‘this’ is always a reference to the object on which the method was invoked.

Java This

Again sometimes when the formal parameter has the same name as an instance variable, then formal parameter hides the instance variable. To avoid hiding of instance variables ‘this’ is used to refer to the instance variable. So ‘this’ is used to resolve the namespace collisions that might occur between instance variables and formal parameters.

Program

class Employee{
  String employeeName;
  String employeeAddress;
  double salary;
  Employee(String employeeName,String employeeAddress,double salary){
    this.employeeName = employeeName;
    this.employeeAddress = employeeAddress;
    this.salary = salary;
  }
  void setSalary(double salary){
    this.salary = salary;
  }
  void showDetails(){
    System.out.println("Employee's Name: "+employeeName);
    System.out.println("Employee's Address: "+employeeAddress);
    System.out.println("Employee's salary: "+salary);
  }
}

class ThisDemo{
  public static void main(String args[]){
    String name = "Ricardo Kaka";
    String address = "South Africa";
    double salary = 26389.92;
    Employee employee = new Employee(name,address,salary);
    System.out.println("Employee Details:");
    System.out.println("--------------------------");
    employee.showDetails();
    System.out.println();
    System.out.println("Modified Employee Details:");
    System.out.println("--------------------------");
    salary = 34902.25;
    employee.setSalary(salary);
    employee.showDetails();
  }
}

Output

java programming

Explanation of the Java Code & Output

In the code we have written one parameterized constructor where the formal parameters have the same name as the name of the instance variables of the same class. Now it is clear that the formal parameters of the parameterized constructor will hide the instance variables of the Employee class. To resolve the problem we have used ‘this’ before the instance variables during initialization. Same is true for the setSalary() method which is used to update the salary. Here also the formal parameter to setSalary() has same name as the name of instance variable salary. So there is a namespace collision, formal parameter salary will hide the instance variable salary. To avoid this problem while initializing instance variable ‘this’ must be preceded.We will see one small program how formal parameter hides instance variable if both are having same name.

class Employee{
  double salary;
  int age;
  Employee(double salary){
    salary = salary;
  }
  Employee(double salary,int age){
     this.salary = salary;
     this.age = age;
  }
  void showDetails(){
    System.out.println("Salary: "+salary);
  }
}
class HideDemo{
  public static void main(String args[]){
    Employee emp = new Employee(23678.88);
    System.out.println("emp");
    System.out.println("---");
    emp.showDetails();
    Employee employee = new Employee(23678.88,21);
    System.out.println("\n");
    System.out.println("employee");
    System.out.println("--------");
    employee.showDetails();
  }
}

Output

this in java

In the first case we have not used ‘this’ even though there was a namespace collision between formal parameter of the constructor and the instance variable of the Employee class, meanwhile formal parameter has hidden the instance variable. But in the second case as we have used ’this’ before instance variable during initialization, this referred to instance variable and meanwhile we got the original value of the salary which was passed during initialization.

Flash On

  1. this’ always returns the reference to the current object.
  2. It can be used inside methods and constructors.
  3. this’ cannot be referenced in static context.
Next we will discuss about Recursion in Java.
Checkout more useful tutorials and definitive guidelines on Java programming here.

by -

Normally a class member must be accessed in conjunction with an object of its class. There will be times when you will want to define the class member which can be accessed without instantiating that class. This can be accomplished by ‘static’. To create such a member, precede its declaration with the keyword ‘static’.

Advantages of Static

When a member is declared static, it can be accessed before any objects of its class are created or without reference to any object.

Why do we declare main() as Static?

main() is the entry point of  a class. In java everything thing is written in a class. Now when you run java filename on command prompt, loader will load the class and JVM will search the main method to enter into the class. So making the main() as static, will make JVM access it directly through classname.main()

That’s why the program name must be same as the class name, where we wrote the main function.

Important Points to Remember 

  1. Instance Variables declared as static are essentially global variables. When you create objects of its class, no copy of a static variable is made. Even all objects share the same static variable.
  2. static variables or member functions will load during class. That means before creating any instances (objects), the main function is the first runnable function of any program which we run manually.
  3. If you want to get something executed/initialization of static variables before actual loading of the class, then put all those in static block.

E.g.

    static{

       System.out.println(“Static block initialized…”);

    }

It gets executed even before main() method during loading of the class.

Restrictions While using Static

  1. static method can access only static variables.
  2. static method can invoke static method only.
  3. static method can’t refer to this and super in any way.

Program

class Addition{
  static int num1;
  static int num2;
  int a;
  int b;
  Addition(){
    num1 = -1;
    num2 = -1;
    a = -1;
    b = -1;
  }
  Addition(int num1,int num2,int a,int b){
    this.num1 = num1;
    this.num2 = num2;
    this.a = a;
    this.b = b;
  }
  static void sum(){
    //System.out.println("Sum of 4 numbers is: "+(num1+num2+a+b));  /*static method can’t access static vars */
    System.out.println("Sum of 'num1' and 'num2' is: "+(num1+num2));
    System.out.println();
  }
  void add(){
    System.out.println("Addition of 4 numbers is: "+(num1+num2+a+b));
    System.out.println();
  }
}

class AditionDemo1{
  public static void main(String args[]){
    System.out.println();
    System.out.println("Static method sum() called without creating any object");
    System.out.println("------------------------------------------------------");
    Addition.sum();

    Addition ad1 = new Addition();

    System.out.println("Static Method sum() is invoked second time");
    System.out.println("-----------------------------------------------");
    Addition.sum();

    System.out.println("Non-Static Method add() is invoked using Object ad1");
    System.out.println("-----------------------------------------------");
    ad1.add();

    Addition ad2 = new Addition(10,20,30,40);

    System.out.println("Static Method sum() is invoked second time");
    System.out.println("-----------------------------------------------");
    Addition.sum();

    System.out.println("Non-Static Method add() is invoked using Object ad2");
    System.out.println("-----------------------------------------------");
    ad2.add();

    System.out.println("Static Method sum() is invoked third time");
    System.out.println("-----------------------------------------------");
    Addition.sum();

    System.out.println("Static Method sum() is invoked using Object");
    System.out.println("-------------------------------------------");
    ad1.sum();
    ad2.sum();
  }
}

Output

 Static in java

Explanation of the Java Code & Output

If you see the code carefully, then you will find we have taken two static variables and two non static variables which are initialized by two constructors viz. one is parameterized and another one is default. We have defined one static method and one non static method.

In main(), first we have invoked static method sum() without creating any object of Addition Class.

In the code you can see that static method can’t access non- static variables. If you try to access then you will get the following error, as we got:

Static in java

Now if you see, static variables are global variables only. Irrespective of the objects it has given the same result whenever static method sum() is invoked by any objects.

Non-static method can access static variables.

Non static method can invoke static methods.

Static methods can be invoked with <classname>.<static method name> and with <objectname>.< static method name > as well.

For non-static variables, each object will have different copies of non-static variables with different values for different objects.

Next we will learn about how to use “this” keyword in Java.

Checkout more useful tutorials and definitive guidelines on Java programming here.

by -

Blogging is not any easy job as you think and not any tougher also if you focus and learn each and every aspect of blogging steadily. Here I haveposted very useful 10 steps for blogging effectively to increase visitors and earn decent money online. Go through all the steps and implement it for good result.

best 10 Blogging tips you should know

1: Setup your blog clean and neatly.

Avoid advertising everywhere in your blog area. Visitors should easily go through all of your contents, so, make navigations to all pages and categories “user-friendly”. Remember, it doesn’t matter how tough your blog’s backend, but front end should be “user-friendly”.

2: Consistency and hard work.

Post articles regularly and maintain consistency. Your visitors might come again to your blog, if they find your article useful and interesting. If they not found any recent articles, then there is a chance of missing those visitors permanently. Be patience, there are no any shortcuts to increase visitors and pageviews. Please don’t go for any SEO kits or Quick paid visitors scams.

3: Genuine and Interesting Articles.

You should post unique, Interesting and useful articles to attract more and more visitors by directly or by search engines. Put your personal appeal to the articles. Involve with all the contents you post in your blogs.

4: Latest Trend hunting.

Keep your eyes open, look for the trending topics around the world. It is well and good if these topics are related to your niche. Be the first to post articles on related trending ideas/product. You can find these trends through twitter, news or around your neighborhood.

5: Reviews and News.

Search deeply about any products/ideas of your niche, try to test it manually or through other sources, and post a clean and personal review of those ideas/products. It should be of your niche.

6: Related articles and interlinks.

While posting an article, remember to provide link to your other interesting article in the posting article. If you use WordPress, then there are many Plugins available for the related articles at the end of every post. These Plugins uses your tags and categories to select related articles.

7: Socialize your articles.

Social networks are very useful to bring you good number of unique visitors. Use socializing Plugins and widgets in your blogs. Keep the space for sharing the articles in twitter, Facebook, stumbleupon, digg and many more. Don’t overload sharing buttons in your posts; it might make your blogs load slowly. There are many Plugins available for socializing your blog or website.

8: Search Engine Friendly Title.

Give your articles a search engine friendly name. Use permalinks in WordPress to show your article title as your article URL. But, keep it in mind that, use permalinks as date/year/post name, because if you only use words in your URL, then your blog will load bit slowly. Your SQL queries will be higher if you use only post name in permalinks.

9: Optimize blog’s SEO.

Make your blogs search engine friendly by using Meta Keywords, Meta Title, and Meta Descriptions.  Submit your URL and sitemap to Search engines. Use search engine friendly names to your images. This will help to get listed in image searches. There are many Plugins available for SEO in WordPress.

10: Comments and Interactions.

Use comments to all of your articles. If someone comments on your article, then reply them as soon as possible in the comments field, then the visitor will be satisfied or happy and he might come again and again to your site.

I posted these 10 steps of my personal experience and I am following these steps. You should always think positive and be confident. Don’t lose hope; you will become famous only if you are consistent, hardworking, and confident with long term plans. Don’t go for any shortcut methods of quick money online, most of them are scams and frauds.

If you trapped inside these scams, then your confidence level will decrease and you will start thinking negatively. I found these ways very useful and implement it on your blogs. Internet is vast and opportunity is less, try your luck, follow these steps, then you will be on the top list of bloggers. See you there!

Stay tuned on The Geeks Club for more Blogging and Make Money Online Tips.

by -

In our previous discussion we have come to know how to pass object reference to a method. In the same way, we can pass the reference to a constructor to initialize the instance variables of another object of the same class with the same value of the instance variables of the object which is passed to the constructor. That is one object is copied to other object.

Advantages of using Copy Constructor

There are several use cases where Copy Constructors works well with respect to other constructors in Java – 

As we know objects can be cloned in Java using clone() method. But copying object using clone() is not flexible and extensible, doesn’t work fine as well.

The first problem is that no constructor is called when the object is being cloned. As a result, it is your  responsibility, as a writer of the clone method, to make sure all the members have been properly set. Here is an example of where things could go wrong. Consider a class keeping track of the total number   of objects of that type, using a static int member. In the constructors you would increase the count. However, if you clone the object, since no constructor is called, the count will not truly reflect the number of objects!

Further, if the class has final fields, these can’t be given a value in the clone method. This leads to           problems with properly initializing the object’s final fields. If the final field is referring to some internal state of the object, then the cloned object ends up sharing the internal state and this surely is not correct for mutable objects.

Disadvantages of using Copy Constructor

As the one object is the exact replica of another, if any changes is made in the first one it will inadvertently change the values of the instance variables of the second one which is the copy of the first one. So you have to be careful and better not to declare copy constructor as public because during inheritance it doesn’t satisfy Open-Closed Principle (OCP). The OCP, by Bertrand Meyer, states that software entities should be open for extension, but closed for modifications.

Program

class Employee{
  String employeeName;
  String address;
  int age;
  double salary;

/*Default Constructor */

  Employee(){
    employeeName = "Platini";
    address = "France";
    age = 45;
    salary = 120500.92;
  }

/* Parameterized Constructor */

  Employee(String empName,String addr,int ag,double sal){
    employeeName = empName;
    address = addr;
    age = ag;
    salary = sal;
  }

/* Copy Constructor  */

  Employee(Employee emp){
    employeeName = emp.employeeName;
    address = emp.address;
    age = emp.age;
    salary = emp.salary;
  }

  void showDetails(){
    System.out.println("Employee's Name: "+employeeName);
    System.out.println("Employee's Address: "+address);
    System.out.println("Employee's Age: "+age);
    System.out.println("Employee's Salary: "+salary);
  }

}

class ConstructorDemo{
  public static void main(String args[]){
    System.out.println("Employee Details");
    System.out.println("----------------");
    Employee employee1 = new Employee();
    employee1.showDetails();

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

    String employeeName = "John";
    String address = "Los Angles";
    int age = 25;
    double salary = 34503.92;
    Employee employee2 = new Employee(employeeName,address,age,salary);
    employee2.showDetails();

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

    Employee employee3 = new Employee();
    employee3.showDetails();

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

    Employee employee4 = new Employee(employee2);
    employee4.showDetails();

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

    Employee employee5 = new Employee(employee3);
    employee5.showDetails();

  }
}

Output

copy_constructor

Explanation of the Java Code & Output

Please carefully observe the code marked in red, basically in the Employee class you will find the syntax how to declare copy constructor. We have created two more objects employee 4 and employee5 which are copy of employee2 and employee3 respectively. From the output it is clearly visible that instance variables of employee4 is having the same value as the values of instance variables of employee2. Same is true for employee5.

Next we will see how to use the keyword “static” in Java.

Checkout more useful tutorials and definitive guidelines on Java programming here.

by -

The access to classes, constructors, methods and fields are regulated using access modifiers i.e. a class can control what information or data can be accessible by other classes. To take advantage of encapsulation, you should minimize access whenever possible.

Java provides a number of access modifiers to help you set the level of access you want for classes as well as the fields, methods and constructors in your classes. A member has package or default accessibility when no accessibility modifier is specified.

Java Access Modifiers/Specifiers

  1. Public
  2. Default
  3. Protected
  4. Private

Public Access Specifiers

Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package (collection of classes, similar to header files will see later) or in another package.

Default Access Specifiers

Java provides a default specifier which is used when no access modifier is present. Any class, field, method or constructor that has no declared access modifier is accessible only by classes in the same package. The default modifier is not used for fields and methods within an interface.

Protected Access Specifiers

The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods and constructors declared protected in a superclass can be accessed only by subclasses in other packages. Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected member’s class.

Private Access Specifiers

The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods or constructors declared private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to make all fields private and provide public getter methods for them.

Below are the programs to demonstrate the use of public, private, protected and default access modifiers while accessing fields and methods. The outputs of each of these java files depict the Java access specifiers.

Program 1

class Employee{
  public String employeeName;
  String address;
  protected int age;
  private double salary;

  void setSalary(double sal){
    salary = sal;
  }
  private double getSalary(){
    return salary;
  }
  void showDetails(){
    System.out.println("Employee's Name: "+employeeName);
    System.out.println("Employee's Address: "+address);
    System.out.println("Employee's Age: "+age);
  }
}

class AccessSpecifierDemo{
  public static void main(String args[]){
    Employee employee = new Employee();
    employee.employeeName = "Ronaldo";
    employee.address = "Portugal";
    employee.age = 29;
    employee.salary = 65034.00;
  }
}

Program 2

class Employee{
  public String employeeName;
  String address;
  protected int age;
  private double salary;

  void setSalary(double sal){
    salary = sal;
  }
  private double getSalary(){
    return salary;
  }
  void showDetails(){
    System.out.println("Employee's Name: "+employeeName);
    System.out.println("Employee's Address: "+address);
    System.out.println("Employee's Age: "+age);
  }
}

class AccessSpecifierDemo1{
  public static void main(String args[]){
    Employee employee = new Employee();
    employee.employeeName = "Ronaldo";
    employee.address = "Portugal";
    employee.age = 29;
    //employee.salary = 65034.00;
    employee.setSalary(65304.00);
    System.out.println("Employee's salary: "+employee.getSalary());
  }
}

Program 3

class Employee{
  public String employeeName;
  String address;
  protected int age;
  private double salary;

  void setSalary(double sal){
    salary = sal;
  }
  private double getSalary(){
    return salary;
  }
  void showDetails(){
    System.out.println("Employee's Name: "+employeeName);
    System.out.println("Employee's Address: "+address);
    System.out.println("Employee's Age: "+age);
    System.out.println("Employee's Salary: "+salary); //1
    System.out.println("Employee's salary: "+getSalary()); //2
  }
}

class AccessSpecifierDemo2{
  public static void main(String args[]){
    Employee employee = new Employee();
    employee.employeeName = "Ronaldo";
    employee.address = "Portugal";
    employee.age = 29;
    //employee.salary = 65034.00;
    employee.setSalary(65304.00);
    //System.out.println("Employee's salary: "+employee.getSalary());
    employee.showDetails();
  }
}

Output

code for access_specifier in java

Explanation of the Java Code & Output

Please carefully observe the code carefully and the corresponding output of the same program. Now we will explain the program and their output. In all the programs we have declared one instance variable of each of the access specifier type.

Now if you see the first program, we have tried to initialize the private member salary of the employee class, it throws a compilation error saying salary has private access in Employee. That does mean private fields/variables cannot be accessed from outside of the class in which it is declared.

Now if you see the second program, we have defined a public method setSalary() to initialize private member variable salary. Here we will come across one more concept that private members can be accessed only in the class where it exists. But here we have defined a private method getSalary () to get the value of the salary. But also private methods of a class cannot be accessed from the outside of the class where it is defined. And we get the same compilation error getSalary() has private access in Employee. Hence, We are unable to get the value of salary printed outside of that class even though set by setSalary() method.

At last if you see the third program, we get the value of salary and all the values of other instance variables printed in the default method showDetails() which is defined in the Employee class.

We will see one more example on access specifier after completing discussion on inheritance and package.

by -

In our previous discussion on how to initialize instance variables in Java, we have came across constructor. Here we will discuss constructor in detail. First we will see what is constructor. It is very tedious to initialize all of the variables in a class each time an instance is created.

Even when you add convenience functions like initialize( ) [as we used in our previous examples], it would be simpler and more concise to have all of the setup done at the time the object is first created. Java allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of a constructor.

Constructor is a special type of method which has the same name as the class in which it resides and initializes the internal state of an object so that the code creating an instance will have a fully initialized, usable object immediately upon creation before the new operator completes and doesn’t have any return type because the implicit resource type of a class’ constructor is the class type itself.

Types of Constructors:

  1. Default Constructor.
  2. Parameterized Constructor.
  3. Copy Constructor. (Will discuss later)

Java Program

class Employee{
  String employeeName;
  String address;
  int age;
  double salary;

/*Default Constructor */

  Employee(){
    employeeName = "Platini";
    address = "France";
    age = 45;
    salary = 120500.92;
  }

/* Parameterized Constructor */

  Employee(String empName,String addr,int ag,double sal){
    employeeName = empName;
    address = addr;
    age = ag;
    salary = sal;
  }
  void showDetails(){
    System.out.println("Employee's Name: "+employeeName);
    System.out.println("Employee's Address: "+address);
    System.out.println("Employee's Age: "+age);
    System.out.println("Employee's Salary: "+salary);
  }
}
class ConstructorDemo{
  public static void main(String args[]){
    System.out.println("Employee Details");
    System.out.println("----------------");
    Employee employee1 = new Employee();
    employee1.showDetails();

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

    String employeeName = "John";
    String address = "Los Angles";
    int age = 25;
    double salary = 34503.92;
    Employee employee2 = new Employee(employeeName,address,age,salary);

    employee2.showDetails();

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

    Employee employee3 = new Employee();
    employee3.showDetails();
  }
}

Output

java constructor program

Explanation of the Java Code & Output

Employee() is a default constructor of Employee class in this code. It is called default because it doesn’t take any parameters. And when you do not explicitly define a constructor for a class, then Java creates a default constructor for the class. If you see the codes written in previous examples you will not find any constructors defined there, despite we were able to create object of those classes, this is because only for that reason.

Flash on:

The default constructor automatically initializes all instance variables to zero.

Here in this example, object employee1 and employee3 is initialized with default constructor Employee()of Employee class. Here we have created the default constructor Employee() for Employee class and we are initializing the objects with some user defined values. Then it will no longer be initialized with zero as it is not implicit default constructor created by java. This is only done when no constructor is defined by programmer for that class. The default constructor automatically initializes all instance variables to zero.

We have also written one parameterized constructor here. It takes parameters while object creation that’s why it is parameterized constructor. Employee object employee2 is initialized with parameterized constructor Employee (String empName, String addr, int ag, double sal).

Flash on:

Once you create your own parameterized constructor, then Java won’t create default constructor for that class. You have to explicitly create the default constructor for that class otherwise you will not be able to initialize objects using default constructor. It will throw a compile time error.

Here if we didn’t create Employee() default constructor and meanwhile if we have created Employee(String empName, String addr, int ag, double sal) constructor, we will not be able to create object using Employee() constructor. i.e.

Employee employee1 = new Employee();

Employee employee3 = new Employee();   both these statements will no longer be valid.

Now,  having removed Employee() default constructor if we compile then we will get this error during compile time.

java constructor program
Do let us know if you have any questions.

Next we will learn how to use copy constructors in Java.

Checkout more useful tutorials and definitive guidelines on Java programming here.

by -

Introduction

Since now you have learnt about creating objects of a Class in Java, we need to checkout how we can pass arguments while creating methods.

In call-by-value approach, the value of an argument is copied to the formal parameter of the subroutine. The changes made to the parameter of the subroutine have no effect on the argument.

In call-by-reference approach, a reference to an argument is passed to the formal parameter of the subroutine, inside the subroutine, the reference is used to access the actual argument specified in the call. This means that changes made to the parameter will affect the argument used to call the subroutine.

We will explain both of the ways of passing argument to a method in Java with these examples.

Program for Call By Value

class Employee{
  double salary;
  int age;
  void incrementSalAndAge(double sal, int a){
    salary = sal+10000;
    age = a+7;
    System.out.println("Salary on call: "+salary);
    System.out.println("Salary on call: "+age);
  }
}

class CallByValueDemo{
  public static void main(String args[]){
    Employee employee = new Employee();
    double salary = 34521.86;
    int age = 23;
    System.out.println("Salary before call: "+salary);
    System.out.println("Salary before call: "+age);
    employee.incrementSalAndAge(salary,age);
    System.out.println("Salary after call: "+salary);
    System.out.println("Salary after call: "+age);
  }
}

Output

call_by_value

Program for Call By Reference

class Employee{
  double salary;
  int age;
  void incrementSalAndAge(Employee emp){
    salary = emp.salary+10000;
    age = emp.age+7;
    System.out.println("Salary on call: "+emp.salary);
    System.out.println("Salary on call: "+emp.age);
  }
}

class CallByRefDemo{
  public static void main(String args[]){
    Employee employee = new Employee();
    employee.salary = 34512.37;
    employee.age = 23;
    System.out.println("Salary before call: "+employee.salary);
    System.out.println("Salary before call: "+employee.age);
    employee.incrementSalAndAge(employee);
    System.out.println("Salary after call: "+employee.salary);
    System.out.println("Salary after call: "+employee.age);
  }
}

Output

call_by_reference

Explanation of the Java Code & Output

If you see the first program, you will find we have written a method incrmentSalAndAge() where we are sending values of the arguments to the formal parameters of the same method. Before calling incrmentSalAndAge(), we have printed the values of the arguments which will be actually passed. Then we have updated the values of the arguments in incrmentSalAndAge() method and printed.

You can see there it will print the updated values of the formal parameters. After returing from subroutine, these updated values will no longer be in existence. And it will print the values of the arguments which was stored within the arguments before calling incrmentSalAndAge() . In conclusion we can say that changes made to the parameter of the subroutine have no effect on the argument.

Now, in the second program you will see instead of passing values stored in the arguments we have passed the reference of the object to incrmentSalAndAge() method.  Thus when you pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by the argument. From the output you can easily make that out. Before calling incrmentSalAndAge() we have printed values of the arguments.It has printed the values with which arguments are initialized.

During invocation of the method incrmentSalAndAge(), the method is supposed the update the values of the formal parameters and get the updated value printed. After coming back from the call it has printed the updated values for the arguments. Therefore, changes made to the parameter will affect the argument used to call the subroutine because both argument and formal parameter both are referring to the same object.

Remember, these concepts are very useful to understand Copy Constructors in Java.

Checkout more useful tutorials and definitive guidelines on Java programming here.

by -

PHP has the ability to upload files on to the server using $_FILES superglobal.  $_FILES works a little differently from $_POST and $_GET in that each file creates an array of related elements that provide information about the uploaded file.

The provided information includes:

  • name: The file name
  • type: The file type (e.g. image/jpeg)
  • tmp_name: The temporary location of the uploaded file
  • error: An error code corresponding to error type (0 if no errors found)
  • size: The file size in bytes (e.g. 15454)

$_FILES , basically is a multidimensional  array, by using the global PHP $_FILES array you can upload files from a client computer to the remote server. The first parameter is the form’s input name and the second index can be either “name”, “type”, “size”, “tmp_name” or “error”.

Here are the array field values to handle uploads. Remember the first value [“file”] is user desired it can be anything user wants to refer.

$_FILES["file"]["name"] – the name of the uploaded file

$_FILES["file"]["type"] – the type of the uploaded file

$_FILES["file"]["size"] – the size in bytes of the uploaded file

$_FILES["file"]["tmp_name"] – the name of the temporary copy of the file stored on the server

$_FILES["file"]["error"] – the error code resulting from the file upload

I am going to use all these above in the example where you could understand their use. Also note that, for security purpose, it is better to restrict user uploads. Allowing all type of uploads might turn out a security pitfall.

In the example iam going to use two scripts basically the first one as a HTML file that will be a form interface to select the desired photo to upload and the second as a PHP script that will do all the processing for a file upload. All the files uploaded will be saved permanently on to “upload‘  folder, so you need to create this folder before you execute the script.

HTML page to select the files to upload.

<html>
<body>
<form action="phpupload.php" method="post"
enctype="multipart/form-data">
<label for="photo">User Photo:</label>
<input type="file" name="file" />
<input type="submit" value="Upload a Photo" />
</form>
<body>
</html>

Save the below code as (phpupload.php)

<html>
<body>
<?php
// check whether upload button is pressed

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
// all the superglobals to store file information and to verify a valid upload.
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000000))
  {
// check for any error
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
// display the file information
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

// Display the image

$file=$_FILES["file"]["name"];
echo '<img src="upload/'.$file.' " height = 150 width = 150/>';
echo"<br/>";

// check for already existing files

if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
// saving the uploaded file permanently to the "upload" folder
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else

  {
  echo "file is incompatible, Plz try another image ";
  }
}

else
{
echo "Choose image first";
}
?>

</body>
</html>

Example:  Here I choose a JPEG image from my PC and then click the “upload” button.

As you can see image has been uploaded with all the details and a small preview as well.

The image has been successfully uploaded on to the folder “upload” which I have set in my PHP script.

Here is the complete review of all the work this PHP code can do:

  1. Keeping in mind all the needs, the PHP file upload script displays all the file(photo) details along with the picture that is being uploaded.
  2.  Allows you to upload images of gif, jpeg and jpg format. You can allow more number of files to be uploaded just by adding further file types in the $_FILES superglobal.
  3. If you try to upload nothing (just click the upload button without selecting any of the file) , you get a warning message.
  4. If you try to upload a text, pdf, .PNG file you get a error message saying “ File not compatible”;
  5. The PHP upload script also displays a small picture of the photo you just uploaded.
  6. Finally you are not allowed to upload same image twice

Also check out:

PHP Tutorial 1: Introduction for Beginners
PHP Tutorial 2: PHP Script Syntax and HTML File Compatibility
PHP Tutorial 3: Variables in PHP
PHP Tutorial 4: Control Statements
PHP Tutorial 5: Functions
PHP Tutorial 6: Form Processing
PHP Tutorial 7: $_POST and $_GET Functions
PHP Tutorial 8: Connecting PHP script to MySQL
PHP Tutorial 9: PHP insert statement
PHP Tutorial 10 : PHP Session

by -

Instance Variables

In our previous discussion we have discussed what is instance variable or member variable. Instance variables are the variables which is declared under a class. Now we will see how to initialize those variables of a class within the same class or even from another class.

We can accomplish the same in three ways:

1. By Object Reference

EmployeeDemo1.java

class Employee{
    String employeeName;
    String address;
    int age;
    double salary;
    void showDetails(){
        System.out.println("Employee's Name: "+employeeName);
        System.out.println("Employee's Address: "+address);
        System.out.println("Employee's Age: "+age);
        System.out.println("Employee's Salary: "+salary);
    }
}

class EmployeeDemo1{
    public static void main(String args[]){
        Employee employee = new Employee();
        employee.employeeName = "John";
        employee.address = "Los Angles";
        employee.age = 25;
        employee.salary = 34503.92;
        employee.showDetails();
    }
}

2. By Method Within The Same Class

EmployeeDemo2.java

class Employee{
    String employeeName;
    String address;
    int age;
    double salary;
    void initialize(String empName,String addr,int ag,double sal){
        employeeName = empName;
        address = addr;
        age = ag;
        salary = sal;
    }
    void showDetails(){
        System.out.println("Employee's Name: "+employeeName);
        System.out.println("Employee's Address: "+address);
        System.out.println("Employee's Age: "+age);
        System.out.println("Employee's Salary: "+salary);
    }
}

class EmployeeDemo2{
    public static void main(String args[]){
        Employee employee = new Employee();
        String employeeName = "John";
        String address = "Los Angles";
        int age = 25;
        double salary = 34503.92;
        employee.initialize(employeeName,address,age,salary);
        employee.showDetails();
    }
}

3. By Constructor

EmployeeDemo3.java

class Employee{
    String employeeName;
    String address;
    int age;
    double salary;
    Employee(String empName,String addr,int ag,double sal){
        employeeName = empName;
        address = addr;
        age = ag;
        salary = sal;
    }
    void showDetails(){
        System.out.println("Employee's Name: "+employeeName);
        System.out.println("Employee's Address: "+address);
        System.out.println("Employee's Age: "+age);
        System.out.println("Employee's Salary: "+salary);
    }
}

class EmployeeDemo3{
    public static void main(String args[]){
        String employeeName = "John";
        String address = "Los Angles";
        int age = 25;
        double salary = 34503.92;
        Employee employee = new Employee(employeeName,address,age,salary);
        employee.showDetails();
    }
}

We will learn more about Java Constructors in our next tutorial.

Output

java instance variable output

Explanation of the Java Code & Outputs

In the first case we have created one object employee of Employee class. After that we have initialized instance variables using the same object.

In the second case we have written a method initialize () within Employee class. Having created object of Employee class we called that method to initialize the instance variables.

In the third case we have created one constructor which takes parameters to initialize the instance variables.

We will discuss about constructors in Java in our next discussion.

Checkout more useful tutorials and definitive guidelines on Java programming here.

by -

Sometimes you may want to pass information into a program during runtime. This can be done by passing command line argument to main() method. Command line argument is nothing but the information that directly follows the program’s name on the command line when the program is executed. This information is stored as String array passed to main(). This command line argument can easily be accessed within the java program. We will see two examples to get how it works. Since now you have well understood how to create objects Java programs, you can run these programs quite easily.

Program 1

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

Output

java command line argument

Explanation of the Java Code & Outputs

Please closely observe all the different types of execution of the same java program.

Case 1:

See during first time execution we have passed information “World” as command line argument immediately after the java program name “CommandLineDemo”, which will be passed to main() method as String(in Java String is a predefined class, will discuss later) i.e. this “World” String will be stored in args[] String array at its 0’th position.

Now come to the program, see the print statement, first we will print “Hello ” to the console then very first argument passed through command line will get printed followed by three exclamation symbols. In java using “+” strings are concatenated. Moreover we put Strings within double quotes(” ”).

Case 2:

See during second time of execution of the same program we didn’t pass any information to main() method through command line, it has thrown an exception(Unexpected error during execution of the java program) as args[] String array doesn’t have any String within it, despite we want to print the String at its 0’th position.

Case 3:

See during third time of execution of the same program we have passed more than one argument “My World” to main() method through command line, i.e. two arguments will be stored in the String array args[] at its 0’th and 1’st position of args[], as we want to print the String present at its 0’th position not the String of any other positions we will get the output as shown in the screen “Hello My!!!

Program 2

class CommandLineDemo2{
    public static void main(String args[]){
        int argsLength = args.length;
        if(argsLength >0){
            for(int argsCount = 0;argsCount<=(argsLength-1);argsCount++){
                System.out.println("args["+argsCount+"] :"+args[argsCount]);
            }
        }
        else{
            System.out.println("No arguments passed");
        }
    }
}

Output

java command line argument

Explanation

In the code, first we have measured the length of the String array based on the number of arguments passed to main() method through command line. Now if we don’t pass any argument to main() then the length of the String array args[] will be 0, definitely it will execute the statement in the else part “No arguments passed”.

Now, during second time execution of the same program we have passed some information “Sun rises in the east” .Each of the space separated word will be stored in the String array args[] starting from 0’th up to the position (Number of Words -1)’th position. This String array args[] with 5 Strings is passed to main() method. Therefore the length of the args[] String array will be 5.By iterating from 0 to 4 we have printed all the strings stored in args[] String array from 0’th to 4’th position.

Next we will learn about Java instance variables.

Checkout more useful tutorials and definitive guidelines on Java programming here.