JAVATECH NEWS

Java

CORE JAVA

Interview

OFF-CAMPUS

Showing posts with label CORE JAVA. Show all posts
Showing posts with label CORE JAVA. Show all posts

Thursday, 25 December 2014

Inheritance in Java


1. What is inheritance?

Ans-Deriving new class(child class) from existing class(base class or parent class) such that new class acquire all the features of parent class/base class is called Inheritance. Java uses “extend” keyword for acquiring the features of parent class to child class.

public class Parent
{
String fathername="Chandan";
int fatherage=50;
}
class Child extends Parent
{
String name="Raju";
void display()
{
System.out.println("My name is "+name+" My fathername is "+ fathername);
System.out.println("My father's age is "+fatherage);
}
}
class Show
{
public static void main(String args[])
{
Child c=new Child();
c.display();
}
}

2. What are the types of inheritance.?


Ans:There are 5 types of inheritance.

1. Single Inheritance.

2. Multilevel Inheritance

3. Hierarchical Inheritance

4.Hybrid Inheritance.

5. Multiple Inheritance.

3.What is single inheritance?

Ans: If One class is extended by only one class,then it is called single inheritance.
Example of single inheritance
class One
{
void methodOne()
{
System.out.println("This is Parent class method");
}
}

class Two extends One
{
void methodTwo()
{
System.out.print("This is Child class method ");
}
public static void main(String args[])
{
Two t=new Two();
t. methodOne();
t.methodTwo();
}
}
O/P:
This is Parent class method
This is Child class method.

4.What is multi level inheritance?

Ans:If a class(here Two) inherit from a base class(here class One),and another class(here class Three) is derived from this derived class(class Two) then it is called Multi level inheritance.
Example of Multi level inheritance.
class One
{
void methodOne()
{
System.out.println("This is method of class One");
}
}

class Two extends One
{
void methodTwo()
{
System.out.println("This is method of class Two ");
}
}
class Three extends Two
{
void methodThree()
{
System.out.println("This is method of class Three");
}

public static void main(String args[])
{
Three t=new Three();
t. methodOne();
t.methodTwo();
t.methodThree();
}
}

O/P:
This is method of class One
This is method of class Two
This is method of class Three.

5.what is Hierarchical Inheritance?

Ans:if One class is extended by many classes.then it is called Hierarchical Inheritance.

6.what is Hybrid Inheritance ?

Ans: Hybrid inheritance is a combination of Single and Multipleinheritance.

7. What is Multiple inheritance and does java support multiple inheritance?

Ans) If a child class acquire the property from multiple classes then it is known as multiple inheritance. Java does not allow to extend multiple classes(multiple inheritance) To overcome this problem java introduces  Interfaces.

8. Why java doesn't support multiple Inheritance ?

Ans-Multiple inheritance leads to ambiguity and confusion in java so java does not support the  multiple Inheritance.
class One
{
void methodOne
{
System.out.print("In class One");
}
}

class Two
{
void methodOne
{
System.out.print("In class B");
}
}

class C extends A,B(if multiple inheritance supported)
//Now which method will be consider in class C from the above Two class A and B,so it leads to ambiguity and confusion. That’s why java doesn't support multiple Inheritance

9.Can a class extend itself.?


Ans-No.

10. How to implement multiple inheritance in java?


Ans:We can implement multiple inheritance through “interfaces” in java,In Java a class can not extend more than one classes, but a class can implement more than one interfaces.
Example:
interface Stallion // Adult Male horse
{
Float HT=6.8f;
void height();
}

interface Dam //Adult Female horse
{
Float HT=5.2f;
void height();
}

class Colt implements Stallion,Dam  // Colt Young male horse
{
public void height()
{
float ht=(Colt.HT+Filly.HT)/2;
System.out.print("Height of Colt is :"+ht);
}
}
class MultipleInheritance
{
public static void main(String args[])
{
Colt ch=new Colt ();
ch.height();
}
}
O/P: Height of Colt is :6.0

To know more about interface Please click here







Read more ...

Wednesday, 26 November 2014

For-each loop (Advanced For loop)


For each loop generally used to handle the elements of  collection.Collection is a group of elements. Eg Arrays and java.utli classes(Stack,LinkedList,Vector etc).
For each loop repeatedly executes statements for each of the elements in the collection.

Syntax of for-each loop:

for(datatype variable:collection)
{
Statements;
}

Example of "for each loop" using array:

Program1:


class ForEachLoop1
{
public static void main(String args[])
{
int arr[]={13,20,30,40};
for(int i:arr)
{
System.out.println(i);
}
}
}

O/P:

13
20
30
40

Example of "for-each loop" using Linked List:

Program2:


import java.util.*;
class ForEachLoop2
{
public static void main(String args[])
{
LinkedList<String> list=new LinkedList<String>();
list.add("Raju");
list.add("Hiten");
list.add("Kiran");
for(String s:list)
{
System.out.println(s);
}
}
}

O/P:

Raju
Hiten
Kiran

Read more ...

Saturday, 15 November 2014

Example of String class methods.



Example of String class methods are-

Here we will explain all the String Class methods with example,in this post you will be able to learn the various String class method with their examples,examples are explained in easy manner to understand easily,String class methods consist 14 methods like length(),charAt(int i),compareTo(String s),compareToIgnoreCase(String s),boolean equals(String s),boolean equalsIgnoreCase(String s),int indexOf(String s),String replace(char c1,char c2),String substring(int i),String substring(int i1,int i2),String toLowerCase(),String toUpperCase(),String trim() etc in this post.Now lets see all the methods one by one.

1.int length():This method is used to find the length or number of character in a string,
Eg:

class Example
{
public static void main(String args[])
{
String s1="My name is Rahim";
System.out.println("Length of String is :"+s1.length());
}
}
O/P:
Length of String is :16

2.char charAt(int i):This method is used to get the character at specific location.

class StringExample
{
public static void main(String args[])
{
String s="i am Rahim";
char ch=s.charAt(6);
System.out.print(ch);
}
}
O/P:
a

3.int compareTo(String s):This method is used to compare two strings and find which string is bigger and smaller,its return type is int.If  both string are equal then it returns 0(zero),If the argument string is greater than this string it returns positive integer, If the argument string is smaller  than this string it returns negative integer.Here is an example:

public class StringComparision
{
       
 
      public static void main(String[] args)
      {
   
      String s1="My name is Raju";
      String s2="My name is Raju";
      String s3="I am from Mumbai India";
            int  x=s1.compareTo(s2);
            System.out.println(x);

            int y=s2.compareTo(s3);
            System.out.println(y);

           int z=s3.compareTo(s2);
            System.out.print(z);
         
    }

}
O/P:
0
4
-4

4.int compareToIgnoreCase(String s): This method is same as previous method but it does not take the case of string in consideration.


5.boolean equals(String s): This method is used to find the strings are same or different by considering the case of string, it  returns true if strings are same, otherwise false.Eg:

public class StringComparision1
{
       
 
      public static void main(String[] args)
      {
   
      String s1="My name is Raju";
      String s2="My name is Raju";
      String s3="MY NAME IS RAJU";
            boolean  x=s1.equals(s2);
            System.out.println(x);

            boolean y=s2.equals(s3);
            System.out.println(y);

             }

}
O/P:
true
false


 7. boolean equalsIgnoreCase(String s):Same as previous method but it does not take case of strings into consideration.


8.int indexOf(String s): it will return the value of substring in main string, if substring is not found then it will return some negative value. .Eg:


class IndexOf
{
public static void main(String args[])
{
String s1="I like Java Programming";
String s2="Java";
int x=s1.indexOf(s2);
System.out.print(x);
}
}
O/P:
7

9.String replace(char c1,char c2) :it replaces the characters c1 with new character c2 in String
Eg:


class Replace
{
public static void main(String args[])
{
String s1="Malayalam";
String x=s1.replace('a','e');
System.out.print(x);
}
}
O/P:
Meleyelem

10.String substring(int i):this method extracts sub string from main string.
Ex:


class SubString
{
public static void main(String args[])
{
String s="I am from India";
String result=s.substring(5);
System.out.println(result);
}
}
O/P:
from India

11.String substring(int i1,int i2): returns a new string consisting of all character starting from i1 to i2(excluding character i2).

Ex:

class SubString
{
public static void main(String args[])
{
String s="I am from India";
String result=s.substring(5,9);
System.out.println(result);
}
}
O/P:
from

12.String toLowerCase(): returns the string after converting all character to lowercase.

Ex:
class ToLowerCase
{
public static void main(String args[])
{
String s="I LIKE JAVA";
String result=s.toLowerCase();
System.out.print(result);
}
}
O/P:
i like java

13.String toUpperCase():returns the string after converting all character to uppercase.

Ex:
class ToUpperCase
{
public static void main(String args[])
{
String s="i like java";
String result=s.toUpperCase();
System.out.print(result);
}
}
O/P:
I LIKE JAVA

14.String trim(): to remove the unnecessary space from the beginning and end of the string.

class Trim
{
public static void main(String args[])
{
String s=" Hi ";
String result=s.trim();
System.out.print(result);
}
}
O/P:
Hi

Read more ...

Thursday, 13 November 2014

String in Java


C/C+ treats string as an array of  character, But in Java string is an object of String class, String is a class as well as data type in Java, Here Example of String data type is: String s=”Indian”,Here ‘s’ is a variable of data type ‘String’.
In Java we can create a string in 3 different process.
In first process JVM creates an object and stores the string to that object,Object is referenced by s1 variable in this example.Eg: String s1="My name is Arun";
Second process is we create a String class object by allocating some memory using new operator and stores the string in the object.Eg: String s2=new String("I am from India");
Last one  is we create an array of character type and we pass the array to string object created. Eg: char arr[]={'i',' ','l','i','k','e',' ','j','a','v','a'}; //array of type String with characters
String s3=new String(arr);  //passing the arr to string object.
Example of creation of string in Java:

class CreateString
{
public static void main(String args[])
{
String s1="My name is Arun";
String s2=new String("I am from India");
char arr[]={'i',' ','l','i','k','e',' ','j','a','v','a'};
String s3=new String(arr);

System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}

O/P:
My name is Arun
I am from India

i like java

N.B:Java is enriched with various String class(in java.lang package) methods.We will discuss those String class methods with example in next post.

If you like this post please read 14 String Class methods with Example also.

Read more ...

Wednesday, 12 November 2014

this Keyword


"this" refers to present class members(instance variable,method,Constructor).local variable are accessible only in that particular method,Constructor where it is declared. if the name of instance variable and local variable are same, by default it will call the local variable  not the instance variable ,so how to refer the instance variable ,for this purpose “this” keyword is used. Here is an
Example of "this" for referencing instance variable,member and constructor of the present class :

class Present
{
int x; //instance variable
Present() //default constructor
{
this(10); //calls the parameterized constructor and passes the value 10
this.presentMethod();
}
//Local variable x gets 10 and it is stored in instance variable x
Present(int x)
{
//initializing value of local variable(x) to instance variable(this.x)
this.x=x;
}
void presentMethod()
{
System.out.print("Value of x is : "+x);
}
}

class This
{
public static void main(String args[])
{
Present p=new Present();
}
}

Read more ...

Monday, 10 November 2014

Instance variable and static variable affect

Java programming language defines following 3 kinds of variables.
1.Instance variable
2.Static variable
3.Local variable.
Here we will discuss about the Instance variable and Static Variable and their effects.

Instance Variable:

a.Non-static variable are called instance variable.
b.Instance variable are the variable which are used inside a class but outside any methods,constructor or any block.
c.Individual states of object is stored in Instance variable or "non-static field".(we will see the effect in the following example).

Static variable:

a.Static variables are also known as class level variable declared in a class, but outside a method, constructor or a block.
b.Class variable or static variables are declared with "static" modifier.
c.Static variables can be accessed by calling with the class name . ClassName.VariableName.

Local Variable:

a.Local variables are declared in methods, constructors, or blocks.
b.Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block.
c.Local variables are visible only within the declared method, constructor or block.

Now lets see the examples to understand the effect of Instance variable and Static variable on object.
A separate copy of instance variable is available to all objects,but a single copy of static variable in memory is available for all objects,so if we change the values of instance variable in one object it does not effect other instance variable in another object,but in case of static variable it affects to all other objects too.Here is example:

Example 1:


class InstanceVariableEffect
{
int x=12; //instance variable
void show()
{
System.out.println("Value of x is : "+x);
}
}

class InstanceVariableEffectDemo
{
public static void main(String args[])
{
InstanceVariableEffect ive1=new InstanceVariableEffect();
InstanceVariableEffect ive2=new InstanceVariableEffect();
++ive1.x;
ive1.show();
ive2.show();
}
}*/
O/P:
Value of x is :13
Value of x is :12
................................................................................................................................................

Example 2:

class StaticVariableEffect
{
static int x=12; //static variable
void show()
{
System.out.println("Value of x is : "+x);
}
}

class StaticVariableEffectDemo
{
public static void main(String args[])
{
StaticVariableEffect sve1=new StaticVariableEffect();
StaticVariableEffect sve2=new StaticVariableEffect();
++sve1.x;
 sve1.show();
 sve2.show();
}
}
O/P:
Value of x is :13
Value of x is :13

Read more ...

can a static method access the non static variable in java?


In this post we will see that access preference of non-static variable by static method.A non-static variable will not allow to be accessed by the static method.For this we have to declare the variable as static by using "static" keyword.

Know more about static variable and non-static variable 

Know more about Static variable and Static methods.

Q.can a static method access the non static variable?
Answer : No.here is an example:
it will show non-static variable x can not be referenced from a static context,if we declare num as static (eg:static int num=10) then it will show the result Value of num is 10.

class Sample
{
  int num=10; //instancre variable
static void test()
{
System.out.print("Value of num is : "+num);
}
}

class StaticDemo
{
public static void main(String args[])
{
Sample.test();
}
}

Read more ...

Static variable and static methods in Java


Static Variable :
Static variable is also called class variable,a single copy of static or class variable is shared by all object in memory.Static variables are stored in method area.

Static method:static method are the method which does not work on instance variable because JVM gives static method higher preference and then create the object since objects are not present at the time of calling the static method so instance variables are not available to act on them ,static method is declared by static keyword,and these are called by Classname.methodname()
Here is an example:

class Static 
{
static double sum(double x,double y) //method should be declared as static
{
double result=x+y;
return result;
}
}

class StaticExample
{
public static void main(String args[])
{
double z=Static.sum(10.5,15.5); //Calling the static method by Classname.methodname()
System.out.print("Answer is : "+z);
}
}

Read more ...

Sunday, 9 November 2014

Example of with parameter and with return type Method


Prgm:This program will show method with parameter and with return type.here method takes two parameter and this method has a return type that's double.check the program here.

class MulOfNumber
{
//return type is double and method taking two double type parameter
double mul(double x,double y)
{
double result=x*y;
return result; //return result
}
}

class MethodExample
{
public static void main(String args[])
{
MulOfNumber sn=new MulOfNumber();
double z=sn.mul(5.2,2.5);
System.out.print("Result is : "+z);
}
}
O/P:Result is : 13.0

Example of Method without any parameter and without return type:


class Calculate
{
int num1,num2;
Calculate(int x,int y)
{
num1=x;
num2=y;
}

void sum()
{
int res=num1+num2;
System.out.println("Result is : "+res);
}
}

class methodWithoutParameter
{
public static void main(String args[])
{ 
Calculate c=new Calculate(21,44);
c.sum();
}
}
O/P:
Result is : 65
Read more ...

Example of Calling Super class parameterized constructor from Sub class.


Program:Here is the Example of Calling Super class parametrized constructor from Sub class.

class Super
{
int i;
Super(int i)
{
this.i=i;
}
}

class Sub extends Super
{
int i;
Sub(int a,int b)
{
super(a);  //call super class constructor and pass a
i=b;
}

void show()
{
System.out.println("Sub class i = "+i);
System.out.println("Super class i = "+super.i);
}
}
class Result
{
public static void main(String args[])
{
Sub s=new Sub(15,32);
s.show();
}
}
O/P:
Sub class i = 32
Super class i=15
Read more ...

Saturday, 8 November 2014

Accessing the Super class Constructor


We need not to access the super class default Constructor, by default it is present in sub/child class. Example:

class Parent
{
            Parent()
            {
            int i=12;
            System.out.println("i is : "+i);
            }
}
class Child extends Parent
{
            Child()
            {
            int i=8;
            System.out.println("i is : "+i);
            }
}

class DefaultConstructorIsCallAutomatically
{
            public static void main(String args[])
            {
Child t=new Child(); 
            }
}
O/P:
 i is : 12

 i is : 8
Read more ...

Preference of Super and Sub class:


In inheritance we always prefer to create the object of child class not the parent class,if we create the object of parent class it will access only the parent class member,to access both class member we should create the child class object.
If the Parent class and child class has the same member name(eg: instance variable and method) then by default it will call only child class member.

class Father       //Parent class
{
int age=60;               //Parent class instance variable
            void old()         //Parent class method
            {
            System.out.print("Age is : "+age);
            }
}

class Child extends Father       //Child class
{
int age=26;           //Child class instance variable
            void old()        //Child class method
            {
            System.out.print("Age is : "+age);
            }
}

class Preference
            {
            public static void main(String args[])
            {
                        Child ch=new Child();     //Child class object
                        ch.old();
            }
            }
O/P: Age is : 26
Now how to access the Super class or parent class member, for that we use “super” keword.We use super.variable for accessing super class variable and super.method() for super class method.Here is an example:


class Father       //Parent class
{
int age=60;               //Parent class instance variable
            void old()         //Parent class method
            {
            System.out.println("Age is Father : "+age);
            }
}

class Child extends Father       //Child class
{
int age=26;           //Child class instance variable
            void old()        //Child class method
            {
            System.out.println("Age of Child is : "+age);
           
            super.old();
           
            System.out.println("Age of Father is : "+super.age);
            }
}

class Preference
            {
            public static void main(String args[])
            {
                        Child ch=new Child();     //Child class object
                        ch.old();
            }

            }
O/P:Age of Child is : 26
      Age of Father is : 60
      Age of Father is : 60

Read more ...

Inheritance


Inheritance is used for reuse the code,Programming work can be efficient by saving the time without writing the code again.Programmer can use the code of parent class in the child class.So we can use the features of parent class to child class,child class gets all the feature of parent class by using extends keyword.Here in example we use the  mutator set() and accesor get()  method to set and get the values.Child class Trainee will acquire all the feature of Parent class Trainer and apart from this we will use another variable Grade for student which is required and was not in parent class Trainer.Now we can get the result by setting the values with the help of  child class object.
Example:

class Trainer
{
int id;
String name;
int age;
String address;

void setId(int id) //Mutator method
{
this.id=id;
}
int getId()   //Accesor method
{
return id;
}

void setName(String name) //Mutator method
{
this.name=name;
}
String getName() //Accesor method
{
return name;
}

void setAge(int age)
{
this.age=age;
}
int getAge()
{
return age;
}

void setAddress(String address)
{
this.address=address;
}
String getAddress()
{
return address;
}
}

class Trainee extends Trainer
{
char grade;
void setGrade(char grade)
{
this.grade=grade;
}
char getGrade()
{
return grade;
}
}

class InheritanceDemo
{
public static void main(String args[])
{
Trainee tr=new Trainee();
tr.setId(1);
tr.setName("Rupak");
tr.setAge(25);
tr.setAddress("Bandra,Mumbai,MH");
tr.setGrade('A');

System.out.println("Id is : "+tr.getId());
System.out.println("Name is : "+tr.getName());
System.out.println("Age is : "+tr.getAge());
System.out.println("Address is : "+tr.getAddress());
System.out.println("Grade is : "+tr.getGrade());
}
}
O/P:
Id is : 1
Name is : Rupak
Age is : 25
Address is : Bandra,Mumbai,MH
Grade is : A

Read more ...

Friday, 7 November 2014

Current date and Happy New Year program.


Java provides the Date class to find the the current date and time,generally this Date class encapsulates the Date and current Time .we can use this with toString to and get the current date and time.Here is an example:
import java.util.Date; //import Date from the util package
public class DateDemo
{
public static void main(String args[])
{
Date date=new Date(); //date object of  Date class
System.out.print(date.toString());
}
}

O/P:Sat Nov 08 13:01:31 IST 2014

WAP to wish Happy New Year

This program was developed to wish the happy new to your friends.In this program we used the buffered Reader to take the input from user,Assumed the current year is 2014 and December end,so if we give a input 2014 it will say that Say goodbye to 2014,if we put 2015 then it will show that Wish you happy new year 2015.but if we don't put 2014 or 2015 then it will show that please enter correct input.lets try it.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class HappyNewYear
{
int year;
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the year:");
int year=Integer.parseInt(br.readLine());
if(year==2014)
System.out.println("SAY GOODBYE TO 2014");
else if(year==2015)
System.out.println("\"WISH YOU HAPPY NEW YEAR 2015\"");
else System.out.println("pK ho kya????Pls enter correct input!!");

}
}
O/P:
Enter the year:2014
SAY GOODBYE TO 2014

Enter the year:2015
"WISH YOU HAPPY NEW YEAR 2015"

Enter the year:2010
pK ho kya????Pls enter correct input!!





Read more ...

Interface In Java


Multiple Inheritance is not allowed in JAVA,so we will use interface to overcome the Inheritance, if we use inheritance in java the programmer becomes confuse that from which class member is taken,Eg:If class A has a member ‘r’ and B also has a member ‘r’,if another class C extends both the classes then which copy of ‘r’ will be available in C, so we will use interface.
Interface uses implements keyword, inheritance uses extends keyword.
Here is an example:

interface Stallion // Adult Male horse
{
Float HT=6.8f;
void height();
}

interface Dam //Adult Female horse
{
Float HT=5.2f;
void height();
}

class Colt implements Stallion,Dam  // Colt Young male horse
{
public void height()
{
float ht=(Colt.HT+Filly.HT)/2;
System.out.print("Height of Colt is :"+ht);
}
}
class MultipleInheritance
{
public static void main(String args[])
{
Colt ch=new Colt ();
ch.height();
}
}
O/P: Height of Colt is :6.0

Read more ...

Java Features

Features of java are-
->Simple
->Object-Oriented
->Distributed
->Robust
->System Independence
->Portability
->High Performance
->Multi threaded
->Scalability
->Dynamic
1.Simple:Java is Simple because some complex concept of C,C++ have been omitted from java.Eg:Concept of Pointer is omitted,which makes the programmers confuse.
2.Object Oriented:Java is called object oriented because it uses object and class.Everything in world that really exists and which can be distinguish from others is called object.Eg:pen,man,car etc.A group of object having same behaviour comes under a group called class.A class is a group name given to the several objects.Eg:Flower(Rose,Orchid,Champa,Lily objects comes under this class).
3.Distributed:Java is distributed because information can be shared over the distributed network.
4.Robust:Robust means strong,java is strong because of two points,One is it does not crash easily like C,C++,because it has the In built Exception handling capacity,Exceptions are error occurs in run time,java can handle these Exception by Exception Handler,Second is Sometime C,C++ programs crush in middle because of Not allocating sufficient memory or forgetting the memory to be freed in the program,this problem is overcome by Java,Java Virtual Machine(JVM) take care of memory management.Programmers does not allocate or de-allocate the memory in java.
5.Secure:Java is secure because security challenges like tampering,impersonation and virus can be eliminated and minimized in Java on Internet.
6.System Independence:Java byte code or class file are not machine dependent,we can run java code on any machine,any processor or in any OS.so its called WORA(Write Once Run Anywhere)
7.Portability:Java Programs gives the same result in every machine,the system independence feature is called portability.
8.Interpreted:Java codes are compiled to generate byte code,these code can be interpreted by interpreter in JVM.
9.High Performance:Problem with the interpreter inside the JVM is that it is slow,but it was overcome by using the JIT(Just in time) compiler,which increases the speed of the execution.So now in JVM both interpreter and JIT compiler work together to run the program.
10.Multithreaded:A thread represents individual process to execute group of statements.JVM uses several threads to execute different blocks of code.
11.ScalabiltyJava platform can be implemented on wide range of computer with varying range of resources.This is possible because of java's compact and plateform independent features.
12.Dynamic:Before java development web pages were static ,now its dynamic.
Read more ...
Designed By Blogger Templates