Showing posts with label java. Show all posts
string handling :: futureX


String comparison:


There are three ways to compare String objects:


  • By equals() method
  • By = = operator
  • By compareTo() method



By equals() method:

equals() method compares the original content of the string.It compares values of string for equality.String class provides two methods:


public boolean equals(Object another){}
compares this string to the specified object.

public boolean equalsIgnoreCase(String another){}
compares this String to another String, ignoring case.


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

   String s1="salman";
   String s2="salman";
   String s3=new String("salman");
   String s4="shahrukh";

   System.out.println(s1.equals(s2));//true
   System.out.println(s1.equals(s3));//true
   System.out.println(s1.equals(s4));//false
 }
}


By == operator:

The = = operator compares references not values.


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

   String s1="Sachin";
   String s2="Sachin";
   String s3=new String("Sachin");

   System.out.println(s1==s2);//true (because both refer to same instance)
   System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
 }
}


By compareTo() method:

compareTo() method compares values and returns an int which tells if the values compare less than, equal, or greater than.

Suppose s1 and s2 are two string variables.If:

s1 == s2          :0
s1 > s2            :positive value
s1 < s2            :negative value


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

   String s1="Sachin";
   String s2="Sachin";
   String s3="Ratan";

   System.out.println(s1.compareTo(s2));//0
   System.out.println(s1.compareTo(s3));//1(because s1>s3)
   System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
 }
}


String Concatenation:



There are two ways to concat string objects:


  • By + (string concatenation) operator
  • By concat() method


 By + (string concatenation) operator

String concatenation operator is used to add strings.

For Example:

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

   String s="Sachin"+" Tendulkar";
   System.out.println(s);//Sachin Tendulkar
 }
}


The compiler transforms this to:

String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();

String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.String concatenation operator produces a new string by appending the second operand onto the end of the first operand.The string concatenation operator can concat not only string but primitive values also.

For Example:

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

   String s=50+30+"Sachin"+40+40;
   System.out.println(s);//80Sachin4040
 }
}


If either operand is a string, the resulting operation will be string concatenation. If both operands are numbers, the operator will perform an addition.


 By concat() method

concat() method concatenates the specified string to the end of current string.

Syntax : public String concat(String another){}

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

   String s1="Sachin ";
   String s2="Tendulkar";

   String s3=s1.concat(s2);

   System.out.println(s3);//Sachin Tendulkar
  }
}

Substring:



You can get substring from the given String object by one of the two methods:
       

public String substring(int startIndex)

This method returns new String object containing the substring of the given string from specified startIndex (inclusive).

public String substring(int startIndex,int endIndex):

This method returns new String object containing the substring of the given string from specified startIndex to endIndex.

In case of string

startIndex    :starts from index 0(inclusive).
endIndex      :starts from index 1(exclusive).

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

   String s="Sachin Tendulkar";
   System.out.println(s.substring(6));//Tendulkar
   System.out.println(s.substring(0,6));//Sachin
 }
}



                                                             JAVA TUTORIALS HOMEPAGE
String Handling in java

In java, string is basically an immutable object. We will discuss about immutable string later. Let's first understand what is string and how we can create the string object.

Generally string is a sequence of characters. But in java, string is an object. String class is used to create string object.


There are two ways to create String object:


  • By string literal
  • By new keyword



By String Literal :
String literal is created by double quote.
For Example:

String s="Hello";


Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool.For example:


String s1="Welcome";
String s2="Welcome";//no new object will be created


In the above example only one object will be created.First time JVM will find no string object with the name "Welcome" in string constant pool,so it will create a new object.Second time it will find the string with the name "Welcome" in string constant pool,so it will not create new object whether will return the reference to the same instance.

String objects are stored in a special memory area known as string constant pool inside the Heap memory.

Why java uses concept of string literal?

To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).


By new Keyword :

String s=new String("Welcome");//creates two objects and one reference variable


In such case, JVM will create a new String object in normal(non pool) Heap memory and the literal "Welcome" will be placed in the string constant pool.The variable s will refer to the object in Heap(non pool).



Immutable String:

In java, strings are immutable (unmodifiable) objects.For example


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

   String s="Sachin";
   s.concat(" Tendulkar");//concat() method appends the string at the end
   System.out.println(s);//will print Sachin because strings are immutable objects
 }
}


Output: Sachin


As you can see in the above figure that two objects will be created but no reference variable refers to "Sachin Tendulkar".But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar" object.For example:


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

   String s="Sachin";
   s=s.concat(" Tendulkar");
   System.out.println(s);
 }
}


Output: Sachin Tendulkar


Why string objects are immutable in java?

Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one object "sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.


                                           JAVA TUTORIALS HOMEPAGE

array in java :: futureX
In java,array is an object. Array in C & C++ is static but in Java it is dynamic.

1D Array:


Declaration:

datatype  []var = new datatype[size];
                      OR
datatype[]  var = new datatype[size];
                      OR
datatype  var[] = new datatype[size]; 

Example:


class A{
public static void main(String[] args){
int a[]=new int[5];
a[0]=11;
a[2]=33;
a[4]=1;

for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}
}

Output:(default value is zero)
11
0
33
0
1

Q: Write a program to find minimum from the Array?


class A{
static void printmin(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
{
if(min>arr[i])
min=arr[i];
}
System.out.println("min is ::" +min);
}

public static void main(String[] args){
int a[]=new int[5];
a[0]=12;
a[1]=1;
a[2]=22;
a[3]=5;
a[4]=32;

printmin(a);
}}

2D Array:

Declaration:

datatype[][]  var = new datatype[size][size];
                      OR
datatype  [][]var = new datatype[size][size];
                      OR
datatype var[][] = new datatype[size][size];
                      OR
datatype  []var[] = new datatype[size][size];

Example:


class A{
public static void main(String args[]){
int a[][]=new int[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++){
a[i][j]=i+j;
System.out.println(a[i][j]+" ");
}
System.out.println();
}}}

Anonymous Array:
JAVA feature of array. 
In normal array, as int a[]={} same array can't declared twice. 


class A{
static void printarray(int arr[]){
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
public static void main(String args[]){
printarray(new int[]{14,5,5,8});
printarray(new int[]{14,3,8,8});
}}


                                             JAVA TUTORIALS HOMEPAGE


access modifiers in java :: futureX

 There are 4 types of access modifiers:


  1. private
  2. default
  3. protected
  4. public



Private :
The private access modifier is accessible only within class.


example :
class Emp{
private int id;
private void show(){System.out.println(id);}
}

class Test{
public static void main(String args[]){
Emp e=new Emp();
e.id=10;
e.show();
}
}

output:compile time error


Note: A class cannot be private or protected except nested class.


Default :
If you don't use any modifier, it is treated as default modifier by default. The default modifier is accessible only within package.

example:

//save as A.java
package com.futurex;
public class A{
void msg(){System.out.println("hello");}
}

//save as Test.java
package com.techshakti;
import com.futurex.*;
class Test{
public static void main(String args[]){
A a=new A();
a.msg();
}
}

output: msg() is not public in A; cannot be accessed from outside package


Protected :
The protected access modifier is accessible within package and outside the package by only through inheritance.
The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.

example:


//save as A.java
package com.futurex;
public class A{
protected void msg(){System.out.println("hello");}
}

//save as Test.java
package com.techshakti;
import com.futurex.*;
class Test extends A{
public static void main(String args[]){
Test t=new Test();
t.msg();
}
}



Public:
The public access modifier is accessible everywhere. It has the widest scope among all other modiers.

example:

//save as A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}


//save as B.java
package mypack;
import pack.*;

class B{
  public static void main(String args[]){
   A obj = new A();
   obj.msg();
  }
}


                  JAVA TUTORIALS HOMEPAGE


A package is a group of similar types of class, interfaces and sub-packages.
Package can be categorized in two form, built-in package and user-defined package. There are many built-in packages such as java.lang, awt, javax, swing, net, io, util, sql etc.
package in java :: futureX

In this page, we will have the detailed learning of creating user-defined packages.

Advantage of Package

  • Package is used to categorize the classes and interfaces so that they can be easily maintained.
  • Package providEs access protection.
  • Package removes naming collision.

Example

To compile : javac -d . Simple.java
To run       : java mypack.Simple

package com;
class Simple{
public static void main(){
System.out.println("hello java");
}
}

The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents the current folder.


How to access package from another package?

  • import package.*;
  • import package.classname;
  • fully qualified name.



The import keyword is used to make the classes and interface of another package accessible to the current package.



If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.

If you import package.classname then only declared class of this package will be accessible but not subpackages.

If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface.

package math;
public class Calc{
public static int cube(int n){return n*n*n;}
}


//import all the classes of that package

package com;
import math.*;
class Simple{
public static void main(String args[]){
System.out.println(Calc.cube(5));
}
}

//only declared class is acessible

package com;
import math.Calc;
class Simple{
public static void main(String args[]){
System.out.println(Calc.cube(5));
}
}




//without import, full qualified name

package com;
class Simple{
public static void main(String args[]){
System.out.println(math.Calc.cube(5));
}
}


Subpackages:

Package inside the package is called the subpackage. It should be created to categorize the package further. Let's take an example, Sun Microsystems has defined a package named java that contains many classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java package into subpackages such as lang, net, io etc. and put the Input/Output related classes in io package, Server and ServerSocket classes in net packages and so on.

standard declaration:
com.companyname.packagename.classname

package com.techshakti.math;
public class subpackage{
public static int cube(int n){return n*n*n;}
}


                                          JAVA TUTORIALS HOMEPAGE
interface in java :: futureX

Interface: An interface is a blueprint of a class. It has static constants and abstract methods.
The interface is a mechanism to achieve abstraction in java. There can be only abstract methods in the interface. It is used to achieve fully abstraction and multiple inheritance in Java.

Why use Interface?

It is used to achieve fully abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling
the java compiler converts methods of interface as public and abstract, data members as public,final and static by default.

Example :

interface Shape{
void draw();
}

class Circle implements Shape{
public void draw(){System.out.println("drawing circle");}
}

class Rectangle implements Shape{
public void draw(){System.out.println("drawing rectangle");}
}

class Test{
public static void main(String args[]){
Shape S=new Circle();
S.draw();

}}

multiple inheritance by interface :

interface Shape{
void draw();
}

interface Color{
String getColor();
}


class Rectangle implements Shape,Color{
public void draw(){System.out.println("drawing rectangle");}
public String getColor(){return("red");}
}

class Test{
public static void main(String args[]){
Rectangle s=new Rectangle();
s.draw();
System.out.println(s.getColor());
}}

                                            JAVA TUTORIALS HOMEPAGE

abstraction in java :: futureX

Abstraction is a process of hiding the implementation details and showing only functionality to the user.Abstraction lets you focus on what the object does instead of how it does it.


Ways to achieve Abstraction:
Abstract class (0 to 100%)
Interface (100%)

Abstract class:
A class that is declared as abstract is known as abstract class.It needs to be extended and its method implemented.It cannot be instantiated.


           abstract class class_name{}

Abstract method:
A method that is declared as abstract and does not have implementation is known as abstract method.


          abstract return_type method_name();    //no braces{}

Example:

abstract class Shape{
abstract void draw();
}

class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}

class Circle extends Shape{
void draw(){System.out.println("drawing circle");}
}

class Test{
public static void main(String args[]){
Shape s=new Circle();
s.draw();
}
}


Note: An abstract class can have data member,abstract method,method body,constructor and even main() method.

Rule: If there is any abstract method in a class, that class must be abstract.

//Shape is not abstract and does not override abstract method //draw() in shape

class Shape{
abstract void draw();
}


                   JAVA TUTORIALS HOMEPAGE





runtime polymorphism in java :: futureX
Runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time.In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.


UPCASTING :
When reference variable of Parent class refers to the object of Child class, it is known as upcasting.
upcasing in java :: futureX
For example:


class Animal{
void eat(){System.out.println("eating food");}
}

class Human extends Animal{
void eat(){System.out.println("eating delicious food");}

public static void main(String args[]){
Animal A=new Human();
A.eat();
}
}

Example of runtime polymorphism


class Bike{
   void run(){System.out.println("running");}
 }
 class Splender extends Bike{
   void run(){System.out.println("running safely with 60km");}

   public static void main(String args[]){
     Bike b = new Splender();//upcasting
     b.run();
   }
 }


In this example, we are creating two classes Bike and Splendar. Splendar class extends Bike class and overrides its run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, subclass method is invoked at runtime. Since it is determined by the compiler, which method will be invoked at runtime, so it is known as runtime polymorphism.


Rule: Runtime polymorphism can't be achieved by data members.

class Bike{ int speedlimit=90; } class Honda extends Bike{ int speedlimit=150; public static void main(String args[]){ Bike obj=new Honda(); System.out.println(obj.speedlimit);//output 90 } }

JAVA TUTORIALS HOMEPAGE



The final keyword in java is used to restrict the user. The final keyword can be used in many context. Final can be:
final keyword in java :: futureX

  • variable
  • method
  • class


Final variable :
If you make any variable as final, you cannot change the value of final variable(It will be constant).

//can't assign a value to final variable class Simple{ final int a=50; void change(){ a=100; //CTE } public static void main(String args[]){ Simple S=new Simple(); S.change(); System.out.println(S.a); } }

Final method :
If you make any method as final, you cannot override it.

//overriden method is final CTE class A{ final void m(){System.out.println("hello");} } class Simple extends A{ void m(){System.out.println("java");} public static void main(String args[]){ Simple S=new Simple(); S.m(); } }

Final class :
If you make any class as final, you cannot inherit it.

//cant inherit from final class CTE final class A{} class Simple extends A{ public static void main(String args[]) {} }

super is a reference variable that is used to refer immediate parent class object.

Uses of super Keyword:

  • super is used to refer immediate parent class instance variable.
  • super() is used to invoke immediate parent class constructor.
  • super is used to invoke immediate parent class method.
1.super is used to refer immediate parent class instance variable.

Problem without super keyword

class Vehicle{ int speed=50; } class Bike extends Vehicle{ int speed=100; void display(){ System.out.println(speed);//will print speed of Bike } public static void main(String args[]){ Bike b=new Bike(); b.display(); } }

In the above example Vehicle and Bike both class have a common property speed. Instance variable of current class is refered by instance bydefault, but I have to refer parent class instance variable that is why we use super keyword to distinguish between parent class instance variable and current class instance variable.

Solution by super keyword

class Vehicle{ int speed=50; } class Bike extends Vehicle{ int speed=100; void display(){ System.out.println(super.speed);//will print speed of Vehicle now } public static void main(String args[]){ Bike b=new Bike(); b.display(); } }

2.super is used to invoke parent class constructor.

class Vehicle{ Vehicle(){System.out.println("Vehicle is created");} } class Bike extends Vehicle{ Bike(){ super();//will invoke parent class constructor System.out.println("Bike is created"); } public static void main(String args[]){ Bike b=new Bike(); } }

3. super can be used to invoke immediate parent class method.

class Person{ void message(){System.out.println("welcome");} } class Student extends Person{ void message(){System.out.println("welcome to java");} void dislay(){ message();//will invoke current class message() method super.message();//will invoke parent class message() method } public static void main(String args[]){ Student s=new Student(); s.display(); } }

JAVA TUTORIALS HOMEPAGE
Inheritance is a mechanism in which one object acquires all the properties and behaviour of another object. The idea behind inheritance is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you reuse (or inherit) methods and fields, and you add new methods and fields to adapt your new class to new situations.Inheritance represents the IS-A relationship.



Why use Inheritance?

  • for method overriding
  • for code reusability
Syntax of Inheritance

class Subclass-name  extends Superclass-name
{
//methods and fields
}


The keyword extends indicates that you are making a new class that derives from an existing class.
In the terminology of Java, a class that is inherited is called a superclass. The new class is called a subclass.

types of inheritance:
















 example of single level inheritance :
class Animal{
void eat(){System.out.println("eating food");}
}


class Dog extends Animal{

void bark(){System.out.println("barking");}

public static void main(String args[]){

Dog d=new Dog();
d.bark();
d.eat();

}
}



Que) Why multiple inheritance is not supported in java?   To reduce the complexity and simplify the language,multiple inheritance is not supported in java.


                            JAVA TUTORIALS HOMEPAGE
Having the same method in the subclass as declared in the parent class is known as method overriding. If a subclass provides a specific implementation of a method that is already provided by its super class, it is known as Method Overriding.

Advantages :

1) Method Overriding is used to provide specific implementation of a method that is already provided by its super class.

2) Method Overriding is used for Runtime Polymorphism.

Rules :

1) method must have same name as in the parent class.

2) method must have same parameter as in the parent class.


class Animal{ void eat(){System.out.println("eating");} } class Human extends Animal{ void eat(){System.out.println("eating delicious food");} public static void main(String args[]){ Human h= new Human(); h.eat(); }
}

Output eating delicious food

 
JAVA TUTORIALS HOMEPAGE


The static keyword is used in java mainly for memory management. We may apply static keyword with variables, methods and blocks. The static keyword belongs to the class than instance of the class. The static can be:

  • variable
  • method
  • block
Static variable :
If you declare any variable as static, it is known static variable.

1) The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.

2) The static variable gets memory only once in class area at the time of class loading.


class Student{
int id;
String address;
static String college ="Rkgit";

Student(int id,String address){
this.id=id;
this.address=address;
}

void displayRecord(){
System.out.println(id+" "+address+" "+college);
}

public static void main(String args[]){
Student s1=new Student(112,"new delhi");
Student s2=new Student(119,"ghaziabad");

s1.displayRecord();
s2.displayRecord();
}
}

Static method :

If you apply static keyword with any method, it is known as static method.

1) A static method belongs to the class rather than object of a class.

2) A static method can be invoked without the need for creating an instance of a class.

3) Static method can access static data member and can change the value of it.


class A{

static int cube(int n){
return (n*n*n);
}

public static void main(String args[]){
System.out.println(cube(3));
}
}


Static block :

1) It is used to initialize the static data member.

2) It is excuted before main method at the time of classloading.


class A{

static {
System.out.println("static block is executed");}

public static void main(String args[]){
System.out.println("main method executed");
}




                                     JAVA TUTORIALS HOMEPAGE







































Copyright © 2013 futureX | Blogger Template by Clairvo