Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, 6 November 2018

Variables in Java

Hi Guys, In this post I'll share some Basic Variable Concepts in Java which will very help full for beginners.
Guys be ready to implement those concepts in your system after getting boost up .

What's a variable Gys?
In a discussion friends i found, A variable can be thought of as a container which holds value for you, during the life of a Java program. Every variable is assigned a data type which designates the type and quantity of value it can hold.
In order to use a variable in a program you to need to perform 2 steps -

  • Variable Declaration- To declare a variable, you must specify the data type & give the variable a unique name.

Examples of other Valid Declarations are

int a,b,c;
float pi;
double d;
char a;

  • Variable Initialization- To initialize a variable, you must assign it a valid value.

Example of other Valid Initializations are
pi =3.14f;
do =20.22d;
a=’v’;
You can combine variable declaration and initialization.
 



Example-

int a=2,b=4,c=6;
float pi=3.14f;
double do=20.22d;
char a=’v’;

Types Of variable in Java- There are three types of variable in java.
1). Local variable- Local Variables are a variable that are declared inside the body of a method.
2). Instance Variable- Instance variables are defined without the STATIC keyword .They are defined Outside a method declaration. They are Object specific and are known as instance variables.
3). Static Variable- Static variables are initialized only once, at the start of the program execution. These variables should be initialized first, before the initialization of any instance variables.

Data Types in Java- Data types classify the different values to be stored in the variable. In java, there are two types of data types:

1). Primitive Data Types
2). Non-primitive Data Types
Primitive Data Types are predefined and available within the Java language. Primitive values do not share state with other primitive values.

There are 8 primitive types: byte, short, int, long, char, float, double, and boolean Integer data types
byte (1 byte)
short (2 bytes)
int (4 bytes)
long (8 bytes)


Floating Data Type-
float (4 bytes)
double (8 bytes)
Textual Data Type-
char (2 bytes)
Logical-
boolean (1 byte) (true/false
Java Data Types-

Java Variable Type Conversion & Type Casting
A variable of one type can receive the value of another type. Here there are 2 cases -
Case 1). Variable of smaller capacity is be assigned to another variable of bigger capacity.
This process is Automatic, and non-explicit is known as Conversion

Case 2)- Variable of larger capacity is be assigned to another variable of smaller capacity
In such cases, you have to explicitly specify the type cast operator. This process is known as Type Casting.

In case, you do not specify a type cast operator; the compiler gives an error. Since this rule is enforced by the compiler, it makes the programmer aware that the conversion he is about to do may cause some loss in data and prevents accidental losses.

Cheers Friends :)

Java Opps Concept

Hi Guys, In this post I'll share some Basic Opps Concepts.which will very help full for beginners.
Gys be ready to implement those concepts in your system after getting boost up .




Object Oriented Programming is a programming concept that works on the principle that objects are the most important part of your program. It allows users create the objects that they want and then create methods to handle those objects. Manipulating these objects to get results is the goal of Object Oriented Programming.


Object Oriented Programming popularly known as OOP, is used in a modern programming language like Java

Core Building Blocks of OPPS - There are 10 Pillars of OPPS which are explained briefly below.

1) Class- The class is a group of similar entities. It is only an logical component and not the physical entity. For example, if you had a class called “Expensive Cars” it could have objects like Mercedes, BMW, Toyota, etc. Its properties(data) can be price or speed of these cars. While the methods may be performed with these cars are driving, reverse, braking etc.

2) Object- An object can be defined as an instance of a class, and there can be multiple instances of a class in a program. An Object contains both the data and the function, which operates on the data. For example - chair, bike, marker, pen, table, car, etc.

3) Inheritance-computer programs are designed in such a way where everything is an object that interact with one another. Inheritance is one such concept where the properties of one class can be inherited by the other. It helps to reuse the code and establish a relationship between different classes.
As we can see in the image, a child inherits the properties from his father. Similarly, in Java, there are two classes:
1. Parent class ( Super or Base class)
2. Child class (Subclass or Derived class )
A class which inherits the properties is known as Child Class whereas a class whose properties are inherited is known as Parent class.
Inheritance is further classified into 4 types:
So let’s begin with the first type of inheritance i.e. Single Inheritance:
1). Single Inheritance- In single inheritance, one class inherits the properties of another. It enables a derived class to inherit the properties and behavior from a single parent class. This will in turn enable code re usability as well as add new features to the existing code.

Here, Class A is your parent class and Class B is your child class which inherits the properties and behavior of the parent class.
Let’s see the syntax for single inheritance:
Class A
{
---
}
Class B extends A {
---
}

2). Multilevel Inheritance- When a class is derived from a class which is also derived from another class, i.e. a class having more than one parent class but at different levels, such type of inheritance is called Multilevel Inheritance.
If we talk about the flowchart, class B inherits the properties and behavior of class A and class C inherits the properties of class B. Here A is the parent class for B and class B is the parent class for C. So in this case class C implicitly inherits the properties and methods of class A along with Class B. That’s what is multilevel inheritance.

Let’s see the syntax for multilevel inheritance in Java:
Class A{
---
}
Class B extends A{
---
}
Class C extends B{
---
}

3). Hierarchical Inheritance- When a class has more than one child classes (sub classes) or in other words, more than one child classes have the same parent class, then such kind of inheritance is known as hierarchical.

If we talk about the flowchart, Class B and C are the child classes which are inheriting from the parent class i.e Class A.
Let’s see the syntax for hierarchical inheritance in Java:
Class A{
---
}
Class B extends A{
---
}
Class C extends A{
---
}
4). Hybrid Inheritance- Hybrid inheritance is a combination of multiple inheritance and multilevel inheritance. Since multiple inheritance is not supported in Java as it leads to ambiguity, so this type of inheritance can only be achieved through the use of the interfaces. 

If we talk about the flowchart, class A is a parent class for class B and C, whereas Class B and C are the parent class of D which is the only child class of B and C.

Now we have learned about inheritance and their different types. Let’s switch to another object oriented programming concept i.e Encapsulation.

4) Encapsulation- Encapsulation is a mechanism where you bind your data and code together as a single unit. It also means to hide your data in order to make it safe from any modification. What does this mean? The best way to understand encapsulation is to look at the example of a medical capsule, where the drug is always safe inside the capsule. Similarly, through encapsulation the methods and variables of a class are well hidden and safe.

We can achieve encapsulation in Java by:
Declaring the variables of a class as private.
Providing public setter and getter methods to modify and view the variables values.
Let us look at the code below to get a better understanding of encapsulation:
public class Employee {
 private String name;
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public static void main(String[] args) {
 }
}
Let us try to understand the above code. I have created a class Employee which has a private variable name. We have then created a getter and setter methods through which we can get and set the name of an employee. Through these methods, any class which wishes to access the name variable has to do it using these getter and setter methods.

5) Abstraction- Abstraction refers to the quality of dealing with ideas rather than events. It basically deals with hiding the details and showing the essential things to the user. If you look at the image here, whenever we get a call, we get an option to either pick it up or just reject it. But in reality, there is a lot of code that runs in the background. So you don’t know the internal processing of how a call is generated, that’s the beauty of abstraction. Therefore, abstraction helps to reduce complexity. You can achieve abstraction in two ways:
a) Abstract Class
b) Interface

Let’s understand these concepts in more detail.

Abstract class: Abstract class in Java contains the ‘abstract’ keyword. Now what does the abstract keyword mean? If a class is declared abstract, it cannot be instantiated, which means you cannot create an object of an abstract class. Also, an abstract class can contain abstract as well as concrete methods.
Note: You can achieve 0-100% abstraction using abstract class.

To use an abstract class, you have to inherit it from another class where you have to provide implementations for the abstract methods there itself, else it will also become an abstract class.

Let’s look at the syntax of an abstract class:

Abstract class Mobile {   // abstract class mobile
Abstract void run();      // abstract method

Interface- Interface in Java is a blueprint of a class or you can say it is a collection of abstract methods and static constants. In an interface, each method is public and abstract but it does not contain any constructor. Along with abstraction, interface also helps to achieve multiple inheritance in Java.
Note: You can achieve 100% abstraction using interfaces.
So an interface basically is a group of related methods with empty bodies. Let us understand interfaces better by taking an example of a ‘ParentCar’ interface with its related methods.

public interface ParentCar {
public void changeGear( int newValue);
public void speedUp(int increment);
public void applyBrakes(int decrement);
}
These methods need be present for every car, right? But their working is going to be different.

Let’s say you are working with manual car, there you have to increment the gear one by one, but if you are working with an automatic car, that time your system decides how to change gear with respect to speed. Therefore, not all my subclasses have the same logic written for change gear. The same case is for speedup, now let’s say when you press an accelerator, it speeds up at the rate of 10kms or 15kms. But suppose, someone else is driving a super car, where it increment by 30kms or 50kms. Again the logic varies. Similarly for applybrakes, where one person may have powerful brakes, other may not.

Since all the functionalities are common with all my subclasses, I have created an interface ‘ParentCar’ where all the functions are present. After that, I will create a child class which implements this interface, where the definition to all these method varies.

Next, let’s look into the functionality as to how you can implement this interface.
So to implement this interface, the name of your class would change to any particular brand  of a Car, let’s say I’ll take an “Audi”. To implement the class interface, I will use the ‘implement’ keyword as seen below:
public class Audi implements ParentCar {
int speed=0;
int gear=1;
public void changeGear( int value){
gear=value;
}
public void speedUp( int increment)
{
speed=speed+increment;
}
public void applyBrakes(int decrement)
{
speed=speed-decrement;
}
void printStates(){
System.out.println("speed:"+speed+"gear:"+gear);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Audi A6= new Audi();
A6.speedUp(50);
A6.printStates();
A6.changeGear(4);
A6.SpeedUp(100);
A6.printStates();
}
}
Here as you can see, I have provided functionalities to the different methods I have declared in my interface class. Implementing an interface allows a class to become more formal about the behavior it promises to provide. You can create another class as well, say for example BMW class which can inherit the same interface ‘car’ with different functionalities.

6). Polymorphism- Polymorphism means taking many forms, where ‘poly’ means many and ‘morph’ means forms. It is the ability of a variable, function or object to take on multiple forms. In other words, polymorphism allows you define one interface or method and have multiple implementations.

Let’s understand this by taking a real-life example and how this concept fits into Object oriented programming.
Let’s consider this real world scenario in cricket, we know that there are different types of bowlers i.e. Fast bowlers, Medium pace bowlers and spinners. As you can see in the above figure, there is a parent class- BowlerClass and it has three child classes: FastPacer, MediumPacer and Spinner. Bowler class has bowlingMethod() where all the child classes are inheriting this method. As we all know that a fast bowler will going to bowl differently as compared to medium pacer and spinner in terms of bowling speed, long run up and way of bowling, etc. Similarly a medium pacer’s implementation of bowlingMethod() is also going to be different as compared to other bowlers. And same happens with spinner class.
The point of above discussion is simply that a same name tends to multiple forms. All the three classes above inherited the bowlingMethod() but their implementation is totally different from one another.

Polymorphism in Java is of two types:

Run time polymorphism
Compile time polymorphism
Run time polymorphism: In Java, runtime polymorphism refers to a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this, a reference variable is used to call an overridden method of a superclass at run time. Method overriding is an example of run time polymorphism. Let us look  the following code to understand how the method overriding works:

public Class BowlerClass{
void bowlingMethod()
{
System.out.println(" bowler ");
}
public Class FastPacer{
void bowlingMethod()
{
System.out.println(" fast bowler ");
}
Public static void main(String[] args)
{
FastPacer obj= new FastPacer();
obj.bowlingMethod();
}
}
Compile time polymorphism: In Java, compile time polymorphism refers to a process in which a call to an overloaded method is resolved at compile time rather than at run time. Method overloading is an example of compile time polymorphism. Method Overloading is a feature that allows a class to have two or more methods having the same name but the arguments passed to the methods are different. Unlike method overriding, arguments can differ in:

Number of parameters passed to a method
Datatype of parameters
Sequence of datatypes when passed to a method.
Let us look at the following code to understand how the method overloading works:

class Adder {
Static int add(int a, int b)
{
return a+b;
}
static double add( double a, double b)
{
return a+b;
}

public static void main(String args[])
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}

7) Association- Association is a relationship between two objects. It defines the diversity between objects. In this OOP concept, all object have their separate lifecycle, and there is no owner. For example, many students can associate with one teacher while one student can also associate with multiple teachers.

8) Aggregation- In this technique, all objects have their separate lifecycle. However, there is ownership such that child object can’t belong to another parent object. For example consider class/objects department and teacher. Here, a single teacher can’t belong to multiple departments, but even if we delete the department, the teacher object will never be destroyed.

9) Composition-A composition is a specialized form of Aggregation. It is also called "death" relationship. Child objects do not have their lifecycle so when parent object deletes all child object will also delete automatically. For that, let’s take an example of House and rooms. Any house can have several rooms. One room can’t become part of two different houses. So, if you delete the house room will also be deleted.

Advantages of OOPS-
OOP offers easy to understand and a clear modular structure for programs.
Objects created for Object-Oriented Programs can be reused in other programs. Thus it saves significant development cost.
Large programs are difficult to write, but if the development and designing team follow OOPS concept then they can better design with minimum flaws.
It also enhances program modularity because every object exists independently.

Comparison of OOPS with other programming styles with help of an Example -
Let's understand with example how OOPs is different than other programming approaches.
Programming languages can be classified into 3 primary types

A). Unstructured Programming Languages- The most primitive of all programming languages having sequentially flow of control. Code is repeated through out the program
B). Structured Programming Languages- Has non-sequentially flow of control. Use of functions allows for re-use of code.
C). Object Oriented Programming: Combines Data & Action Together.

Let's understand these 3 types with an example.
Suppose you want to create a Banking Software with functions like

1. Deposit
2. Withdraw
3. Show Balance

Unstructured Programming Languages-
The earliest of all programming language were unstructured programming language. A very elementary code of banking application in unstructured Programming language will have two variables of one account number and another for account balance
balance
int account_number=20;
int account_balance=100;
Suppose deposit of 100 dollars is made.
account_balance=account_balance+100
Next you need to display account balance.
printf(“Account Number=%d,account_number)
printf(“Account Balance=%d,account_balance)
Now the amount of 50 dollars is withdrawn.
account_balance=account_blance-50
Again, you need to display the account balance.
printf(“Account Number=%d,account_number)
printf(“Account Balance=%d,account_balance)
For any further deposit or withdrawal operation – you will code repeat the same lines again and again.
Structured Programming- With the arrival of Structured programming repeated lines on the code were put into structures such as functions or methods. Whenever needed, a simple call to the function is made.
Object-Oriented Programming- In our program, we are dealing with data or performing specific operations on the data.
In fact, having data and performing certain operation on that data is very basic characteristic in any software program.
Experts in Software Programming thought of combining the Data and Operations. Therefore, the birth of Object Oriented Programming which is commonly called OOPS.
The same code in OOPS will have same data and some action performed on that data.
Class Account{
 int account_number;
 int account_balance;
public void showdata(){
 system.out.println(“Account Number”+account_number)
 system.outprintln(“Account Balance”+ account_balance)
}
}
By combining data and action, we will get many advantages over structural programming viz,

Abstraction
Encapsulation
Inheritance
Polymorphism

Cheers Guys :) Happy Deewali.

Frequently Asked JAVA Interview Question and Answer Part 5

Hi Guys, In this post I'll share some interview questions and answers which i have faced or asked in interview panel.you can read my previous post related to JAVA QA JAVA QA PART 1 , JAVA QA PART 2 , JAVA QA PART 3 and JAVA QA PART 4 .


Q1. When a lot of changes are required in data, which one should be a preference to be used? String or StringBuffer?
Ans: Since StringBuffers are dynamic in nature and we can change the values of StringBuffer objects unlike String which is immutable, it’s always a good choice to use StringBuffer when data is being changed too much. If we use String in such a case, for every data change a new String object will be created which will be an extra overhead.
Q2. What’s the purpose of using Break in each case of Switch Statement?
Ans: Break is used after each case (except the last one) in a switch so that code breaks after the valid case and doesn’t flow in the proceeding cases too.
If break isn’t used after each case, all cases after the valid case also get executed resulting in wrong results.
Q3.  How garbage collection is done in Java?
Ans: In java, when an object is not referenced any more, garbage collection takes place and the object is destroyed automatically. For automatic garbage collection java calls either System.gc() method or Runtime.gc() method.
Q4. How we can execute any code even before main method?
Ans: If we want to execute any statements before even creation of objects at load time of class, we can use a static block of code in the class. Any statements inside this static block of code will get executed once at the time of loading the class even before creation of objects in the main method.
Q5. Can a class be a super class and a sub-class at the same time? Give example.
Ans: If there is a hierarchy of inheritance used, a class can be a super class for another class and a sub-class for another one at the same time.
In the example below, continent class is sub-class of world class and it’s super class of country class.

public class world {

..........

}

public class continenet extends world {

............
}
public class country extends continent {
......................
}


Q6.  How objects of a class are created if no constructor is defined in the class?
Ans: Even if no explicit constructor is defined in a java class, objects get created successfully as a default  constructor is implicitly used for object creation. This constructor has no parameters.
Q7.  In multi-threading how can we ensure that a resource isn’t used by multiple threads simultaneously?
Ans: In multi-threading, access to the resources which are shared among multiple threads can be controlled by using the concept of synchronization. Using synchronized keyword, we can ensure that only one thread can use shared resource at a time and others can get control of the resource only once it has become free from the other one using it.
Q8. Can we call the constructor of a class more than once for an object?
Ans:  Constructor is called automatically when we create an object using new keyword. It’s called only once for an object at the time of object creation and hence, we can’t invoke the constructor again for an object after its creation.
Q9. There are two classes named classA and classB. Both classes are in the same package. Can a private member of classA can be accessed by an object of classB?
Ans: Private members of a class aren’t accessible outside the scope of that class and any other class even in the same package can’t access them.
Q10. Can we have two methods in a class with the same name?
Ans: We can define two methods in a class with the same name but with different number/type of parameters. Which method is to get invoked will depend upon the parameters passed.
For example in the class below we have two print methods with same name but different parameters. Depending upon the parameters, appropriate one will be called:
public class methodExample {
 public void print() {
 system.out.println("Print method without parameters.");
 }
 public void print(String name) {
 system.out.println("Print method with parameter");
 }
 public static void main(String args[]) {
 methodExample obj1= new methodExample();
 obj1.print();
 obj1.print("xx");
 }
 }
Q11. How can we make copy of a java object?
Ans: We can use the concept of cloning to create copy of an object. Using clone, we create copies with the actual state of an object.
Clone() is a method of Cloneable interface and hence, Cloneable interface needs to be implemented for making object copies.
Q12. What’s the benefit of using inheritance?
Ans: Key benefit of using inheritance is reusability of code as inheritance enables sub-classes to reuse the code of its super class. Polymorphism (Extensibility ) is another great benefit which allow new functionality to be introduced without effecting existing derived classes.

Q13.  What’s the default access specifier for variables and methods of a class?
Ans: Default access specifier for variables and method is package protected i.e variables and class is available to any other class but in the same package,not outside the package.
Q14. Give an example of use of Pointers in Java class.
Ans: There are no pointers in Java. So we can’t use concept of pointers in Java.
Q15.  How can we restrict inheritance for a class so that no class can be inherited from it?
Ans: If we want a class not to be extended further by any class, we can use the keyword Final with the class name.
In the following example, Stone class is Final and can’t be extend
public Final Class Stone {
 // Class methods and Variables
 }
Q16. What’s the access scope of Protected Access specifier?
Ans: When a method or a variable is declared with Protected access specifier, it becomes accessible in the same class,any other class of the same package as well as a sub-class.
Access Levels
MODIFIER
CLASS
PACKAGE
SUBCLASS
WORLD
public
Y
Y
Y
Y
protected
Y
Y
Y
N
no modifier
Y
Y
N
N
private
Y
N
N
N
Q17. What’s difference between Stack and Queue?
Ans: Stack and Queue both are used as placeholder for a collection of data. The primary difference between a stack and a queue is that stack is based on Last in First out (LIFO) principle while a queue is based on FIFO (First In First Out) principle.
Q18. In java, how we can disallow serialization of variables?
Ans: If we want certain variables of a class not to be serialized, we can use the keyword transient while declaring them. For example, the variable trans_var below is a transient variable and can’t be serialized:
public class transientExample {
private transient trans_var;
// rest of the code
}
Q19.  How can we use primitive data types as objects?
Ans: Primitive data types like int can be handled as objects by the use of their respective wrapper classes. For example, Integer is a wrapper class for primitive data type int. We can apply different methods to a wrapper class, just like any other object.
Q20. Which types of exceptions are caught at compile time?
Ans: Checked exceptions can be caught at the time of program compilation. Checked exceptions must be handled by using try catch block in the code in order to successfully compile the code.
Q21. Describe different states of a thread.
Ans: A thread in Java can be in either of the following states:
·           Ready: When a thread is created, it’s in Ready state.
·           Running: A thread currently being executed is in running state.
·           Waiting: A thread waiting for another thread to free certain resources is in waiting state.
·           Dead: A thread which has gone dead after execution is in dead state.
Q22. Can we use a default constructor of a class even if an explicit constructor is defined?
Ans: Java provides a default no argument constructor if no explicit constructor is defined in a Java class. But if an explicit constructor has been defined, default constructor can’t be invoked and developer can use only those constructors which are defined in the class.
Q23. Can we override a method by using same method name and arguments but different return types?
Ans: The basic condition of method overriding is that method name, arguments as well as return type must be exactly same as is that of the method being overridden.  Hence using a different return type doesn’t override a method.
Q24.What will be the output of following piece of code?
public class operatorExample {
public static void main(String args[]) {
int x=4;
system.out.println(x++);
}
}
Ans: In this case postfix ++ operator is used which first returns the value and then increments. Hence it’s output will be 4.
Q25. A person says that he compiled a java class successfully without even having a main method in it? Is it possible?
Ans: main method is an entry point of Java class and is required for execution of the program however; a class gets compiled successfully even if it doesn’t have a main method. It can’t be run though.

Cheers :)

Eclipse With Python

Hi Guys, Today i'll share how to start python project in eclipse IDE. to start Py development in eclipse we need to add Py Dev plugi...