KEMBAR78
PPT ON JAVA AND UNDERSTANDING JAVA'S PRINCIPLES | PPTX
Operator in Java is a symbol which is used to perform operations.
Java provides a rich set of operators to manipulate variables. We can divide all
the Java operators into the following groups −
•Arithmetic Operators
•Relational Operators
•Bitwise Operators
•Logical Operators
•Assignment Operators
•Misc Operators
The Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that
they are used in algebra.
Operator Description Example
+ (Addition)
Adds values on either side of the operator.
A + B will give 30
- (Subtraction)
Subtracts right-hand operand from left-hand
operand.
A - B will give -10
* (Multiplication)
Multiplies values on either side of the operator.
A * B will give 200
/ (Division)
Divides left-hand operand by right-hand operand.
B / A will give 2
% (Modulus)
Divides left-hand operand by right-hand operand
and returns remainder.
B % A will give 0
++ (Increment)
Increases the value of operand by 1.
B++ gives 21
--- (Decrement)
Decreases the value of operand by 1.
B--- gives 19
Assume integer variable A holds 10 and variable B holds 20,
The Relational Operators
Operator Description Example
== (equal to)
Checks if the values of two operands are equal or
not, if yes then condition becomes true.
(A == B) is not true.
!= (not equal to)
Checks if the values of two operands are equal or
not, if values are not equal then condition
becomes true. (A != B) is true.
> (greater than)
Checks if the value of left operand is greater than
the value of right operand, if yes then condition
becomes true. (A > B) is not true.
< (less than)
Checks if the value of left operand is less than
the value of right operand, if yes then condition
becomes true. (A < B) is true.
>= (greater than or
equal to)
Checks if the value of left operand is greater than
or equal to the value of right operand, if yes then
condition becomes true. (A >= B) is not true.
<= (less than or equal
to)
Checks if the value of left operand is less than or
equal to the value of right operand, if yes then
condition becomes true. (A <= B) is true.
The Bitwise Operators
Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and
byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary
format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Operator Description Example
& (bitwise and)
Binary AND Operator copies a bit to the
result if it exists in both operands.
(A & B) will give 12 which is
0000 1100
| (bitwise or) Binary OR Operator copies a bit if it exists
in either operand.
(A | B) will give 61 which is
0011 1101
^ (bitwise XOR) Binary XOR Operator copies the bit if it is
set in one operand but not both.
(A ^ B) will give 49 which is
0011 0001
~ (bitwise
compliment)
Binary Ones Complement Operator is
unary and has the effect of 'flipping' bits.
(~A ) will give -61 which is
1100 0011 in 2's
complement form due to a
signed binary number.
<< (left shift)
Binary Left Shift Operator. The left
operands value is moved left by the
number of bits specified by the right
operand.
A << 2 will give 240 which
is 1111 0000
>> (right shift)
Binary Right Shift Operator. The left
operands value is moved right by the
number of bits specified by the right
operand.
A >> 2 will give 15 which is
1111
>>> (zero fill right
shift)
Shift right zero fill operator. The left
operands value is moved right by the
number of bits specified by the right
operand and shifted values are filled up
with zeros.
A >>>2 will give 15 which is
0000 1111
The Logical Operators
&& (logical and)
Called Logical AND operator. If
both the operands are non-zero,
then the condition becomes true.
(A && B) is false
|| (logical or)
Called Logical OR Operator. If any
of the two operands are non-zero,
then the condition becomes true.
(A || B) is true
! (logical not)
Called Logical NOT Operator. Use
to reverses the logical state of its
operand. If a condition is true then
Logical NOT operator will make
false. !(A && B) is true
The Assignment Operators
Operator Description Example
=
Simple assignment operator. Assigns values from right
side operands to left side operand.
C = A + B will assign value of A
+ B into C
+=
Add AND assignment operator. It adds right operand to
the left operand and assign the result to left operand. C += A is equivalent to C = C +
A
-=
Subtract AND assignment operator. It subtracts right
operand from the left operand and assign the result to
left operand.
C -= A is equivalent to C = C –
A
*=
Multiply AND assignment operator. It multiplies right
operand with the left operand and assign the result to
left operand.
C *= A is equivalent to C = C *
A
/= Divide AND assignment operator. It divides left
operand with the right operand and assign the result
to left operand.
C /= A is equivalent to C = C /
A
%=
Modulus AND assignment operator. It takes modulus
using two operands and assign the result to left
operand.
C %= A is equivalent to C = C
% A
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2
Category Operator Associativity
Postfix expression++ expression-- Left to right
Unary ++expression –-expression +expression –expression ~ ! Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift << >> >>> Left to right
Relational < > <= >= instanceof Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= ^= |= <<= >>= >>>= Right to left
Precedence of Java Operators
Java If Statement
The Java if statement is used to test the condition. It
checks boolean condition: true or false. There are various
types of if statement in Java.
•if statement
•if-else statement
•if-else-if ladder
•nested if statement
Java if Statement
The Java if statement tests the condition. It executes the if
block if condition is true.
class A {
public static void main(String[] args) {
int age=20;
if(age>18)
{
System.out.print("Age is greater than 18");
}
}
}
Java if-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is
true otherwise else block is executed.
public class A {
public static void main(String[] args) {
int number=13;
if(number%2==0){
System.out.println("even number");
}
else{
System.out.println("odd number");
}
}
}
Ternary Operator
We can also use ternary operator (? :) to perform the task of if...else statement. It is a
shorthand way to check the condition. If the condition is true, the result of ? is returned.
But, if the condition is false, the result of : is returned.
public class T {
public static void main(String[] args) {
int number=13;
//Using ternary operator
String output=(number%2==0)?"even number":"odd number";
System.out.println(output);
}
}
Java if-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements.
public class A {
public static void main(String[] args) {
int marks=65;
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
} }
Java Nested if statement
The nested if statement represents the if block within another if block. Here, the inner if
block condition executes only when outer if block condition is true.
public class A {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
}
}
}}
Java While Loop
While loop starts with the checking of condition. If it evaluated to true, then the loop body
statements are executed otherwise first statement following the loop is executed. For this
reason it is also called Entry control loop
while(condition){
//code to be executed
Incr. or decr. operator
}
class A {
public static void main(String[] args)
{
int i=1;
while(i<=10)
{
System.out.println(i);
i++;
}
}
}
Java Infinitive While Loop
If you pass true in the while loop, it will be infinitive while loop
while(true){
.
do while loop in java
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
class A1 {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
for loop
for loop provides a concise way of writing the loop structure. Unlike a while loop, a for
statement consumes the initialization, condition and increment/decrement in one line
thereby providing a shorter, easy to debug structure of looping.
for(initialization;condition;incr/decr)
Initialization: It is the initial condition which is executed once when the loop starts.
Here, we can initialize the variable, or we can use an already initialized variable. It is an
optional condition.
Condition: It is the second condition which is executed each time to test the condition
of the loop. It continues execution until the condition is false. It must return boolean
value either true or false.
Increment/Decrement: It increments or decrements the variable value.
class A
{
public static void main(String args[])
{
// for loop begins when x=2
// and runs till x <=4
for (int x = 2; x <= 4; x++)
System.out.println("Value of x:" + x);
}
}
Java Nested For Loop
If we have a for loop inside the another loop, it is known as nested for loop. The inner
loop executes completely whenever outer loop executes.
class A {
public static void main(String[] args) {
//loop of i
for(int i=1;i<=3;i++){
//loop of j
for(int j=1;j<=3;j++){
System.out.println(i+" "+j);
}//end of i
}//end of j
}
}
Java for-each Loop
class A {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
System.out.println (String.format("%.2f", a));
Java switch Statement
In Java, we have used the if..else if ladder to execute a block of code among multiple
blocks. However, the syntax of if...else...if ladders are too long.
Hence, we can use the switch statement as a substitute for long if...else...if ladders. The
use of switch statements makes our code more readable.
What is a string
• A sequence of characters
• Representing alphanumeric data.
• Defined in the java.lang.String class
• String is a class and objects of String type are
reference variables.
Making a string
• Declared as a typical object would be.
By new keyword
• String s= new String(“Hello”)
String Literal
Java String literal is created by using double quotes.
String s = “Hello”
String s1=“Welcome”
String s2=“Welcome”
Immutability
• Once created, a string cannot be changed: none of its
methods changes the string.
• Such objects are called immutable.
• Immutable objects are convenient because several
references can point to the same object safely: there
is no danger of changing an object through one
reference without the others being aware of the
change.
Why string objects are immutable in java?
Advantages Of Immutability
Uses less memory.
word1
OK
Less efficient:
wastes memory
“Java"
“Java"
“Java"
word2
word1
word2
Disadvantages of Immutability
Less efficient — you need to create a new string and throw
away the old one even for small changes.
word “java"
“Java"
Concatenating String
There are 2 methods to concatenate two or more string.
1) Using concat() method
Concat() method is used to add two or more string into a single string object. It is string
class method and returns a string object.
2) Using + operator
Java uses "+" operator to concatenate two string objects into single one. It can also
concatenate numeric value with string object.
String Comparison
To compare string objects, Java provides methods and operators both. So we can compare
string in following three ways.
Using equals() method
equals() method compares two strings for equality, It compares the content of the strings.
It will return true if string matches, else returns false.
Using == operator
The double equal (==) operator compares two object references to check whether they
refer to same instance. This also, will return true on successful match else returns false.
By compareTo() method
String compareTo() method compares values and returns an integer value which tells if the
string compared is less than, equal to or greater than the other string. It compares the
String based on natural ordering i.e alphabetically.
Java String charAt() method
The string charAt() method returns a character at specified index.
Java String length() method
The string length() method returns length of the string.
Java String valueOf() method
The string valueOf() method coverts given type such as int, long, float, double, boolean,
char and char array into string.
Java String replace() method
The string replace() method replaces all occurrence of first sequence of character with
second sequence of character.
Java String toUpperCase() and toLowerCase() method
The java string toUpperCase() method converts this string into uppercase letter and string
toLowerCase() method into lowercase letter.
Java String trim() method
The string trim() method eliminates white spaces before and after string.
String search:
indexOf() Method
int indexOf(int ch):
It returns the index of the first occurrence of character ch in a given String.
int indexOf(int ch, int fromIndex):
It returns the index of first occurrence of character ch in the given string after the
specified index “fromIndex”. For example, if the indexOf() method is called like this
str.indexOf(‘A’, 20) then it would start looking for the character ‘A’ in string str after
the index 20.
int indexOf(String str):
Returns the index of string str in a particular String.
int indexOf(String str, int fromIndex):
Returns the index of string str in the given string after the specified index
“fromIndex”.
* returns -1 if the specified char/substring is not found in the particular String.
StringBuffer class:
Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class
in java is same as String class except it is mutable i.e. it can be changed.
StringBuffer()
creates an empty string buffer with the initial capacity of 16.
StringBuffer(String str)
creates a string buffer with the specified string.
StringBuffer(int capacity)
creates an empty string buffer with the specified capacity as length.
1) StringBuffer append() method
The append() method concatenates the given argument with this string.
2) StringBuffer insert() method
The insert() method inserts the given string with this string at the given position.
3) StringBuffer replace() method
The replace() method replaces the given string from the specified beginIndex and
endIndex.
4) StringBuffer delete() method
The delete() method of StringBuffer class deletes the string from the specified beginIndex
to endIndex.
5) StringBuffer reverse() method
The reverse() method of StringBuffer class reverses the current string.
6) StringBuffer capacity() method
The capacity() method of StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current
capacity is 16, it will be (16*2)+2=34.
Java Package
Package is a collection of related classes. Java uses package to group related classes,
interfaces and sub-packages.
We can assume package as a folder or a directory that is used to store similar files.
Types Of Package
Package can be built-in and user-defined
Built-in Package: math, util, lang, i/o etc are the example of built-in packages.
User-defined-package: Java package created by user to categorize their project's classes
and interface are known as user-defined packages.
How to Create a Package
Use package command followed by name of the package as the first statement in java
source file.
Package p;
•Package statement must be first statement in the program even before the
import statement.
•A package is always defined as a separate folder having the same name as
the package name.
•Store all the classes in that package folder.
•All classes of the package which we wish to access outside the package must
be declared public.
How to import Java Package
There are 3 different ways to refer to any class that is present in a different package:
•without import the package
•import package with specified class
•import package with all classes
Inheritance in Java
It is the mechanism in java by which one class is allow to inherit the features(fields and
methods) of another class.
Important terminology:
Super Class: The class whose features are inherited is known as super class(or a base
class or a parent class).
Sub Class: The class that inherits the other class is known as sub class(or a derived class,
extended class, or child class). The subclass can add its own fields and methods in
addition to the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to
create a new class and there is already a class that includes some of the code that we
want, we can derive our new class from the existing class. By doing this, we are reusing
the fields and methods of the existing class.
Class b extends A
Single Inheritance : In single inheritance, subclasses inherit the features of one
superclass.
Multilevel Inheritance : In Multilevel Inheritance, a derived class will be inheriting a base
class and as well as the derived class also act as the base class to other class. In below
image, the class A serves as a base class for the derived class B, which in turn serves as a
base class for the derived class C. In Java, a class cannot directly access the grandparent’s
members.
Hierarchical Inheritance, one class serves as a superclass (base class) for more than one
sub class.In below image, the class A serves as a base class for the derived class B,C and
D.
Class b extends c,d
Print()- function
class c
Print()- function
class d
U-object class b
U.Print();
Method Overloading in JAVA
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
method overloading in Java is a feature that allows a class to have more than one
method with the same name. To identify each method uniquely, we differentiate
each method by types of arguments or the number of arguments or order of
arguments.
If we have to perform only one operation, having same name of the methods
increases the readability of the program.
•Method Overloading: changing no. of arguments
•Method Overloading: changing data type of arguments
Constructor Overloading in Java
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists
Method Overriding in Java
Usage of Java Method Overriding
Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
•The method must have the same name as in the parent class
•The method must have the same parameter as in the parent class.
•There must be an relationship (inheritance).
Super Keyword in Java
The super keyword in Java is a reference variable which is used to refer immediate parent
class object.
Usage of Java super Keyword
•super can be used to refer immediate parent class instance variable.
•super can be used to invoke immediate parent class method.
•super() can be used to invoke immediate parent class constructor.
Can we Override static methods in java? No
We can declare static methods with same signature in subclass, but it is not considered
overriding as there won’t be any run-time polymorphism
If a derived class defines a static method with same signature as a static method in base
class, the method in the derived class hides the method in the base class.
Following are some important points for method overriding and static methods in Java.
1) For class (or static) methods, the method according to the type of reference is called, not
according to the object being referred, which means method call is decided at compile
time.
2) For instance (or non-static) methods, the method is called according to the type of
object being referred, not according to the type of reference, which means method calls is
decided at run time.
3) An instance method cannot override a static method, and a static method cannot hide
an instance method. For example, the following program has two compiler errors.
4) In a subclass (or Derived Class), we can overload the methods inherited from the
superclass. Such overloaded methods neither hide nor override the superclass methods —
they are new methods, unique to the subclass.
Access Modifiers in Java
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and
class by applying the access modifier on it.
Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed from within
the class, outside the class, within the package and outside the package.
P
Class A
Protected Int I
Class b
I
Q
Class c extends class A
PPT ON JAVA AND UNDERSTANDING JAVA'S PRINCIPLES

PPT ON JAVA AND UNDERSTANDING JAVA'S PRINCIPLES

  • 1.
    Operator in Javais a symbol which is used to perform operations. Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups − •Arithmetic Operators •Relational Operators •Bitwise Operators •Logical Operators •Assignment Operators •Misc Operators
  • 2.
    The Arithmetic Operators Arithmeticoperators are used in mathematical expressions in the same way that they are used in algebra. Operator Description Example + (Addition) Adds values on either side of the operator. A + B will give 30 - (Subtraction) Subtracts right-hand operand from left-hand operand. A - B will give -10 * (Multiplication) Multiplies values on either side of the operator. A * B will give 200 / (Division) Divides left-hand operand by right-hand operand. B / A will give 2 % (Modulus) Divides left-hand operand by right-hand operand and returns remainder. B % A will give 0 ++ (Increment) Increases the value of operand by 1. B++ gives 21 --- (Decrement) Decreases the value of operand by 1. B--- gives 19 Assume integer variable A holds 10 and variable B holds 20,
  • 3.
    The Relational Operators OperatorDescription Example == (equal to) Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true. != (not equal to) Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true. > (greater than) Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true. < (less than) Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true. >= (greater than or equal to) Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true. <= (less than or equal to) Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true.
  • 4.
    The Bitwise Operators Javadefines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte. Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they will be as follows − a = 0011 1100 b = 0000 1101 ----------------- a&b = 0000 1100 a|b = 0011 1101 a^b = 0011 0001 ~a = 1100 0011 Operator Description Example & (bitwise and) Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12 which is 0000 1100 | (bitwise or) Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61 which is 0011 1101 ^ (bitwise XOR) Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49 which is 0011 0001 ~ (bitwise compliment) Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~A ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number. << (left shift) Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240 which is 1111 0000 >> (right shift) Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15 which is 1111 >>> (zero fill right shift) Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros. A >>>2 will give 15 which is 0000 1111
  • 5.
    The Logical Operators &&(logical and) Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. (A && B) is false || (logical or) Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true. (A || B) is true ! (logical not) Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is true
  • 6.
    The Assignment Operators OperatorDescription Example = Simple assignment operator. Assigns values from right side operands to left side operand. C = A + B will assign value of A + B into C += Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand. C += A is equivalent to C = C + A -= Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand. C -= A is equivalent to C = C – A *= Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand. C *= A is equivalent to C = C * A /= Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand. C /= A is equivalent to C = C / A %= Modulus AND assignment operator. It takes modulus using two operands and assign the result to left operand. C %= A is equivalent to C = C % A <<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2 >>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2 &= Bitwise AND assignment operator. C &= 2 is same as C = C & 2 ^= bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2 |= bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2
  • 7.
    Category Operator Associativity Postfixexpression++ expression-- Left to right Unary ++expression –-expression +expression –expression ~ ! Right to left Multiplicative * / % Left to right Additive + - Left to right Shift << >> >>> Left to right Relational < > <= >= instanceof Left to right Equality == != Left to right Bitwise AND & Left to right Bitwise XOR ^ Left to right Bitwise OR | Left to right Logical AND && Left to right Logical OR || Left to right Conditional ?: Right to left Assignment = += -= *= /= %= ^= |= <<= >>= >>>= Right to left Precedence of Java Operators
  • 8.
    Java If Statement TheJava if statement is used to test the condition. It checks boolean condition: true or false. There are various types of if statement in Java. •if statement •if-else statement •if-else-if ladder •nested if statement Java if Statement The Java if statement tests the condition. It executes the if block if condition is true. class A { public static void main(String[] args) { int age=20; if(age>18) { System.out.print("Age is greater than 18"); } } }
  • 9.
    Java if-else Statement TheJava if-else statement also tests the condition. It executes the if block if condition is true otherwise else block is executed. public class A { public static void main(String[] args) { int number=13; if(number%2==0){ System.out.println("even number"); } else{ System.out.println("odd number"); } } }
  • 10.
    Ternary Operator We canalso use ternary operator (? :) to perform the task of if...else statement. It is a shorthand way to check the condition. If the condition is true, the result of ? is returned. But, if the condition is false, the result of : is returned. public class T { public static void main(String[] args) { int number=13; //Using ternary operator String output=(number%2==0)?"even number":"odd number"; System.out.println(output); } }
  • 11.
    Java if-else-if ladderStatement The if-else-if ladder statement executes one condition from multiple statements.
  • 12.
    public class A{ public static void main(String[] args) { int marks=65; if(marks<50){ System.out.println("fail"); } else if(marks>=50 && marks<60){ System.out.println("D grade"); } else if(marks>=60 && marks<70){ System.out.println("C grade"); } else if(marks>=70 && marks<80){ System.out.println("B grade"); } else if(marks>=80 && marks<90){ System.out.println("A grade"); }else if(marks>=90 && marks<100){ System.out.println("A+ grade"); }else{ System.out.println("Invalid!"); } } }
  • 13.
    Java Nested ifstatement The nested if statement represents the if block within another if block. Here, the inner if block condition executes only when outer if block condition is true.
  • 14.
    public class A{ public static void main(String[] args) { //Creating two variables for age and weight int age=20; int weight=80; //applying condition on age and weight if(age>=18){ if(weight>50){ System.out.println("You are eligible to donate blood"); } } }}
  • 15.
    Java While Loop Whileloop starts with the checking of condition. If it evaluated to true, then the loop body statements are executed otherwise first statement following the loop is executed. For this reason it is also called Entry control loop while(condition){ //code to be executed Incr. or decr. operator } class A { public static void main(String[] args) { int i=1; while(i<=10) { System.out.println(i); i++; } } }
  • 16.
    Java Infinitive WhileLoop If you pass true in the while loop, it will be infinitive while loop while(true){ .
  • 17.
    do while loopin java A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. class A1 { public static void main(String[] args) { int i=1; do{ System.out.println(i); i++; }while(i<=10); } }
  • 18.
    for loop for loopprovides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping. for(initialization;condition;incr/decr) Initialization: It is the initial condition which is executed once when the loop starts. Here, we can initialize the variable, or we can use an already initialized variable. It is an optional condition. Condition: It is the second condition which is executed each time to test the condition of the loop. It continues execution until the condition is false. It must return boolean value either true or false. Increment/Decrement: It increments or decrements the variable value. class A { public static void main(String args[]) { // for loop begins when x=2 // and runs till x <=4 for (int x = 2; x <= 4; x++) System.out.println("Value of x:" + x); } }
  • 19.
    Java Nested ForLoop If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes completely whenever outer loop executes. class A { public static void main(String[] args) { //loop of i for(int i=1;i<=3;i++){ //loop of j for(int j=1;j<=3;j++){ System.out.println(i+" "+j); }//end of i }//end of j } }
  • 20.
    Java for-each Loop classA { public static void main(String[] args) { //Declaring an array int arr[]={12,23,44,56,78}; //Printing array using for-each loop for(int i:arr){ System.out.println(i); } } }
  • 21.
  • 22.
    Java switch Statement InJava, we have used the if..else if ladder to execute a block of code among multiple blocks. However, the syntax of if...else...if ladders are too long. Hence, we can use the switch statement as a substitute for long if...else...if ladders. The use of switch statements makes our code more readable.
  • 23.
    What is astring • A sequence of characters • Representing alphanumeric data. • Defined in the java.lang.String class • String is a class and objects of String type are reference variables.
  • 24.
    Making a string •Declared as a typical object would be. By new keyword • String s= new String(“Hello”)
  • 25.
    String Literal Java Stringliteral is created by using double quotes. String s = “Hello” String s1=“Welcome” String s2=“Welcome”
  • 26.
    Immutability • Once created,a string cannot be changed: none of its methods changes the string. • Such objects are called immutable. • Immutable objects are convenient because several references can point to the same object safely: there is no danger of changing an object through one reference without the others being aware of the change.
  • 27.
    Why string objectsare immutable in java? Advantages Of Immutability Uses less memory. word1 OK Less efficient: wastes memory “Java" “Java" “Java" word2 word1 word2
  • 28.
    Disadvantages of Immutability Lessefficient — you need to create a new string and throw away the old one even for small changes. word “java" “Java"
  • 29.
    Concatenating String There are2 methods to concatenate two or more string. 1) Using concat() method Concat() method is used to add two or more string into a single string object. It is string class method and returns a string object. 2) Using + operator Java uses "+" operator to concatenate two string objects into single one. It can also concatenate numeric value with string object.
  • 30.
    String Comparison To comparestring objects, Java provides methods and operators both. So we can compare string in following three ways. Using equals() method equals() method compares two strings for equality, It compares the content of the strings. It will return true if string matches, else returns false. Using == operator The double equal (==) operator compares two object references to check whether they refer to same instance. This also, will return true on successful match else returns false. By compareTo() method String compareTo() method compares values and returns an integer value which tells if the string compared is less than, equal to or greater than the other string. It compares the String based on natural ordering i.e alphabetically.
  • 31.
    Java String charAt()method The string charAt() method returns a character at specified index. Java String length() method The string length() method returns length of the string. Java String valueOf() method The string valueOf() method coverts given type such as int, long, float, double, boolean, char and char array into string. Java String replace() method The string replace() method replaces all occurrence of first sequence of character with second sequence of character. Java String toUpperCase() and toLowerCase() method The java string toUpperCase() method converts this string into uppercase letter and string toLowerCase() method into lowercase letter. Java String trim() method The string trim() method eliminates white spaces before and after string.
  • 32.
    String search: indexOf() Method intindexOf(int ch): It returns the index of the first occurrence of character ch in a given String. int indexOf(int ch, int fromIndex): It returns the index of first occurrence of character ch in the given string after the specified index “fromIndex”. For example, if the indexOf() method is called like this str.indexOf(‘A’, 20) then it would start looking for the character ‘A’ in string str after the index 20. int indexOf(String str): Returns the index of string str in a particular String. int indexOf(String str, int fromIndex): Returns the index of string str in the given string after the specified index “fromIndex”. * returns -1 if the specified char/substring is not found in the particular String.
  • 33.
    StringBuffer class: Java StringBufferclass is used to create mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed. StringBuffer() creates an empty string buffer with the initial capacity of 16. StringBuffer(String str) creates a string buffer with the specified string. StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length.
  • 34.
    1) StringBuffer append()method The append() method concatenates the given argument with this string. 2) StringBuffer insert() method The insert() method inserts the given string with this string at the given position. 3) StringBuffer replace() method The replace() method replaces the given string from the specified beginIndex and endIndex. 4) StringBuffer delete() method The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex. 5) StringBuffer reverse() method The reverse() method of StringBuffer class reverses the current string. 6) StringBuffer capacity() method The capacity() method of StringBuffer class returns the current capacity of the buffer. The default capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
  • 35.
    Java Package Package isa collection of related classes. Java uses package to group related classes, interfaces and sub-packages. We can assume package as a folder or a directory that is used to store similar files. Types Of Package Package can be built-in and user-defined Built-in Package: math, util, lang, i/o etc are the example of built-in packages. User-defined-package: Java package created by user to categorize their project's classes and interface are known as user-defined packages. How to Create a Package Use package command followed by name of the package as the first statement in java source file. Package p; •Package statement must be first statement in the program even before the import statement. •A package is always defined as a separate folder having the same name as the package name. •Store all the classes in that package folder. •All classes of the package which we wish to access outside the package must be declared public.
  • 36.
    How to importJava Package There are 3 different ways to refer to any class that is present in a different package: •without import the package •import package with specified class •import package with all classes
  • 37.
    Inheritance in Java Itis the mechanism in java by which one class is allow to inherit the features(fields and methods) of another class. Important terminology: Super Class: The class whose features are inherited is known as super class(or a base class or a parent class). Sub Class: The class that inherits the other class is known as sub class(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods. Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class. Class b extends A
  • 38.
    Single Inheritance :In single inheritance, subclasses inherit the features of one superclass.
  • 39.
    Multilevel Inheritance :In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also act as the base class to other class. In below image, the class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C. In Java, a class cannot directly access the grandparent’s members.
  • 40.
    Hierarchical Inheritance, oneclass serves as a superclass (base class) for more than one sub class.In below image, the class A serves as a base class for the derived class B,C and D. Class b extends c,d Print()- function class c Print()- function class d U-object class b U.Print();
  • 41.
    Method Overloading inJAVA If a class has multiple methods having same name but different in parameters, it is known as Method Overloading. method overloading in Java is a feature that allows a class to have more than one method with the same name. To identify each method uniquely, we differentiate each method by types of arguments or the number of arguments or order of arguments. If we have to perform only one operation, having same name of the methods increases the readability of the program. •Method Overloading: changing no. of arguments •Method Overloading: changing data type of arguments
  • 42.
    Constructor Overloading inJava Constructor overloading in Java is a technique of having more than one constructor with different parameter lists
  • 43.
    Method Overriding inJava Usage of Java Method Overriding Method overriding is used to provide the specific implementation of a method which is already provided by its superclass. Method overriding is used for runtime polymorphism Rules for Java Method Overriding •The method must have the same name as in the parent class •The method must have the same parameter as in the parent class. •There must be an relationship (inheritance).
  • 44.
    Super Keyword inJava The super keyword in Java is a reference variable which is used to refer immediate parent class object. Usage of Java super Keyword •super can be used to refer immediate parent class instance variable. •super can be used to invoke immediate parent class method. •super() can be used to invoke immediate parent class constructor.
  • 45.
    Can we Overridestatic methods in java? No We can declare static methods with same signature in subclass, but it is not considered overriding as there won’t be any run-time polymorphism If a derived class defines a static method with same signature as a static method in base class, the method in the derived class hides the method in the base class. Following are some important points for method overriding and static methods in Java. 1) For class (or static) methods, the method according to the type of reference is called, not according to the object being referred, which means method call is decided at compile time. 2) For instance (or non-static) methods, the method is called according to the type of object being referred, not according to the type of reference, which means method calls is decided at run time. 3) An instance method cannot override a static method, and a static method cannot hide an instance method. For example, the following program has two compiler errors. 4) In a subclass (or Derived Class), we can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass methods — they are new methods, unique to the subclass.
  • 46.
    Access Modifiers inJava The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it. Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class. Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default. Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package. Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package. P Class A Protected Int I Class b I Q Class c extends class A