Tuesday, October 29, 2019

Java oops




About Java:
Java is a programming language is object-oriented programming language(except primitive datatype all elements in java are objects) that was released by sun microsystem in 1995.It was created by the team leading by James Gosling.

 It is platform independent (write once Run Anywhere): Java programs use the Java virtual machine as abstraction and do not access the operating system directly. This makes Java programs highly portable. It can be run modified on any platform like windows and ubuntu.
It is use to create an application that may run on single computer or may be distributed between the server and the client network.
Java is case sensitive variable name MyValue and Myvalue are not treated as the same.
Above we mention JVM WHAT IS JVM??
JVM(JAVA VIRTUAL MACHINE)it is an runtime engine to run java application .JVM is the one that calls the main method in the java code.
It is called platform independent because we can write code once any other java enabled system without any adjustment it is because of JVM.

When we compile the .java file .class file gets auto generated by the java compiler. This class file goes into various steps when we run it.These steps together describe the whole JVM.





Example:

In the above example the java files are converted into their respective class file when we compile the file the class file is auto generated.






 In the above figure the class loader will load the class and the byte code verifier will verify the byte code and with the execution engine it will convert the byte code into native code. Hence the JVM process is very slow.


Installation of java:
Step 1:-
  Go to Java SE ( JDK 1.8 ) download site – www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
 Check Accept License Agreement”.
 You can check your Windows OS is 32-bit or 64-bit via Control Panel System “System Type”. Then Choose your operating platform, e.g., “Windows x64 for 64-bit Windows OS” or “Windows x32 for 32-bit Windows OS”.

Step 2:-  
 Install JDK. open the downloaded JDK setup files. See a first window of the screenshots. Click Next>



Java Se development kit 8 update setup windows. you can modify install to the path but this step is optional. My recommended is default path C:\program files\java\jdk……    It’s a setup automatically so just click Next>

install-java-in-windows

Installing screen.  wait 2-5 minutes
install-java-in-windows

 The Java Runtime ( JRE ) is needed for running Java programs. it compulsory install in windows. if you see this windows then Just click Next>


install-java-in-windows

Wait. . .   Installing JRE.

install-java-in-windows

Its all done here. The installation complete now.  click the Close button.
install-java-in-windows


The JDK installation successful.

Step 3:-     
 The right click on This PC  or  My Computer and select the properties.  or Another method use shortcut ( Win + E ) to open the explorer select computer tab> system properties.


Then select left side find the Advanced system settings and click now. and you see the pop-up windows title of the system properties. Go the Advanced tab find in a bottom of the window and select the Environment variables. 



Click New.  the user variable for UserName in the first row. and add this values like
Variable name: JAVA_HOME
Variable value :     C:\Program Files\Java\jdk1.8.0_60\bin
[Developer note: if you are an android developer or android studio have used on your windows computer. then please set variable value: C:\Program Files\Java\jdk1.8.0_60  remove \bin because it not working on android studio IDE.]
And click Ok.
 Windows OS searches the current directory and the directories listed in the PATH environment variable for executable programs.  JDKs programs such as Java compiler javac.exe and Java runtime java.exe” reside in directory “<JAVA_HOME>\bin” where <JAVA_HOME> denotes the JDK installed directory ( C:\Program Files\Java\jdk1.8.0_60\ ).
 I have shared an environment variables screenshot see and Setup the user variable.
install-java-in-windows

 Now click Ok > Apply > Ok and close all the window.
Step 4:- 
Verify the installation of JDK.  Launch a CMD command (Click  Win + R button run… enter “cmd” OR from “Start” button All Programs Accessories Command Prompt)
Enter the command java version and press enter.
See the message like this
java version “1.8.0_60”
Java(TM) SE Runtime Environment (build 1.8.0_60-b27)
Java Hotspot(TM) 64-Bit Server VM (build 25.5-b23, mixed mode)

It means java JDK install and complete setup 



Syntax:
syntax refers to the rules that specify the correct combined sequence of symbols that can be used to form a correctly structured program using a given programming language. 


The name of the java file must match the class name. When saving the file, save it using the class name and add ".java" to the end of the filename.
Any code inside the main() method will be executed. You don't have to understand the keywords before and after main. You will get to know them bit by bit while reading this tutorial.
For now, just remember that every Java program has a class name which must match the filename, and that every program must contain the main() method.



COMMENTS:
Comments can be used to explain Java code, and to make it more readable.
It is not executed when program is compiled.
It is useful  to understand and Edit the program by new programmer.
We can write comments in 2 different ways:
·        Single line comments.
Single line comments starts with //.
Any text between // and the end of the line is ignored by Java (will not be executed).
Example:
public class abc {
    public static void main(String[] args) {
     String firstName = "Ram";//this is the comment
String lastName = "joshi";
System.out.println(firstName + " " + lastName);


    }
}
Output:



See the comment is not executed.

·        Multiline comments.
Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by Java.
Example:

/* this code is useful
to display the concatination
 of two string*/
public class abc {
    public static void main(String[] args) {
     String firstName = "Ram";//this is the comment
String lastName = "joshi";
System.out.println(firstName + " " + lastName);


    }
}
Output:













See here also the above part is not executed.







Hello world program:
package hello;
public class Hello {
    public static void main(String[] args) {
        System.out.println("hello world");
    }
   

In the above picture there are 2 steps to run this file 1]to compile it 2]to run the file.
The file name should be saved same as the class name.




Variables:

In java variables are the container to store data values.
In java there are different type of variables:I.e
String:to store a word such as ”Hello”.
Int:To stores integer whole number such as 123 -123.
Float:To store decimal values such as 1.23,3.141.
Char:To store a single character such as ‘a’,’b’, Char values are surrounded by single quotes.
Boolean: Stores values with two states: true or false.

Declaring a variable:

To create a variable, you must specify the type and assign it a value:
Syntax :
Type variable =value;
Where type is one of Java's types (such as int or String), and variable is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.

Example:

String  name=”Ram”;
System.ou.println(name);
Int myint=12;
System.ou.println(myint);
Float myfloat=12;
System.ou.println(myfloat);
Char mychar=’a’;
System.ou.println(mychar);


For mathematical “+” this represent like an addition but for string it is concatenation.

For declaring many variables it is separated by a comma;
Example:
public class abc {
    public static void main(String[] args) {
     int x=2,y=3,z=5;
System.out.println(x+y+z);
    }
}

Output:







DATATYPES:

A data type, in programming, is a classification that specifies which type of value a variable has and what type of mathematical, relational or logical operations can be applied to it without causing an error. A string, for example, is a data type that is used to classify text and an integer is a data type used to classify whole numbers.
There are 8 types of primitive data types:
  • Boolean data type
  • byte data type
  • char data type
  • short data type
  • Int data type
  • long data type
  • float data type
  • double data type


SIZE:

Type
Storage size
Value range
char
1 byte
-128 to 127 or 0 to 255
unsigned char
1 byte
0 to 255
signed char
1 byte
-128 to 127
int
2 or 4 bytes
-32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int
2 or 4 bytes
0 to 65,535 or 0 to 4,294,967,295
short
2 bytes
-32,768 to 32,767
unsigned short
2 bytes
0 to 65,535
long
8 bytes
-9223372036854775808 to 9223372036854775807
unsigned long
8 bytes
0 to 18446744073709551615

Example :

package hello;
          public class Hello {
    public static void main(String[] args) {
       byte x=2;
        System.out.println(x);
        int y=4;
        System.out.println(y);
        float f=10.3f;
        System.out.println(f);
        double d=2.3;
        System.out.println(d);
        Boolean b=false;
        System.out.println(b);
        char letterA = 'A';
        System.out.println(letterA);
    }
   
} 

Output:

                 

TYPE CASTING:
                        Type casting is when you assign a value of one primitive data type to another type.
                         In Java, there are two types of casting:
There are two type of type casting.

1.automatically
Converting a smaller type to a larger type size.
Byte->short->char->int->long->float ->double

Example:
package hello;
public class Hello {
    public static void main(String[] args) {
       int x=4;
double y=x;
System.out.println(x);
System.out.println(y);

    }
}

Output:


2.Manually
Converting a larger type to a smaller size type.
->double ->float -> long ->int-> char-> short->Byte

Example:

package hello;

public class Hello {
    public static void main(String[] args) {
       //int x=4;
//double y=x;
//System.out.println(x);
//System.out.println(y);
double mydouble=2.8462;
int myInt=(int)mydouble;
System.out.println(mydouble);
System.out.println(myInt);

    }
   
}
Here it will print 2 that is floor value.

Output:


 Operators

Operators are used to perform operations on variables and values.
Java divides the operators into the following groups:
  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Bitwise operators

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.
Operator
Name
Description
Example
+
Addition
Adds together 2 values
x + y
-
Subtraction
Subtracts one value from another
x-y
*
Multiplication
Multiplies two values
x*y
/
Division
Divides one value from another
x/y

%
Modulus
Returns the division remainder
x%y
++
Increament
Increases the value of a variable by 1
++x
--
Decreament
Decreases the value of a variable by 1
--x

Example:

package hello;
public class Hello {
    public static void main(String[] args) {
       int a=10;
       int b=20;
       int c=a+b;
       int d=a-b;
       int e=a*b;
       int f=a/b;
       int g=a%b;
       int h=++a;
       int i=--b;
        System.out.println("Addition of A and B is "+c);
         System.out.println("Subtraction of A and B is "+d);
          System.out.println("Multiplication of A and B is "+e);
           System.out.println("Division of A and B is "+f);
            System.out.println("Modulus of A and B is "+g);
             System.out.println("Increament of A  is "+h);
              System.out.println("Decrement B is "+i);
    }
   
}
Output:


 

Assignment Operators

Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:
Eg:   int x=10

A list of all assignment operators:
Name
Operator
Example
=
x=5
X=5
+=
X+=5
X=x+3
-=
x-=3
x=x-3
*=
x*=3
x=x*3
/=
x/=3
x=x/3
%=
x%=3
x=x%3
&=
x&=3
x=x&=3
|=
x|=3
x=x|=3
^=
x^=3
x=x^=3
>>=
x>>=3
x=x<<=3
<<=
X<<=3
x=x<<=3

Example:

package hello;

public class Hello {

    public static void main(String[] args) {

        int x = 5;

    System.out.println(x);

    x += 3;

    System.out.println(x);

    int z=5;

     z -= 3;

    System.out.println(z);

    int k=5;

     k*= 3;

    System.out.println(k);

    int p=5;

     p/= 3;

    System.out.println(p);

    int q=5;

     q %= 3;

    System.out.println(q);

    int s=5;

     s &= 3;

    System.out.println(s);

    int h=5;

     h |= 3;

    System.out.println(h);

     int y = 5;

     y ^= 3;

    System.out.println(y);

    int f=5;

     f>>= 3;

    System.out.println(f);

    int g=5;

     g <<= 3;

    System.out.println(g);

    }

   

}

Output:

 

 

Comparison Operators

Comparison operators are used to compare two values:
Operator
Name
Example
==
Equal to
X==y
!=
Not Equal to
x!=y
> 
Greater than
x>y
< 
Less than
X<y
>=
Greater than equal to

<=
Less than equal to

Example:

package hello;

public class Hello {

    public static void main(String[] args) {

      int x = 5;

    int y = 3;

    System.out.println(x == y);

     int a = 5;

    int b = 3;

    System.out.println(a != b);

     int p = 5;

    int q = 3;

    System.out.println(p > q);

    int r = 5;

    int s = 3;

    System.out.println(r < s);

    int u = 5;

    int v = 3;

    System.out.println(u >= v);

    int e = 5;

    int h = 3;

    System.out.println(e <= h);

    }

   

}

Output:

 

 

 

Logical Operators

Logical operators are used to determine the logic between variables or values:
Operator`
Name
Description
example
&&
And
Return True if Both the Statement are true
x < 5 &&  x < 10
||
Or
Returns true if one of the statements is true
x < 5 || x < 4
!
Not
Reverse the result, returns false if the result is true
(x < 5 && x < 10)

Example:

package hello;
public class Hello {
    public static void main(String[] args) {
         int x = 5;
    System.out.println(x > 3 && x < 10);
    int y = 5;
    System.out.println(y > 3 || y < 4);
    int z = 5;
    System.out.println(!(z > 3 && z < 10));
   }
}

Output:



Bitwise operators

Bitwise operators are used to perform manipulation of individual bits of a number. They can be used with any of the integral types (char, short, int, etc). They are used when performing update and query operations of Binary indexed tree.
1.OR bitwise operator
             It is represented by (|). If either of the bit is one it gives 1 else it give 0.
Example:
A=5(0101)
B=7(0111)
Bitwise OR
   0101
| 0111
_____
  0111=7

2.AND Bitwise Operator
      It is represented by (&). If both of the bit is 1 then it will give 1 else it will give 0.
A=5(0101)
B=7(0111)

Bitwise AND
   0101
| 0111
_____
  0101=5


3.XOR Bitwise Operator.
    It is represented by (^).If the corresponding bit are same it will give 0 else it give 1.
A=5(0101)
B=7(0111)
Bitwise XOR
   0101
| 0111
_____
  0010=2

4.Complement Bitwise Operator.
    It is represented by(~).For every 0 it gives 1 and for every 1 it gives 0.
A=5(0101)
B=7(0111)
Bitwise COMPLEMENT
 0101
_____
  1010=10

Example:


package hello;
public class Hello {
    public static void main(String[] args) {
     int a = 5;
        int b = 7;
   System.out.println("a&b = " + (a & b));
    System.out.println("a|b = " + (a | b));
      System.out.println("a^b = " + (a ^ b));
      System.out.println("~a = " + ~a);
    }
   
}

Output:




Java Strings

Strings are used for storing text.
A String variable contains a collection of characters surrounded by double quotes:
Example of declaring a String and printing it.
public class abc {
    public static void main(String[] args) {
     String mystring="Hello";
System.out.println(mystring);
    }
}
Output:

How to find the Length of the String.
Example:
public class abc {
    public static void main(String[] args) {
     String mystring="Hello";
System.out.println(mystring);
System.out.println("The length of the mystring string is: " + mystring.length());
    }
}
Output:

How to make String in uppercase and lowercase:
Example :
public class abc {
    public static void main(String[] args) {
     String mystring="Hello";

System.out.println(mystring.toUpperCase());
System.out.println(mystring.toLowerCase());


    }
}
Output:


How to find the index of the letter:
Example:
public class abc {
    public static void main(String[] args) {
     String mystring="Hello";

System.out.println(mystring.indexOf('l'));
    }
}
Output:


How to concatenate the String by using the concat()  method:
Example:
public class abc {
    public static void main(String[] args) {
     String firstName = "Ram";
String lastName = "joshi";
System.out.println(firstName + " " + lastName);
    }
}
OR

/* this code is useful
to display the concatination
 of two string*/
public class abc {
    public static void main(String[] args) {
     String firstName = "John ";
String lastName = "Doe";
System.out.println(firstName.concat(lastName));


    }
}
Output:



Escape character
Result
Description
\'
'
Single quote
\"
"
Double quote
\\
\
Backslash


/* this code is useful
to display the concatination
 of two string*/
public class abc {
    public static void main(String[] args) {
   String txt = "We are the so-called \"Vikings\" from the north.";
System.out.println(txt);

    }
}
Output:




Java Maths
The Java Math class has many methods that allows you to perform mathematical tasks on numbers.

Math.max(x,y)

The Math.max(x,y) method can be used to find the highest value of x and y:

Math.min(x,y)

The Math.min(x,y) method can be used to find the lowest value of of x and y:

Math.sqrt(x)

The Math.sqrt(x) method returns the square root of x:

Math.abs(x)

The Math.abs(x) method returns the absolute (positive) value of x:

Math.random()

Math.random() returns a random number between 0 (inclusive), and 1 (exclusive):
Example:
public class abc {
  public static void main(String args[]){
System.out.println("The maximun value"+Math.max(2,4));
System.out.println("The minimum value"+Math.min(2,4));
System.out.println("The sruareroot"+Math.sqrt(4));
System.out.println("The absolute value"+Math.abs(4));
System.out.println("The random number"+Math.random());
}
    }


Output:


Conditional Statements:
If statement
Use the if statement to specify a block of Java code to be executed if a condition is true.
SYNTAX:
if (condition){
block of statement to be executed. If the condition is true
}
Example:
package hello;
public class Hello {
    public static void main(String[] args) {
     if(20<30){
         System.out.println("20 is less then 30");
     }
    }
   
}
Output:


Else statement:
SYNTAX:
if (condition){
//block of statement to be executed. If the condition is true
}
else{
//block of statement to be executed if the condition is false
}
Example:

package hello;
public class Hello {
    public static void main(String[] args) {
        int time=13;
     if(time<12){
         System.out.println("good morning");
     }
     else{
//block of statement to be executed if the condition is false
System.out.println("good day");
}
    }
   
}
Output:




else if Condition:
 SYNTAX:
if (condition1){
//block of statement to be executed. If the condition1 is true
}
else if (condition2){
//block of statement to be executed if the condition1 is false and condition2 is True
}
else{
//block of statement to be executed if the condition1 is false and condition2 is false

}
Example:

package hello;
public class Hello {
    public static void main(String[] args) {
        int time=23;
     if(time<12){
         System.out.println("good morning");
     }
     else if (time<22){
//block of statement to be executed if the condition is false
System.out.println("good day");
}
     else{
         System.out.println("good night");
     }
    }
    
}
Output:


You can also use Ternary operator in place of if else statement.
SYNTAX:
Variable= (condition)? expression True : expression False
Example:

package hello;
public class Hello {
    public static void main(String[] args) {
        int time=13;
                String result=(time<12)? "Good morning" : "Good afternoon";
                System.out.println(result);
    }
   
}
Output:






Nested if else statement:
Example:
package hello;
public class Hello {
    public static void main(String[] args) {
       int age = 18;

if (age < 13)
{
  System.out.println("You are a  child!");
}
else if (age < 19)
{
  System.out.println("You are no longer a child, but a budding teenager.");
}
else
{
  if (age < 65)
  {
    System.out.println("You are an adult!");
  }
  else
  {
    System.out.println("You are now a senior, enjoy the good life friends!");
  }

}
    }
   
}
Output:

Switch Case:
Use the switch statement to select one of many code blocks to be executed.
SYNTAX:
switch(expression){
case x:
//code block
break;
case y:
//code block
break;
default:
//code block
}
Example:

package hello;
public class Hello {
    public static void main(String[] args) {
     int day = 4;
switch (day) {
  case 1:
    System.out.println("Monday");
    break;
  case 2:
    System.out.println("Tuesday");
    break;
  case 3:
    System.out.println("Wednesday");
    break;
  case 4:
    System.out.println("Thursday");
    break;
  case 5:
    System.out.println("Friday");
    break;
  case 6:
    System.out.println("Saturday");
    break;
  case 7:
    System.out.println("Sunday");
    break;
}
   
    }}
Output:




LOOPS:
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code more readable.

WHILE LOOPS
The while loop loops through a block of code as long as a specified condition is true.
SYNTAX:
while(condition) {
//code block to be executed
}
Example:

package hello;
public class Hello {
    public static void main(String[] args) {
     int i=0;
     while(i<5){
         System.out.println(i);
         i++;
     }
   
    }}
Output:




DO WHILE LOOPS
The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested.
SYNTAX:
do
{
//code of block to be executed
}
While(condition);

Example:

package hello;
public class Hello {
    public static void main(String[] args) {
     int i=0;
    do{
        System.out.println(i);
        i++;
       
    }
    while(i<=1);
   
    }}
OUTPUT:



FOR LOOPS:
When you know exactly how many times you want to loop through a block of code use the for loop instead of while loop.
Syntax:
for(statement1; statement2; statemwnt3){
//code block to be executed
}
Statement1 is executed before the execution of the code block.
Statement2 defines the condition for executing the code block.
Statement 3 is executed after the code block has been executed
Example:
package hello;
public class Hello {
    public static void main(String[] args) {
     for(int i=0; i<5; i++){
         System.out.println(i);
     }
   
    }}
Output:




Break Statement:
The break statement is use to jump out of the loop.
Example:
package hello;
public class Hello {
    public static void main(String[] args) {
     for(int i=0; i<10; i++){
         if(i==4){
         break;
         }
         System.out.println(i);
     }
   
    }}
Output:




Continue Statement:
The continue statement breaks one iteration, if a specified condition occurs and continue with the next iteration in the loop.
Example:
package hello;
public class Hello {
    public static void main(String[] args) {
     for(int i=0; i<10; i++){
         if(i==4){
         continue;
         }
         System.out.println(i);
     }
   
    }}
Output:

See in the above example it has skipped 4. And continue with further iteration.



ARRAYS:
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To declare an array, define the variable type with square brackets:

String[] cars;
Here we have declared a variable that holds an array.
Now let’s insert a value in that array.
String[] cars = {"Volvo", "BMW", "Ford"};
Int[] mynum={1,2,3,4};

How to Access the element of the array:
Example:
TO find the element present at index value 2:
package hello;
public class Hello {
    public static void main(String[] args) {
    String[] cars = {"Volvo", "BMW", "Ford"};
        System.out.println(cars[2]);  
    }}
Output:





How to find the length of the array:
Example:
package hello;
public class Hello {
    public static void main(String[] args) {
    String[] cars = {"Volvo", "BMW", "Ford"};
        System.out.println(cars.length);  
    }}
Output:

How to change the element in the array:
Example:
package hello;
public class Hello {
    public static void main(String[] args) {
    String[] cars = {"Volvo", "BMW", "Ford"};
    cars[2]="wolks";
        System.out.println(cars[2]);  
    }}
Output:

Array loops:
package hello;
public class Hello {
    public static void main(String[] args) {
            String[] cars = {"Volvo", "BMW", "Ford"};
     for(int i=0; i<cars.length; i++){
         System.out.println(cars[i]);
     }
   
    }}

Output:


For each loop:
There is also a "for-each" loop, which is used exclusively to loop through elements in arrays
SYNTAX:
for(type variable : arrayname){
………//
}
Example:
package hello;
public class Hello {
    public static void main(String[] args) {
            String[] cars = {"Volvo", "BMW", "Ford"};
     for(String i : cars){
         System.out.println(i);
     }
   
    }}
OUTPUT:




Multidimensional Arrays:
A multidimensional array is an array containing one or more arrays.
To create a two-dimensional array, add each array within its own set of curly braces:
Example:
int num[][]={{1,2,3,4},{5,6,7,8}};
To find the element present at 2 row 3 column.
Example:
package hello;
public class Hello {
    public static void main(String[] args) {
           
     int num [] []={{1,2,3,4},{5,6,7,8}};
     int x=num[1][2];
        System.out.println(x);
   
    }}
Output:

Example:
package hello;
import java.util.Scanner;
public class Hello {
    public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            System.out.println("Eneter your dimension");
            int rows=sc.nextInt();
            int cols=sc.nextInt();
            int a[][]=new int[rows][cols];
            int b[][]=new int[rows][cols];
            System.out.println("enter array a");
            for(int i=0;i<rows;i++){
            for(int j=0;j<cols;j++){
            a[i][j]=sc.nextInt();
           
            }
            }
            System.out.println("enter array b");
            for(int i=0;i<rows;i++){
            for(int j=0;j<cols;j++){
            b[i][j]=sc.nextInt();
           
            }
            }
            int c[][]=new int[rows][cols];
            for(int i=0;i<rows;i++){
            for(int j=0;j<cols;j++){
            c[i][j]=a[i][j]+b[i][j];
             
            }
            }
            System.out.println("result array c");
            for(int i=0;i<rows;i++){
            for(int j=0;j<cols;j++){
                System.out.print( c[i][j] +"");
            
            }
                System.out.println(" ");
            }
          
    }
}
Output:




Exception:
When executing Java code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, Java will normally stop and generate an error message. The technical term for this is: Java will throw an exception (throw an error).
To handle this we have try catch block.
Syntax:
try{
//block of code to be executed
}catch(Exception e)
{
//exception. To handle
}
Example.
package hello;
public class Hello {
    public static void main(String[] args) {
     try{
     int num[]={1,3,4};
         System.out.println(num[10]);
     }catch(Exception e){
         System.out.println("Something went wrong");
     }
    }
}
Here in this code it should give ARRAY INDEX OUT OF BOUND. But here it is handle by try catch block.
Output:

Finally

The finally statement will be executed every time even if the result is not appearing.
Example:
package hello;
public class Hello {
    public static void main(String[] args) {
     try{
     int num[]={1,3,4};
         System.out.println(num[10]);
     }catch(Exception e){
         System.out.println("Something went wrong");
     }
     finally {
      System.out.println("The 'try catch' is finished.");
    }
    }
}

Ouput:


The throw keyword

The throw statement allows you to create a custom error. The throw statement is used together with an exception type. there are many exception types available in java they are: ArithimaticException, FileNotFoundException,ArrayIndexOutOfBoundException,etc.
Example:
package hello;
public class Hello {
    static void validate(int age){  
     if(age<18) 
      throw new ArithmeticException("not valid"); 
     else 
      System.out.println("welcome to vote"); 
   } 
    public static void main(String[] args) {
    validate(13); 
      System.out.println("rest of the code..."); 
     
    }
}
Output:


If age is greater than 18 then it will not give exception.
Example:
package hello;
public class Hello {
    static void validate(int age){ 
     if(age<18) 
      throw new ArithmeticException("not valid"); 
     else 
      System.out.println("welcome to vote"); 
   } 
    public static void main(String[] args) {
    validate(20); 
      System.out.println("rest of the code..."); 
    
    }
}
Output:





JAVA METHODS:
It is executed whenever it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times.
How to create a method.
SYNTAX:
public class MyClass{
static void myMethod(){
//code to be executed
}
}
MyClass() is the name if the method,
Static means that the method belongs to the MyClass class and not an object of the MyClass class.
Void means this class is not having return type.

How to call a method.
To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
Example.
package hello;
public class Hello {
   static void myMethod() {
    System.out.println("Hello Method");
  }

    public static void main(String[] args) {
        myMethod() ;
        myMethod() ;
    }
    }
Output:

You can call method as many times you want.
Inside method we can also set a parameter.
Example:
package hello;
public class Hello {
   static void myMethod(String fname) {
    System.out.println(fname +" hola");
  }

    public static void main(String[] args) {
        myMethod("ram") ;
        myMethod("riya") ;
    }
    }


Output:


RETURN VALUE.
In the above examples using void indicate that it does not return any value. If we want to return any value we should use return keyword along with primitive datatype(int , char etc);

Example:

package hello;
public class Hello {
   static int myMethod(int x) {
    return 5+x;
  }

    public static void main(String[] args) {
        System.out.println(myMethod(4)) ;
      
    } 
    }

Output:


Can pass two parameter .To add two numbers.
Example:

package hello;
public class Hello {
   static int myMethod(int x,int y) {
    return x+y;
  }

    public static void main(String[] args) {
        System.out.println(myMethod(4,1)) ;
      
    }
    }
Output:





Can store it in some variable and then print the value.

Example:

package hello;
public class Hello {
   static int myMethod(int x,int y) {
    return x+y;
  }

    public static void main(String[] args) {
        int z=myMethod(2,1);
        System.out.println(z) ;
      
    }
    }
Output:





Methods with condition.
Example:

package hello;
public class Hello {
    static void checkage(int age){
    if(age<18){
        System.out.println("acess deneied");
    }
    else{
        System.out.println("you can vote");
    }
    }
    public static void main(String[] args) {
     
       checkage(20);
//checkage(10);
    }
    }


Output:




When age will be less then 18 then the output will be:





Classes and object in java.

Java is an object oriented programming language. Everything is associated with classes and object in java along with its method .
Example:
Dog is an object with attribute breed , colour , age and with methods such as bark , eat , sleep.
How to create a class in java

Example:

public class Hello {
    int x=2;
    }
   
How to create an object of this class name Hello:

Example:

package hello;
public class Hello {
    int x=2;
    public static void main(String[] args) {
        Hello obj1=new Hello();
        System.out.println(obj1.x);
       
    }
}
    Here will get output as 2
We can create a multiple object in this:

Example

package hello;
public class Hello {
    int x=2,y=3;
    public static void main(String[] args) {
        Hello obj1=new Hello();
        Hello obj2=new Hello();
        System.out.println(obj1.x);
        System.out.println(obj1.y);
       
    }
}

    Output:






We can do the above example with multiple classes .Like in this NewClass name  class it contain attribute and another file contain the object of it.


And this is the class which is containing main method in it in which the  object is created .of anotherclass ie.NewClass.






Output:






Example:(classes and object)

package hello;
public class Hello {
    String fname="ram";
    String lname="dilima";
    int age=20;
    public static void main(String[] args) {
        Hello obj1=new  Hello();
         Hello obj2=new  Hello();
          Hello obj3=new  Hello();
        System.out.println(obj1.fname);
        System.out.println(obj2.lname);
        System.out.println(obj3.age);
       
    }
}

    Output:




Here Hello is the name of the class and obj1,obj2,obj3 are the object created in it.
There are two type of methods they are 1)static 2)public.
In static there is no need to create an object to access it,and in public method it is necessary to create an object.

Example:

package hello;
public class Hello {
    // Static method
  static void myStaticMethod() {
    System.out.println("Static methods can be called without creating objects");
  }

  // Public method
  public void myPublicMethod() {
    System.out.println("Public methods must be called by creating objects");
  }
    public static void main(String[] args) {
       myStaticMethod(); // Call the static method
    // myPublicMethod(); This would compile an error

    Hello myObj = new Hello(); // Create an object of Hello
    myObj.myPublicMethod(); // Call the public method on the object
       
    }
}

Output:


  
How to access method with an object.

Example:

package hello;
public class Hello {
    public void hola(){
            System.out.println("hello 1st Method");
}
    public void hola2(){
            System.out.println("hello 2nd Method");
}
    public static void main(String[] args) {
        Hello obj1=new  Hello();
         Hello obj2=new  Hello();
         obj1.hola();
         obj2.hola2();
      
       
    }
}

Output:

   



In the above example:
There is a class with name Hello .
We have created 2 methods in it.1)hola2)hola2
Inorder  to call this methods we have to create an object so obj1 and obj2 are created in side the main method by using a new keyword.


Remember that..

The dot (.) is used to access the object's attributes and methods.
To call a method in Java, write the method name followed by a set of parentheses (), followed by a semicolon (;).
A class must have a matching filename .
Hello is the file name and class name is Hello().

 By using 2 different class we can also access the methods

Example:

!st class (NewClass)


2nd class(Hello)

Output:




Java Constructors:

It has same name as that of the class name.
A constructor in Java is a special method that is used to initialize objects. 
 The constructor is called when an object of a class is created. 

Example:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package hello;

/**
 *
 * @author DINESH
 */
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
public class BoxDemo {
    public static void main(String[] args) {
        // declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);

    }
}

Output: 




new Box( ) is calling the Box( ) constructor. When you do not explicitly define a constructor
for a class, then Java creates a default constructor for the class. In the above example of methods calling there we had not use the constructor it automatically call the default constructor. The default constructor automatically initializes all instance variables to zero. The default constructor is often sufficient for simple classes, but it usually won’t do for more sophisticated ones. Once you define your own constructor, the default constructor is no longer used.


Parameterized Constructors

Example:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package hello;

/**
 *
 * @author DINESH
 */
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w,double h,double d) {
System.out.println("Constructing Box");
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
public class BoxDemo {
    public static void main(String[] args) {
        // declare, allocate, and initialize Box objects
Box mybox1 = new Box(10,10,10);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
    }

}

Output:



Java Modifiers

Till now we were using the public keyword so You would be familiar of it till now.
The public keyword is an access modifier, meaning that it is used to set the access level for classes, attributes, methods and constructors.
We divide modifiers into two groups:
  • Access Modifiers - controls the access level
  • Non-Access Modifiers - do not control access level, but provides other functionality

ACCESS MODIFIERS:

For classes you can use either public or default:
Modifiers
Description
Public
This class is accessible by any other classes.
Default
This classes is only accessible by classes in the same package. This is used when you don’t specify a modifiers.
For attributes ,methods and constructors you can use the one of the following:
Modifier
Description
Public
The code is accessible for all classes
Private
This code is accessible within the declared class
Default
This code is only accessible in the same package, this is used when you don’t specify a modifier
Protected
The code is accessible in the same package and subclasses.

NON-ACCESS MODIFIERS

For classes, you can either use final or abstract:
Modifiers
Description
Final
The class cannot be inherited by other.
Abstract
The class cannot be used to create object
For attributes and methods, you can use the one of the following.
Modifiers
Description
final
Attributes and methods cannot be overridden/modified.
Static
Attribute and method belong to the class, rather than the object
Abstract
Can only be used in an abstract class, and can only be used on methods. The method does not have a body, for example abstract void run (); The body is provided by the subclass (inherited from). 
Transient
Attributes and methods can only be accessed by one thread at a time,
Synchronized
Method can only be accessed by one thread at a time.
Volatile
The value of an attribute is not cached thread-locally, and is always read from the “main memory”

Final Keyword:

If you declared a attribute value as final means will not be able to change the value of it  is fixed.

Example:

package hello;
public class Hello {
    final double x = 3.147;
    public static void main(String[] args) {
       Hello obj1=new Hello ();
         System.out.println(obj1.x=20);  
    }
}

    Output:




ABSTRACT

An abstract method belongs to an abstract class, and it does not have a body. The body is provided by the subclass:

Example:

package hello;
public class Hello {
    final double x = 3.147;
    public static void main(String[] args) {
     Employee obj1=new Employee();
        System.out.println("Employee Name "+obj1.empname);
        System.out.println("Employee age "+obj1.empage);
        System.out.println("joining year "+obj1.joiningyear);
        obj1.work();//abstract method called
    }
}

    OUTPUT:




Encapsulation

Encapsulation is use to hide the data from the users. Same as till now we were declaring an attribute as private .But till now this attribute can be access within the same class .but we can access this through getter and setter method.

The get method return the variable value.

The set method set the value.

Example:

abstract class NewClass {

   public String empname ;

   public String getName(){

   return empname;

   }

  public void setName(String NewName){

  this.empname=NewName;

}}

 

Main class:

package hello;

public class Hello {

    public static void main(String[] args) {

    NewClass obj1=new NewClass() {};

    obj1.empname = "John";

    System.out.println(obj1.empname);

   

    }}

OUTPUT:


PACKAGES

You need some way to be assured that the name you choose for a class will be reasonably unique and not collide with class names chosen by other programmers.

For example:

If the ISP of some area is using “ISP 1” as a class name and another as “ISP 2” as a class name. To manage these classes java, provide a mechanism known as PACKAGES.

The package is both a naming and a visibility control mechanism. You can define classes inside a package that are not accessible by code outside that package.

There are many built-in packages in java.

Refer: https://docs.oracle.com/javase/8/docs/api/

The above link  shows the list of built-in packages present in java.

To use the packages from the library you need to use import keyword:

Example:

Import package.name.Class;//single class

Import package.*;//importing whole package.

 

If you want to import a particular class lets say scanner class.

Import java.util.Scanner;

Example:

package hello;

import java.util.Scanner;

public class Hello {

    public static void main(String[] args) {

    Scanner myObj = new Scanner(System.in);

    System.out.println("Enter username");

    String userName = myObj.nextLine();

    System.out.println("Username is: " + userName);

    }}

    Output:

 

To import a whole package, end the sentence with an asterisk sign (*).

Example:

import java.util.*;

User Defined packages can also be created:

To create your own package, you need to understand that Java uses a file system directory to store them. Just like folders on your computer:

_______root

______pack

____Hello.java

Example:

package hello;

import java.util.Scanner;

public class Hello {

    public static void main(String[] args) {

        System.out.println("this is hello package");

    }}

Inheritance:

Inheritance allow the creation of hierarchical classification. Using Inheritance, you can use create a general class common to a related item. The class that is inherited is called as super class, the class which is not inherited is called as a subclass.

Example:

public class Hola {

    int i=2,j=3;

 void showij(){

     System.out.println("value of i and j is "+i +""+j);

 }

}

class Hi extends Hola{

int k=4;

void showk(){

    System.out.println("vale of k "+k);

}

void sum(){

    System.out.println("addition of i j k is "+(i+j+k));

   

}

    public static void main(String[] args) {

        Hi obj1=new Hi();

        obj1.showij();

        obj1.showk();

        obj1.sum();

    }

}

Output:


In the above example Hola is the super class and Hi is the subclass which extends the Hola class.

When and Why to use Inheritance:

·         It is use to reuse the attribute and Methods of the existing class.

Final Keyword:

If you don’t want to give the access to the other class of the existing class you can use final keyword.

Final class Hola {

}

Example:

final class Hola {

    int i=2,j=3;

 void showij(){

     System.out.println("value of i and j is "+i +""+j);

 }

}

class Hi extends Hola{ //This line will give u error becoz class Hola has access modifiers as final

int k=4;

void showk(){

    System.out.println("vale of k "+k);

}

void sum(){

    System.out.println("addition of i j k is "+(i+j+k));

   

}

    public static void main(String[] args) {

        Hi obj1=new Hi();

        obj1.showij();

        obj1.showk();

        obj1.sum();

    }

}

Output :

 

Polymorphism:

Polymorphism means 1 NAME MANY FORMS. In Polymorphism Poly means Many and morph means Form.

Example:

package hello;

class Animal{

void AnimalSound(){

    System.out.println("Animals Make Sounds");

}

}

class Dog extends Animal{

void AnimalSound(){

    System.out.println("Dog maks sound bow-bow.");

}}

class Cat extends Animal{

void AnimalSound(){

    System.out.println("Cat maks sound mew-mew.");

}}

public class Hola {

    public static void main(String[] args) {

        Animal animal=new Animal();

        Animal dog=new Dog();

        Animal cat=new Cat();

        animal.AnimalSound();

        dog.AnimalSound();

        cat.AnimalSound();

    }

}

Output:


The above example is of polymorphism.

In this Animal can be of different at different time it can be dog cat pig etc. At different time it should behave in different way.

In this example the Animal is the class which have different classes i.e. Dog Cat.

 

 User Input:(Scanner)

The Scanner class is used to get user input, and it is found in the java.util package.


import java.util.Scanner;
Scanner sc=new Scanner(System.in);
Int x=sc.nextInt();

Example:
package hello;
import java.util.Scanner;
public class Hello {
    public static void main(String[] args) {
     Scanner sc=new Scanner(System.in);
     int x=sc.nextInt();
     double y=sc.nextDouble();
System.out.println("the integer value is "+ x);

System.out.println("The double value is "+ y);


    }
   
}

Output:


For a sentence to take as a input and print it.

package hello;
import java.util.Scanner;
public class Hello {
    public static void main(String[] args) {
     Scanner sc=new Scanner(System.in);
     String x=sc.nextLine();
    
System.out.println("the String value is "+ x);
    }
}


Output:




Lets find a simple interest without taking value from user.
package hello;
import java.util.Scanner;
public class Hello {
    public static void main(String[] args) {
     int principal=5000;
float rate=12.5f;
int time=12;
float simpleinterest=principal*rate*time/100;
        System.out.println("the simple intrest is "+simpleinterest);
    }
   
}

Output :

 

Let’s find a simple interest taking value from user
package hello;
import java.util.Scanner;
public class Hello {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
     int principal=sc.nextInt();
float rate=sc.nextFloat();
int time=sc.nextInt();
float simpleinterest=principal*rate*time/100;
        System.out.println("the simple intrest is "+simpleinterest);
    }
   
}

Output:



JAVA DATE:

Java does not have a built-in Date class, but we can import the java. Time package to work with the date and time API.This package include many class in it.

Class
Description
LocalDate
Displays a date (year, month, day (yyyy-MM-dd))
LocalTime
Displays a time (hour, minute, second and milliseconds (HH-mm-ss-zzz))
LocalDateTime
Displays both a date and a time (yyyy-MM-dd-HH-mm-ss.zzz)
DateTimeFormatter
Displaying and parsing date-time objects

 

Example:

import java.time.LocalDate;

import java.time.LocalTime;

import java.time.LocalDateTime;

public class abc {

  public static void main(String args[]){

LocalDate myobj=LocalDate.now();

System.out.println(myobj);         //displays the current Date.

LocalTime myobj1=LocalTime.now();

System.out.println(myobj1);       //displays the current Time.

LocalDateTime myobj2=LocalDateTime.now();

System.out.println(myobj2);        //displays the current Time.//displays the current date and time.

}

    }

 

Output:




Formatting Date and Time

The "T" in the example above is used to separate the date from the time. You can use the DateTimeFormatter class with the ofPattern() method in the same package to format or parse date-time objects. The following example will remove both the "T" and milliseconds from the date-time:

Example:

import java.time.LocalTime;

import java.time.LocalDateTime;

import java.time.format.DateTimeFormatter;

public class abc {

  public static void main(String args[]){

LocalDateTime myDateObj = LocalDateTime.now(); 

    System.out.println("Before formatting: " + myDateObj); 

    DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"); 

   

    String formattedDate = myDateObj.format(myFormatObj); 

    System.out.println("After formatting: " + formattedDate); 

}

    }

Output:



The ofPattern() method accepts all sorts of values, if you want to display the date and time in a different format. For example:

Value

Example

yyyy-MM-dd

"1988-09-29"

dd/MM/yyyy

"29/09/1988"

dd-MMM-yyyy

“29-Sep-1988”

 

 

Wrapper Classes

Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects.

Example:

public class abc {

  public static void main(String args[]){

Integer myInt = 5;

    Double myDouble = 5.99;

    Character myChar = 'A';

    System.out.println(myInt);

    System.out.println(myDouble);

    System.out.println(myChar);

}

    }

Output:


Another useful method is the toString() method, which is used to convert wrapper objects to strings.
In the following example, we convert an Integer to a String, and use the length() method of the String class to output the length of the "string":

Example:

public class abc {

  public static void main(String args[]){

Integer myInt = 100;

    String myString = myInt.toString();

    System.out.println(myString.length());

}

    }

Output:

 

 Files:

The File class from the java.io package, allows us to work with files.
To use the File class, create an object of the class, and specify the filename or directory name:

Like:

import java.io.File ;
File obj=new File(“filename.txt”);

File class has many useful methods.

Method
Type
Description
canRead()
Boolean
Tests whether the file is readable or not
canWrite()
Boolean
Tests whether the file is writable or not
createNewFile()
Boolean
Creates an empty file
delete()
Boolean
Deletes a file
exists()
Boolean
Tests whether the file exists
getName()
String
Returns the name of the file
getAbsolutePath()
String
Returns the absolute pathname of the file
length()
Long
Returns the size of the file in bytes
list()
String[]
Returns an array of the files in the directory
mkdir()
Boolean
Creates a directory


How to create a file.
To create a file use createNewFile() method.This method returns the Boolean value True if the file is created,and False if the file is already exist.
This method is enclosed in the try catch block.

Example:

package hola;
import java.io.File;
import java.io.IOException;
    public static void main(String[] args) {
     try{
     File myobj=new File("123.txt");
     if(myobj.createNewFile()){
         System.out.println("file created"+myobj.getName());
     }else{
         System.out.println("file already exist");
     }
     }catch(IOException e){
         System.out.println("An error occured");
         e.printStackTrace();
     }
    }
   
}

Output: 


How to gat information about the file:

Example:


package hola;

import java.io.File;
import java.io.IOException;

public class Hola {
    public static void main(String[] args) {
   
     File myobj=new File("123.txt");
     if(myobj.exists()){
         System.out.println("file Name "+myobj.getName());
         System.out.println("Absolute Path "+myobj.getAbsolutePath());
         System.out.println("Wriateble "+myobj.canWrite());
         System.out.println("Readable "+myobj.canRead());
         System.out.println("File Size in byte " +myobj.length());
     }
     else{
         System.out.println("file does not exists");
     }
     }
    }

    Output:



How to write in the created file:

To write in the created file we use FileWriter Class write() method to write in the created file.After completion of writing we have to close it with close() method.

Example:


package hola;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Hola {
    public static void main(String[] args) {
        try{
    FileWriter mywrite=new FileWriter("123.txt");
    mywrite.write("hello this is the content");
    mywrite.close();
            System.out.println("Data inserted in the file");
        }catch(IOException e){
            System.out.println("An error occured");
            e.printStackTrace();
        }
     }
    }

    Output:




Reader the data from the file:

Scanner class is use to read the content of the file.

Example:

package hola;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class Hola {
    public static void main(String[] args) {
        try{
    File myobj=new File("123.txt");
   Scanner myReader=new Scanner(myobj);
   while(myReader.hasNextLine()){
   String data=myReader.nextLine();
       System.out.println(data);
      
   }
   myReader.close();
        }catch(FileNotFoundException e){
            System.out.println("An error occured");
            e.printStackTrace();
        }
     }
    }

    Output:




 

WAYTOJAVA Template by Ipietoon Cute Blog Design and Bukit Gambang