Archive for category Java

Java Tutorial 13 – Visibility and Scope

Visibility is how accessible methods and variables to other class is. We’ve used methods from other class in tutorial Multiple Class. Which was possible because all the method we used from other class was public. There are mainly three types of access specifier.

  1. Public
    Every Public variable and method is accessible to all other class.
  2. Protected
    Protected elements are inheritable, means each child class has all the protected method that parent has and it only accessible between all it’s inheritance tree.
  3. Private
    Private elements are accessible only for class itself.

Lets have a cup of Example:

we will create 2 class parent class will have 1 public, 1 protected and 1 private int, and we will try to access these ints in its child class.

Parent:

public class Parent {
    static public int a;
    static protected int b;
    static private int c;
}
Child:
public class Child extends Parent {
    public static void main(String[] args) {
        a = 0;
        b = 0;
        c = 0;  // this line give you error
    }
}
We do not need to run it, just type it and when you mansion c=0 it will give you error because child can not inherit private elements from parent and so Child class doesn’t know the int c exist.
Scope:
Scope means where the method or variable is accessible in the same class.
for example if u define an int inside a for loop, this int is not accessible out side the for loop and Same thing is true for any method also.
if you have any variable inside a method than its only accessible inside it.
In short we can say elements are accessible between {…} inside which they are declared.
So, if you declare variable or method inside class ( outside other methods ) it’s accessible between {..} of class means inside whole class and so it’s called Global declaration.
Some Examples:
1) Global declaration
public class yash{
int a;           // accessible inside all methods of class
int b;           // accessible inside all methods of class
method1()
…..
…..
method10()
}
2) inside Method which is not accessible to other method
public class yash{
method1(){
int a;           // accessible only for method1
int b;           // accessible only for method1
}
…..
…..
method10()
}
I hope you cleared if not merriment declaring and using variables different places in class.
Doubts are invited.
have a nice day.
Peace.

, , , ,

Leave a comment

Java Tutorial 12 – Constructors

constructors are a special type of method which we can use to initialize Objects when we create it. If u do not use constructor, objects contains all the variables and methods, But Using constructor you can initialize values of variables. For example you can initialize some variables to zero or Strings to default values and etc. Lets Clear this with an example. Create two classes Tom and Jerry.

Tom:

public class Tom {

public static void main(String[] args){
Jerry object = new Jerry();
object.print();
}
}

Jerry:

public class Jerry {
int a;
String b;

public void print(){
System.out.println(“int a = “+a);
System.out.println(“String b = “+b);
}
}

Now if u run the Tom.java you will see the output like:

int a = 0
String b = null

Now if you want to initialize String b to some text say “Hi” and int a to value 5 whenever the new object is created, you can do it by creating constructor. There are some rules for it:

  • Name of the constructor must be same as name of class.
  • there is no other rule 😛

Now lets create constructor for Jerry class and initialize variables.

Jerry:

public class Jerry {
int a;
String b;

Jerry(){
a=5;
b = “Hi”;
}
public void print(){
System.out.println(“int a = “+a);
System.out.println(“String b = “+b);
}
}

 

!!!!! yap writing return type and access modifiers is optional. We can define Constructor by just Jerry(){ … }.

Now if you run the Tom.java you will see the output like:

int a = 5
String b = Hi

Here constructor initialized both variables when we created an object of Jerry.

catch you again later…

doubts are invited.

have a nice day.

Peace.

, , , , , ,

Leave a comment

Java Tutorial 11 – Inheritance

inheritance means Inheritance ! (hehe you know that )

i mean consider two classes one is parent and second is child class and if you inherits child from parent class that child class can access all the variables and methods which are public in parent.

Let we have 2 classes Car and TataNano:

Car:

public class Car {
    public void breaks(){
    // breaks the car
}
    public void Speedup(){
        // speed up the car
    }
    public void indicator(){
        // indicator operation
    }
}
Now we have a model car which has functions like break speedup and indicator.
now consider for a while that you are making a Racing game and that has lots of different cars, but this break and indicators will be common in each of the cars. So you have to define all this three methods in each car.
Instead what u can do is throw common methods in one class called car and all the different cars will be inherited from it so all the cars automatically has all the three methods.
In short in this example Car is parent and specific car like Tata, Nissan, etc are childs and so it contains all the public methods of car.
How to inherit? :
if you want to inherit Tata from Car all you have to say is:
public class Tata extends Car {}
now you can directly call all three method of Car inside Tata class without creating object of Car.
Again doubts are invited.
have a good1, Peace.

, ,

1 Comment

Java Tutorial 10 – Enhanced For Loops

enhanced for loops are very useful for arrays.

to loop through array what we generally do is we take one int as index and use this index inside loop to point to array location and then we increment it.

But there is one more easiest way to loop through array which is called Enhanced For Loop. it automatically increments index and stops at the end of the array. let me show you one example:

For loop:

public class fruit {
    public static void main(String[] args) {
        String fruift[] = {“apple”, “banana”, “grapes”};
        int i;
        for (i = 0; i < 3; i++) {
            System.out.println(fruift[i]);
        }
    }
}
Enhanced For Loop:
public class fruit {
    public static void main(String[] args) {
        String fruift[] = {“apple”, “banana”, “grapes”};
        for (String i : fruift) {
            System.out.println(i);
        }
    }
}
You can see the difference between lines of code.
it is pretty much easy to use each element of array and loop through it.
Syntax:
for( <type of array> <variable> : <array name> )
for example u have array of int and you want to loop through each 1 then u have to write.
for( int x : numbers ){
….things to do….
}
here “numbers” is array of ints. int x holds the value of array elements.
Example.
int num[] = { 4, 34, 12, 7, 56, 89}
for( int x : num){
}
when first time it loops x holds value “4”.
then in second loop value of x will be “34” and so on…
It’s very useful to loop through all elements of array.
So, it’s all about enhanced for loop.
Have a nice day, Peace.

, , , , ,

Leave a comment

Java Tutorial – 9 Method Overloading ( function Overloading )

Overloading is nothing but defining different behavior ( functionality ) for same function.

for example u can create add method which will add two ints, three ints, two doubles, three doubles.

it is not possible to define one method again and again with same name but u can do it by changing arguments.

example:

add(int x) { return x++; }

add(int x, int y) { return x+y; }

add(double x, int y) { return ((int)y + x); }

  1. if u call the method with 1 int it will call the first add method and return incremented value
    Example.
    int ans =add(3);
  2. if u call the method with 2 ints it will return addition of them
    Example.
    int ans =add( 3, 4 );
  3. and with 1 double and 1 int i will return again the sum.
    Example.
    int ans =add( 3.5, 4 );

This was simple example but we can also overload as many times u want, it will provide very flexibility to the software.

as always doubts invited.
have a nice 1, Peace.

, , ,

Leave a comment

Java Tutorial 8 – Passing objects as argument

first create 1 new class (i have named it Class3 for make it simple to understand)

and add the code to all thre classes as follows

(after copy and pasting press Alt+Shift+f  and it will formate everything…)

Class1:

public class Class1 {

public static void main(String[] args) {

//created two objects

Class3 c3ob = new Class3();
Class2 c2ob = new Class2();

//passing object of Class3 to method of Class2

c2ob.basket(c3ob);

}

}

Class2:

public class Class2 {
int i;
public void basket(Class3 receivedfriut){
for(i=0;i<3;i++)
System.out.println(receivedfriut.fruit[i]);
}

}

Class3:

public class Class3 {
String fruit[] ={ “apple”, “banana”, “grapes” };

}

  1. we created two objects of class2 and class3
  2. we passed and object of class3 as arguiment of method of class 2
  3. we defined basket method in class2 which takes object of Class3 and save it in receivedfruit
  4. we used receivedfruit object and printed the String array.

This is useful when you are dealing with lots of int,doubles and etc. You can make a different class for it and use it in other Classes and methods by passing objects.

inough bla bla bla, Doubts are invited,

Have a nice day, Peace.

, , , ,

1 Comment

Java Tutorial 7 – passing arguments and returning values

Passing arguments between methods is very easy.

lets use class1 and class2 that we created before.

and change class1 to :

public class class1 {
public static void main(String[] args) {

Class2 c2object= new Class2();
c2object.boy(“Yash”);
c2object.girl(“sweety”);
}

}

and Class2 :

public class Class2 {

public void girl(String name){
System.out.println(name + ” is present”);
}

public void boy(String name){
System.out.println(name + ” is present”);
}
}

Here we have changed

public void boy()

to

public void boy(String name)

so now every time we call boy method it takes a string, see we have passed a string in boy(“Yash”) in class 1.

  1. boy(“yash”) passes a string to boy function.
  2. this string is cached into the String name in class 2.
  3. then we used name to print a line.

You can also pass int, double etc. but when you pass an int you must define other int in definition of method to catch that int.

for example:

public static void main(String[] args){

add(12,13);

public static void add(int x, int y){

System.out.println(x+y);

}

}

we have passed two arguments and cached it in int x and y and used it to display sum.

Returning values:

to return value just add one line at bottom of method called “return (variable)

in above example we can return the sum like this way:

public static void main(String[] args){

int ans;

ans = add( 12, 13 );

System.out.println(ans);

public static int add(int x, int y){

return (x+y);

}

}

what we have done here is , we simply get 2 int in method and returned the addition of them.

now notice that we have changed public static void add(int x, int y) to public static int add(int x, int y)

it is because now our method returns an int.

same way if your method returns double or String method would be public static double add(int x, int y)

and in class 1 we written ans = add( 12, 13 ) here ans is the variable which will store the returned value.

same way if you returns a String you must have String variable to store it instead of int ans.

In next tutorial we will learn how to pass Objects between methods.

, , , , ,

Leave a comment

Java Tutorial 6 – Multiple class methods

If u want to make more complex and big application You should divide your whole code into different classes.

for example if you are creating a Calculator you can have a class that holds main method and another class which contains all operations like add, sub, multiply etc. and when dealing with GUI you can also have one more class for defining all the GUI elements like buttons, Textfields etc.

(maan plz stop talking…)

  1. Create 2 classes whatever you want.
  2. create main method in one class.
  3. create methods that you want to use in other class.

Like this way

Class1:

Class 2:

  • We have created 2 classes one has methods and other will use it.
  • class 1 has main method that will be run first and class 2 has methods that we will use in class 1
  • class 2 has 2 methods boy() and girl()
  • Now to access method of class2 we created object of class2 in class 1 that is c2object.
  • now only we have to do is to refer method of class 2 bye calling object.method() means if u want to use girl() then c2object.girl().
  • you can name object anything you want.
  • if you have an int in class2, you can also use it by referring c2object.intname

Practice more and implement different logic to improve you speed and accuracy.

Have a nice day, Peace.

, , , , ,

1 Comment

Java Tutorial 5 – Creating methods

We have used system defined methods like println() and nextInt(), Now let’s create our own method and use it.

Defining method is very useful when bunch of code is getting repeated,  just put that code in a method and just call that method instead of writing all the code again

create a class and add this code as always we do.

  1. Why int and Scanner before main method? 

    if we create int inside the main method, then, only main method can use or change that int. so defining anything in the class and outside any method is called Global declaration.

  2. Why Static?
    to use that int into the main or any other method because main itself is static so any variable used within it must be static and thats why we also crated all the methods static.

We created 3 methods and it can be defined anywhere in the class.Observe the out put and you will dig out everything.

u can create different methods of adding subtracting etc. and create  calc.

Doubts invited,

Have a nice day, Peace.

, , , , , , ,

Leave a comment

Java Tutorial 4 – Looping

I think you guys can do following:

  1. create new class
  2. now add following lines in main method

no need to import anything because we are not using scanner here.

Syntax:

while ( condition ) {

 ….to do …

}

it will first check the condition and if condition is true it run the code within the {} and again check the condition, this will continue till condition will not become false. Once it become false loop is ended.

we created here an int i and printed 1 line each time it loops.

and If u know C/C++ its going to boring for you ! because its same.

Again Doubts and suggestions  are invited.

Peace.

, , , , , ,

Leave a comment

Design a site like this with WordPress.com
Get started