Showing posts with the label Java Stuff

What is Encapsulation in Java?

Encapsulation is a mechanism of binding code and data together in a single unit. Let’s take an example of Capsule. Different powdered or liquid medicines are encapsulated inside a capsule. Likewise in encapsulation, all the methods and variables are wrapped together in a single class. However if we setup public getter and setter methods to update (for example  void setAge(int age) )and read (for example   int getAge() ) the private data fields then the outside class can access those private data fields via public methods. This way data can only be accessed by public methods thus making the private fields and their implementation hidden for outside classes. That’s why encapsulation is known as  data hiding.  Lets see an example to understand this concept better. Example of Encapsulation: /* Create a class */ public class Encapsulation { private String name ; private int age ; public int getAge () { return age ; } publ

What are Java Data Types and Variables?

What is a Java Variable? A variable can be called as a container which holds some value in a java program.  Variable has assigned a data type which defines what type of value variable can hold. Variable has a name which locates to the memory. If you want to use variable in a program, there are two steps associated with it you have to perform: Variable Declaration Variable Initialization i. Variable Declaration While declaring a variable you have to assign data type with variable name. Variable name has to be unique. Example:  String employee; ii. Variable Initialization It means assigning a value to the declared variable. Example:  employee = "John" Above two steps (declaration and initialization) can also be joined together in one single step. Example:  String employee = "John"; Let's explain above example,  ' String ' is data type ' employee ' is name of variable " John " is value assigned to variable named employee. Types of Variable