Friday, 26 February 2016

Class and Object and Variabls in java

OOPs:-(object oriented programming system):-it is technique for solving bussiness problem
1-abstraction.
2-incapsulation.
3-inheritance.
4-polymorphism.

Class:-class is collection of variable and methods
 and we can say it is prototype or template or blue print of object's state and behavior,
class can hold both  data and function

Example

public class Dog {
   String breed;
   int age;
   String color;

   void barking() {
   }

   void hungry() {
   }

   void sleeping() {
   }
}
ex:-class Employee{
int eid;
Strings ename;
long phone;
void show(){

....
  }
}

Q:-Why class?
ans-java has giving some fixed datatypes to store values, but
in real world - we need some data types which are not giving by java
exmple:-in tickit reservation  project, we need a data type called passenger, but it is not predefined in java.
so in order to create user-defined datatypes by using fixed datatype , we use class.

Objects in Java

What is  Object:-
ans-Any real word living or nonliving physicl things is called object
ex:-bank , telivision
we can say object is instance of a class.
Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors – wagging the tail, barking, eating. An object is an instance of a class.
Let us now look deep into what are objects. If we consider the real-world, we can find many objects around us, cars, dogs, humans, etc. All these objects have a state and a behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking, wagging the tail, running.
If you compare the software object with a real-world object, they have very similar characteristics.
Software objects also have a state and a behavior. A software object's state is stored in fields and behavior is shown via methods.
So in software development, methods operate on the internal state of an object and the object-to-object communication is done via methods.

Q-Why we need object?
ans:-in c language a program is loaded separately for each input values into memory for execution
if we want to pass 10 time input values then a c-program is loaded for 10 times

to overcome this problem  in oops concept is called object is introduce with object
here we can send multiple times values to a program loading it for once
class is loaded into jvm for onec and multiple object can be created to pass input to that class.
example:-

class Employee{                           
int eid;
Strings ename;
long phone;
void show(){

System.out.println(eid);
System.out.println(ename);
System.out.println(phone);
  }
}


public class Main{

public static void main(Strings args[]) {

Employee e1=new Employee();
e1.show();
Employee e12=new Employee();
e2.eid=99;
e2.ename="piyush";
e2.phone=8951155787;
e2.show();
  }
}

Q-What is a Java Variable:-
Ans-Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in the memory.

A variable is container, which holds user data
memory will be allocated  for the variable while executing the program
value of variable can be change any number of times during the program execution.

ex:- int x=5;
class Integers {
  public static void main(String[] arguments) {
    int c=10; //declaring a variable
 
System.out.println(c);
  
  }
}


There type of variable:-
1:-instance variable
2:-class variable
3:-local variable

1-Instance Variables

it is class level variable 
we can say a variable defined in class without using static modifier are called instance variable it is also called non-static variable
note:-memory will be allocated for instance variable at that time of creation an object.
instance variable are storing in heap area.

  • Instance variables are declared in a class, but outside a method, constructor or any block.
  • When a space is allocated for an object in the heap, a slot for each instance variable value is created.
  • Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.
  • Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.
  • Instance variables can be declared in class level before or after use.
  • Access modifiers can be given for instance variables.
  • The instance variables are visible for all methods, constructors and block in the class. Normally, it is recommended to make these variables private (access level). However, visibility for subclasses can be given for these variables with the use of access modifiers.
  • Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is null. Values can be assigned during the declaration or within the constructor.
  • Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName.

Example

 Live Demo
import java.io.*;
public class Employee {

   // this instance variable is visible for any child class.
   public String name;

   // salary  variable is visible in Employee class only.
   private double salary;

   // The name variable is assigned in the constructor.
   public Employee (String empName) {
      name = empName;
   }

   // The salary variable is assigned a value.
   public void setSalary(double empSal) {
      salary = empSal;
   }

   // This method prints the employee details.
   public void printEmp() {
      System.out.println("name  : " + name );
      System.out.println("salary :" + salary);
   }

   public static void main(String args[]) {
      Employee empOne = new Employee("Ransika");
      empOne.setSalary(1000);
      empOne.printEmp();
   }
}
This will produce the following result −

Output

name  : Ransika
salary :1000.0

2:-



2-Local Variables

:-a variable which defined inside method.
note:-memeory allocate to local variable, when ever metho is called.
loacl variable are storing in stack area.



Example

Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to only this method.
 Live Demo
public class Test {
   public void pupAge() {
      int age = 0;
      age = age + 7;
      System.out.println("Puppy age is : " + age);
   }

   public static void main(String args[]) {
      Test test = new Test();
      test.pupAge();
   }
}
This will produce the following result −

Output

Puppy age is: 7

Example

Following example uses age without initializing it, so it would give an error at the time of compilation.
 Live Demo
public class Test {
   public void pupAge() {
      int age;
      age = age + 7;
      System.out.println("Puppy age is : " + age);
   }

   public static void main(String args[]) {
      Test test = new Test();
      test.pupAge();
   }
}
This will produce the following error while compiling it −

Output

Test.java:4:variable number might not have been initialized
age = age + 7;
         ^
1 error

3-

Class/Static Variables

Ans- it is also calss level variable
a variable defined in the class using static modifier are called class variable or also called ststic variable.
class variable is stored in methos area.
note:memory will be allocated for static variable at the time of loading the class.

  • Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
  • There would only be one copy of each class variable per class, regardless of how many objects are created from it.
  • Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final, and static. Constant variables never change from their initial value.
  • Static variables are stored in the static memory. It is rare to use static variables other than declared final and used as either public or private constants.
  • Static variables are created when the program starts and destroyed when the program stops.
  • Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class.
  • Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null. Values can be assigned during the declaration or within the constructor. Additionally, values can be assigned in special static initializer blocks.
  • Static variables can be accessed by calling with the class name ClassName.VariableName.
  • When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.

Example

 Live Demo
import java.io.*;
public class Employee {

   // salary  variable is a private static variable
   private static double salary;

   // DEPARTMENT is a constant
   public static final String DEPARTMENT = "Development ";

   public static void main(String args[]) {
      salary = 1000;
      System.out.println(DEPARTMENT + "average salary:" + salary);
   }
}
This will produce the following result −

Output

Development average salary:1000
Note − If the variables are accessed from an outside class, the constant should be accessed as Employee.DEPARTMENT

 Q- there are four way to access class variable?
ans-instance variable:-4 way
    class variable:-  2 way
    local variable:- 1 way

Q- how to declaring and inilizating a variable?

ans-
class Employee{                           
int a=99;
Strings str="Piyush";
double d=99.99;
boolean b=true;
void show(){

System.out.println(a);
System.out.println(str);
System.out.println(d);
System.out.println(b);
  }
}

Creating an Object

As mentioned previously, a class provides the blueprints for objects. So basically, an object is created from a class. In Java, the new keyword is used to create new objects.
There are three steps when creating an object from a class −
  • Declaration − A variable declaration with a variable name with an object type.
  • Instantiation − The 'new' keyword is used to create the object.
  • Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.

Example


public class Puppy {
   public Puppy(String name) {
      // This constructor has one parameter, name.
      System.out.println("Passed Name is :" + name );
   }

   public static void main(String []args) {
      // Following statement would create an object myPuppy
      Puppy myPuppy = new Puppy( "tommy" );
   }
}

Output

Passed Name is :tommy

Accessing Instance Variables and Methods

Instance variables and methods are accessed via created objects. To access an instance variable, following is the fully qualified path −
/* First create an object */
ObjectReference = new Constructor();

/* Now call a variable as follows */
ObjectReference.variableName;

/* Now you can call a class method as follows */
ObjectReference.MethodName();

Example

This example explains how to access instance variables and methods of a class.
 Live Demo
public class Puppy {
   int puppyAge;

   public Puppy(String name) {
      // This constructor has one parameter, name.
      System.out.println("Name chosen is :" + name );
   }

   public void setAge( int age ) {
      puppyAge = age;
   }

   public int getAge( ) {
      System.out.println("Puppy's age is :" + puppyAge );
      return puppyAge;
   }

   public static void main(String []args) {
      /* Object creation */
      Puppy myPuppy = new Puppy( "tommy" );

      /* Call class method to set puppy's age */
      myPuppy.setAge( 2 );

      /* Call another class method to get puppy's age */
      myPuppy.getAge( );

      /* You can access instance variable as follows as well */
      System.out.println("Variable Value :" + myPuppy.puppyAge );
   }
}
If we compile and run the above program, then it will produce the following result −

Output

Name chosen is :tommy
Puppy's age is :2
Variable Value :2

Example-we will be creating two classes. They are Employee and EmployeeTest.


The Employee class has four instance variables - name, age, designation and salary. The class has one explicitly defined constructor, which takes a parameter.

Example

import java.io.*;
public class Employee {

   String name;
   int age;
   String designation;
   double salary;

   // This is the constructor of the class Employee
   public Employee(String name) {
      this.name = name;
   }

   // Assign the age of the Employee  to the variable age.
   public void empAge(int empAge) {
      age = empAge;
   }

   /* Assign the designation to the variable designation.*/
   public void empDesignation(String empDesig) {
      designation = empDesig;
   }

   /* Assign the salary to the variable salary.*/
   public void empSalary(double empSalary) {
      salary = empSalary;
   }

   /* Print the Employee details */
   public void printEmployee() {
      System.out.println("Name:"+ name );
      System.out.println("Age:" + age );
      System.out.println("Designation:" + designation );
      System.out.println("Salary:" + salary);
   }
}
As mentioned previously in this tutorial, processing starts from the main method. Therefore, in order for us to run this Employee class there should be a main method and objects should be created. We will be creating a separate class for these tasks.
Following is the EmployeeTest class, which creates two instances of the class Employee and invokes the methods for each object to assign values for each variable.
Save the following code in EmployeeTest.java file.
import java.io.*;
public class EmployeeTest {

   public static void main(String args[]) {
      /* Create two objects using constructor */
      Employee empOne = new Employee("James Smith");
      Employee empTwo = new Employee("Mary Anne");

      // Invoking methods for each object created
      empOne.empAge(26);
      empOne.empDesignation("Senior Software Engineer");
      empOne.empSalary(1000);
      empOne.printEmployee();

      empTwo.empAge(21);
      empTwo.empDesignation("Software Engineer");
      empTwo.empSalary(500);
      empTwo.printEmployee();
   }
}
Now, compile both the classes and then run EmployeeTest to see the result as follows −

Output

C:\> javac Employee.java
C:\> javac EmployeeTest.java
C:\> java EmployeeTest
Name:James Smith
Age:26
Designation:Senior Software Engineer
Salary:1000.0
Name:Mary Anne
Age:21
Designation:Software Engineer
Salary:500.0

Data Types in Java

Data types represent the different values to be stored in the variable. In java, there are two types of data types:
Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables.
  • Primitive data types
  • Non-primitive data types
datatype in java



Literals:-literal are the actuals values
literal will be assigned to variable or constant
literal are also used to perform any operatons.

example:-datatype  variable name    Literals
                int             a                  =   123;
               String         str               =    "piyush";

String literals:-  strings litrals s collections of zero or more characters enclosed between quotations marks.
strings variable can be assigned to reference variable of type string

ex:-public class Lab41 { public static void main(String[] args) { String str1=null; System.out.println(str1);
int x=str1.length(); System.out.println(x); } }


Operators:--

ans:-operators are used to perform oprations  by using operands

1:-Unary operator.
2:-Binary operator.
3:-Ternary operator

1:- Unary operator:-
     (a)Unary arithmetic operators.
     (b)Binary arithmetic operators.

Q-arithmetic operators.?
ans:-
+
_

*

/

%

example1:-
class Programming{
  public static void main(String[] arguments) {

 int num1,num2;
num1=10;
num2=20;

int result;
result=num1+num2;
System.out.println(result);
  
  }
}

Exm2
class Programming{
  public static void main(String[] arguments) {

 int num1,num2;
num1=10;
num2=20;


System.out.println(num1 + num2);
System.out.println(num1 - num2);
System.out.println(num1 * num2;);
System.out.println(num1 % num2;);
System.out.println(num1 /num2;);

  
  }
}

Strings concatenation Operators:-

example:-

class Programming{
  public static void main(String[] arguments) {

 int a=90;

 int b=9;








System.out.println("sum is" +a+b);

  }
}

exm2:-
class Programming{
  public static void main(String[] arguments) {

 int a=10;
 int b=8;
int c=a+b;
String str="Sum of" +a+" and "+b+" is "+c;


System.out.println(str);
System.out.println("%d,%d,%d"+a,b,c);

  }
}

 Assignment operators:-(=)

ans:-it is binary operator
it is used to assign the value to a variable.
example:-
class Programming{
  public static void main(String[] arguments) {
int a=123;
int b=12+23;
System.out.println(a);
System.out.println(b);

  }
}


Type casting:-
1:-implicit casting:-when type casting is  happening automatically  by compiler then it is called as implicit casting
2:-expilicit casting:-when type casting is done by the programmer expilicitly then it is called as expilicitly casting
example:-int a=10; // this is implicit
byte b=(byte)a;// this is expilicit

increment and dcrement operator:-
increment operator will be used to increase the value of the variable by 1
example:-
class Increment{
  public static void main(String[] arguments) {
int a=10;
a=a+1;
System.out.println(a);


  }
}//output:11

class Increment{
  public static void main(String[] arguments) {
int a=10;
a++;
System.out.println(a);


  }
}//output:11

class Increment{
  public static void main(String[] arguments) {
int a=10;
++a;
System.out.println(a);


  }
}//output:11

class Increment{
  public static void main(String[] arguments) {
int a=10;

System.out.println(a++);


  }
}//output:10

class Increment{
  public static void main(String[] arguments) {
int a=10;

System.out.println(a++);

System.out.println(a);
  }
}//output:11

class Increment{
  public static void main(String[] arguments) {
int a=10;
a++;
System.out.println(a);
System.out.println(a++);
System.out.println(a);


  }
}//output:11
 //output:11
 //output:12

class Increment{
  public static void main(String[] arguments) {
int a=10;
++a;
System.out.println(a);
System.out.println(++a);
System.out.println(a);


  }
}//output:11
 //output:12
 //output:12
Relational operator
example:-
class Comparison{
public static void main(String[] arguments) {
boolean result;
int num1=100, num2=100;
result= num1 >num2;
System.out.println(result);
System.out.println(num1 < num2 );
System.out.println(num1 <= num2 );
System.out.println(num1 >= num2 );
System.out.println(num1 == num2 );


  }
}

class Comparison{
public static void main(String[] arguments) {
boolean result;
int num1=100, num2=100;
result= 100<=95
System.out.println(result);


  }
}


Locgical operator:- logcal operator work on boolen value.
logical  operator are used to form logical expressions
the operands of these operators boolean type.
result of logical expeession will be boolean type i.e:treu or false
!= not operator:-
example:-
class Condition {
  public static void main(String[] args) {
    boolean human= true;
 
    if (human) {
      System.out.println("am human");
    }
    else {
      System.out.println("am not human");
    }
  }
}//output: am human

class Condition {
  public static void main(String[] args) {
    boolean human= true;
 
    if (!human) {
      System.out.println("am human");
    }
    else {
      System.out.println("am not human");
    }
  }
}//output: am  not human

class Condition {
  public static void main(String[] args) {
    boolean human= false;
 
    if (!human) {
      System.out.println("am human");
    }
    else {
      System.out.println("am not human");
    }
  }
}//output: am  human

&&= and operator:-
example:-
true && true = true
true && false = false
false && false = false

example2:-class Condition {
  public static void main(String[] args) {
    boolean human= false;
 
    if (!human) {
      System.out.println("am human");
    }
    else {
      System.out.println("am not human");
    }

int number=6
if((number % 2==0) && (number % 3==0)){
System.out.println(number+"number is completely divisible by 2 and 3");

}else{
System.out.println(number+"number is not completely divisble by 2 and 3");
}
  }
}//output: am  human
 //output:6 is completely divisible by 2 and 3


|| = or operator
example: true || false = true
         true || true = true
         false || false = false
example:-example of or operator
class Condition {
  public static void main(String[] args) {
    boolean human= false;
 
    if (!human) {
      System.out.println("am human");
    }
    else {
      System.out.println("am not human");
    }

int number=8
if((number % 2==0) && (number % 3==0)){
System.out.println(number+"number is completely divisible by 2 and 3");

}else{
System.out.println(number+"number is not completely divisble by 2 and 3");
}

if((number % 2==0) || (number % 3==0)){
System.out.println(number+"number is completely divisible by 2 or 3");

}else{
System.out.println(number+"number is not completely divisble by 2 or 3");
}
} }//output: am human
 //output:8 is  not completely divisible by 2 and 3
 //output:8 is  completely divisible by 2 and 3

Java if else program:

ans:-Java if else program uses if else to execute statement(s) when a condition is fulfilled
class Condition {
  public static void main(String[] args) {
   
 
    if (condition) {
step1:- if this condition is true    
       what ever statement we can write between  in this curlibraces will be executed
     so if this condition will true we can ececute all the code, that we can write inside this block.

Step2:- if this condition is false  at that time the statement that we can write inside the block that will not be executed in that case else part  statement will execute
    }
    else {
      
    }
  }
}//output:-


example:-class Condition {
  public static void main(String[] args) {
   
 int age=16;
    if (age>=18) {
System.out.println("welcome to dance clube");

}else{
System.out.println("go home kid");

}

System.out.println("dancing is fun");
  }
}
by using scanner:-
example:-class IfElse {
  public static void main(String[] args) {
    int marksObtained, passingMarks;
 
    passingMarks = 40;
 
    Scanner input = new Scanner(System.in);
 
    System.out.println("Input marks scored by you");
 
    marksObtained = input.nextInt();
 
    if (marksObtained >= passingMarks) {
      System.out.println("You passed the exam.");
    }
    else {
      System.out.println("Unfortunately you failed to pass the exam.");
    }
  }
}
If else If:-

class Condition {
  public static void main(String[] args) {
   
 int chocolate=1;
    if (chocolate==1) {
System.out.println("  one chocolate");
System.out.println(" am gonig to eat one chocolate");
}else if(chocolate==2){
System.out.println(" am gonig to eat one chocolate and one to give my gf");
}

else if(chocolate==3){
System.out.println(" am gonig to eat one chocolate and one to give my gf one to bf");

}else{
 System.out.println("more than one chocolate");
System.out.println(" am gonig share will be to all my friend");
}
 }
}

Java for loop:

Java for loop used to repeat execution of statement(s) until a certain condition holds true. for is a keyword in Java programming language.
lets say you want to print text 100 time
example :-
-class Condition {
  public static void main(String[] args) {
   
  latter carthdhd // so what you can do you can write system.out.println 100 time
                   and lets you can say you have to print 500 times
                   so thats its not convenient way
  note :-what we can do you can write only one statement and make at to execute  a 
statement 100 time tus can be dine by using loops in java
   }
}
1:-for loop
2:-while loop
3:-do while loop
2:-while loop:-
example;-
class Checkin{
  public static void main(String[] args) {
   
int counter =1;  // here counter value is not change in our program every time check for the condition it will be 1 or it will be less than or equal to 10 and execute the body infinite time
  
while(counter<=10){ // if this while loop condition is true than this blog will execute
note:- so what we can do we can increment the value of this counter variable so here inside the loop body i am goona to 
 System.out.println("infinite loop");

}
   }
}output:- if i run this program every time this condition will true

example:--

public class Chicken {

 public static void main(String[] args) {
   
  int counter = 1;
  
  while(counter <= 10){
   System.out.println(counter+"");
   System.out.println("learning lad");
   counter++;
  }
 }

}
output:- it will be execute 10 time
for loop
You can initialize multiple variables, test many conditions and perform increments or decrements on many variables according to requirement. Please note that all three components of for loop are optional. For example following for loop prints "Java programmer" indefinitely.
example:-
class Integers {
  public static void main(String[] arguments) {
    int c; //declaring a variable
 
  /* Using for loop to repeat instruction execution */
 
    for (c = 1; c <= 10; c++) {
      System.out.println(c);
    }
  }
}

example:-

carlibaces:({}) --this curlibraces are use to define region or blogs in java .region or blogs is nothing but  collections of some statement
so  here in this block class which belongs to this class Hello we can write java statement.

Q-what is methos:-
ans-methos is nothing but a name giving to group of  action that we can do.
first program:-
class Integers {
  public static void main(String[] arguments) {
    int c=10; //declaring a variable
 
System.out.println(c);
  
  }
}


1 comment: