This section will describe the basic things for understanding the programming.
1) Java OOPs Concepts
OOP stands for Object Oriented Programming. It is a methodology that is use to developed softwares. It provides important concepts like Object , Class , Inheritance , Abstraction , Polymorphism and Encapsulation which simplifies the software development and maintenance and helps to create a program using classes and objects.Simula and Smalltalk are considered as the first object oriented programming languages where everything is represented as Object.
There are following keywords of OOP:
1)Object Any entity that has state and behavior is known as Object.It can be physical and logical. It is an instance of class. For example chair , bike , fan , pen , keyboard etc. 2) Class Class is a template for creating objects.It tells the virtual machine how to make an object of that particular type.Each object is made from that class can have its own values for the instance variable of that class. |
-
Modifiers:-
-
Access Modifiers:- There are four type of access modifiers
-
public Modifiers:-public member and class can be accessible from anywhere.
-
default Modifiers:-Any variable or class will be consider as having default modifier if you will not declare any modifier. default modifier can be accessible within the package only. It also means that you can access class members by creating its object within the package(weather it is method or variable).
-
private Modifiers:- private member can be accessible within the class. You will not able to create even object of a class If you declare its constructor as private. A class can not be private except methods , variable and nested class.
-
protected Modifiers:- protected members can be accessible through Inheritance only. A class can not be protected except methods , variable and nested class.
-
public Modifiers:-public member and class can be accessible from anywhere.
-
Non-Access Modifiers:- There are following type of non access modifiers
-
final Modifiers:- You can declare a variable , method and class as final. It can be initialized only once. It can be initialized only at the creation time or in the constructor. If you declare a variable as final and static both then you can initialized it in the static block only. You can not do the following change in final members:
- You can not change the value of the final variable
- You can not override the final method
- You can not inherit the final class
-
static Modifiers:- You can declare a class variable , a class method , block and nested class as static. Static members belongs to the class not to the instance of the object. It gets memory only once in class area at the time of class loading. Only a static member can access the static member of a class without any instance.
-
abstract Modifiers:- You can declare a variable , method and class as abstract. Only a abstract class can have abstract variable and method. abstract class can not be instantiated. abstract class need to extend and implemented its unimplemented methods.
-
synchronized Modifiers:- It is basically use to lock a thread. It is use to lock a object, method(for both static and non-static) or a block.
-
transient Modifiers:- This keyword basically used in serialization. If you declared a variable as transient, It will not be serialized.
-
final Modifiers:- You can declare a variable , method and class as final. It can be initialized only once. It can be initialized only at the creation time or in the constructor. If you declare a variable as final and static both then you can initialized it in the static block only. You can not do the following change in final members:
-
Access Modifiers:- There are four type of access modifiers
-
Data-Type:-The nature of data is known as Data type.In java there are two type of data types.
1) primitive data type such as Boolean and Numeric.
2) non primitive data type such as String , Array etc
Data Type Default Value Default Size boolean false 1 bit char '\u0000' 2 byte byte 0 1 byte short 0 2 byte int 0 4 byte long 0L 8 byte float 0.0f 4 byte double 0.0d 8 byte
-
Variables:-It is a member of class or method which is reserved area allocated in memory.Syntax:
Access Modifier Data-Type Variable-Name;
or
Access Modifier Data-Type Variable-Name=Initialization;
- local variable
A variable that is declared inside a method is called local Variable. - instance variable
A variable that is declared inside the class but outside the method is known as instance variable. It is not declared as static. - static variable
A method which is declared as static is known as static variable. It can't be local.
You can use following rules for creating a name:
- It must start with a letter, underscore(_), or dollar sign($).
- After the first character You can use number as well but You can't start with a number.
- It should not be java reserved word
- local variable
-
Operator:-It is a special symbol that is used to perform operations. There are many type of operator in the java such as unary operator , arithmetic operator , relational operator , shift operator , bitwise operator, ternary operator and assignment operator.
Operators Precedence Description postfix exp++ exp-- unary ++exp --exp +exp -exp ~ ! multiplicative * / % additive + - shift << >> >>> relational < > <= >= instanceof equality == != bitwise AND & bitwise exclusive OR ^ bitwise inclusive OR | Return true only if one operand is true from two or more operands. Logical AND && logical OR | | ternary ? : (condition) ? (if true) : (if false) assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
-
Methods:-It is a member of class which execute a block/group of code.Syntax:
Access Modifier return-Type method-Name(arguments)
{
}
When one object acquires all the properties and behavior of parent object that is known as Inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
4) Abstraction
Hiding internal details and showing functionality only is known as abstraction.For example cell phone , we don't know the internal processing. In java we use abstract class and interface to achieve abstraction.
5) Polymorphism
When one task is performed by different ways that is known as Polymorphism. In java we use method overriding and method overloading to achieve polymorphism Another example can be to speak something example cat speak meaw , dog barks woof etc.To draw something example shape or rectangle etc.
6) Encapsulation
Binding or wrapping code and data together into a single unit is known as Encapsulation . For example capsule, it is wrapped with different medicines. A java class is an example of Encapsulation. Java bean is fully encapsulated class because all the data members are private here.
2) Advantages of OOPs
- OOPs makes development and maintenance easier.
- OOPs provides data hiding.
- OOPs provides ability to simulate real world event much more effectively.
3) Object Oriented Programming Vs Object Based Programming
Object Based Programming language follows all the features of OOPs except Inheritance. JavaScript and VBScript are the examples of Object Based Programming language.4) Conditional Branching
The if statement and the switch statement are types of conditional/decision controls that allow your program to behave differently depending on the result of a logical test.When you use decision statements in your program, you're asking the program to evaluate a given expression to determine which course of action to take.1) if-else Branching:
The expression in parentheses must evaluate to (a boolean) true or false.Typically you're testing something to see if it's true, and then running a code block (one or more statements) if it is true, and (optionally) another block of code if it isn't.The basic format of an if statement is as follows:
if (booleanExpression)
{
System.out.println("If boolean Expression is true");
}
else
{
System.out.println("If boolean Expression is false");
}
The else block is optional, so you can also use the following:
if (x > 3)
{
y = 2;
}
z += 8;
a = y + x;
The preceding code will assign 2 to y if the test succeeds (meaning x really is greater than 3), but the other two lines will execute regardless. Even the curly braces are optional if you have only one statement to execute within the body of the conditional block. The following code example is legal (although not recommended for readability):
if (x > 3) // bad practice, but seen on the exam
y = 2;
z += 8;
a = y + x;
You might have a need to nest if-else statements (although, again, it's not recommended for readability, so nested if tests should be kept to a minimum). You can set up an if-else statement to test for multiple conditions. The following example uses two conditions so that if the first test fails, we want to perform a second test before deciding what to do:
if (price < 300)
{
buyProduct();
}
else
{
if (price < 400)
{
getApproval();
}
else
{
dontBuyProduct();
}
}
2) switch Statements:
It can be very confusing to read a program if we use multiple elseifs statements .A way to simulate the use of multiple if statements is with the switch statement.A switch's expression must evaluate to a char, byte, short, int, or, as of Java 6, an enum. That means if you're not using an enum, only variables and values that can be automatically promoted (in other words, implicitly cast) to an int are acceptable. You won't be able to compile if you use anything else, including the remaining numeric types of long, float, and double.The general form of the switch statement is:
switch (expression)
{
case constant1: code block break;
case constant2: code block break;
default: code block
}
when the program encounters the keyword break during the execution of a switch statement, execution will immediately move out of the switch block to the next statement after the switch. If break is omitted,the program just keeps executing the remaining case blocks until either a break is found or the switch statement ends.
Examples | |
int x = 3; switch (x) { case 1: System.out.println("x is equal to 1"); break; case 2: System.out.println("x is equal to 2"); break; case 3: System.out.println("x is equal to 3"); break; default: System.out.println("Still no idea what x is"); } |
Break and Fall-Through in switch Blocks int x = 1; switch(x) { case 1: System.out.println("x is one"); case 2: System.out.println("x is two"); case 3: System.out.println("x is three"); } System.out.println("out of the switch"); |
result: x is equal to 3 |
result: x is one x is two x is three out of the switch |
5) Looping
Java loops come in three flavors: while, do, and for (and as of Java 6, the for loop has two variations). All three let you repeat a block of code as long as some condition is true, or for a specific number of iterations. You're probably familiar with loops from other languages, so even if you're somewhat new to Java, these won't be a problem to learn.Instead of having three components, the enhanced for has two.
Loop name | Syntax | Example |
while Loop The while loop is good for scenarios where you don't know how many times a block or statement should repeat, but you want to continue looping as long as some condition is true. |
while (expression) { // do stuff } |
int x = 2; while(x == 2) { System.out.println(x); ++x; } |
do Loop The do loop is similar to the while loop, except that the expression is not evaluated until after the do loop's code is executed. Therefore the code in a do loop is guaranteed to execute at least once. |
do { // do stuff } while (expression) |
int x = 2; do { System.out.println(x); ++x; } while(x == 2) |
for Loop The for loop is especially useful for flow control when you already know how many times you need to execute the statements in the loop's block. The for loop declaration has three main parts which are separated by semicolons, besides the body of the loop: 1)Initialization 2)Condition 3)Iteration The last thing to note is that all three sections of the for loop are independent of each other. The three expressions in the for statement don't need to operate on the same variables, although they typically do.But even the iterator expression, which many mistakenly call the "increment expression," doesn't need to increment or set anything; you can put in virtually any arbitrary code statements that you want to happen with each iteration of the loop. Look at the following: int b = 3; for (int a = 1; b != 1; System.out.println("iterate")) { b = b - a; } None of the three sections of the for declaration are required! The following example is perfectly legal (although not necessarily good practice): for( ; ; ) { System.out.println("Inside an endless loop"); } In the preceding example, all the declaration parts are left out so the for loop will act like an endless loop. It's important to know that with the absence of the initialization and increment sections, the loop will act like a while loop. The following example demonstrates how this is accomplished: int i = 0; for (;i<10 br="">{ i++; //do some other work }10> |
for (/*Initialization*/ ; /*Condition*/ ; /* Iteration */) { /* loop body */ } |
int [] a = {1,2,3,4}; for(int x = 0; x < a.length; x++) // basic for loop System.out.print(a[x]); import java.util.*; public class Pockets { public static void main(String[] args) { Pockets o = new Pockets(); HashSet //sets.add("Anish"); sets.add("Manish"); sets.add("Anish"); sets.add("Manisha"); Iterator itr; String s; for(itr=sets.iterator(); itr.hasNext();) { s=(String)itr.next(); System.out.println(s); } } } |
Enhanced for loop The enhanced for loop, new to Java 6, is a specialized for loop that simplifies looping through an array or a collection. | for(declaration : expression) { // Statements } |
int [] a = {1,2,3,4}; for(int n : a) // enhanced for loop System.out.print(n); |
6) The way Java works
1)Source Code We use java language to create a source code file. This file creates in Notepad and save with .java extension or by using either Netbean or Eclipse Application. 2)Compiler After creating the source code, we uses the java compiler.If there is not any error in the source code we'll get compiled code. 3)Compiled Code This is an file which will have .class extension. We will get it after compiling in the same directory in which source code is saved. 4)Virtual Machine You don't have a physical java virtual machine but all you have a virtual java machine ( implemented in software) running inside their electronic gadgets which translates the compiled bytecode into something the underlying platform understands, and runs your program. |