Thursday, March 31, 2016

Introduction


what is java?

Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere" (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of computer architecture. As of 2015, Java is one of the most popular programming languages in use, particularly for client-server web applications, with a reported 9 million developers. Java was originally developed by James Gosling at Sun Microsystems (which has since been acquired by Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++, but it has fewer low-level facilities than either of them.
The original and reference implementation Java compilers, virtual machines, and class libraries were originally released by Sun under proprietary licences. As of May 2007, in compliance with the specifications of the Java Community Process, Sun relicensed most of its Java technologies under the GNU General Public License. Others have also developed alternative implementations of these Sun technologies, such as the GNU Compiler for Java (bytecode compiler), GNU Classpath (standard libraries), and IcedTea-Web (browser plugin for applets).
The latest version is Java 8, which is the only version currently supported for free by Oracle, although earlier versions are supported both by Oracle and other companies on a commercial basis.


Downloading Java


Java Platform, Standard Edition (Java SE) lets you develop and deploy Java applications on desktop and servers, as well as in today's demanding embedded environments. Java offers the rich user interface, performance, versatility, portability, and security that today's applications require.

Download Java Standard Edition (SE)
(sn :- download JDK only)

After you installed the setup,

  • open 'bin' folder in your java installed location(ex - C:\Program Files\Java\jdk1.8.0_60)
  • Copy the URL
  • Then open computer properties.
  • Click 'Advanced system settings'
  • Click 'New'
  • In variable name; type 'Path'
  • In Variable value; paste the URL.
  • Press Enter
Now open Command Prompt

  • Type  'javac'
  • Press Enter

First Program



Hey guys, welcome to another java tutorial. In this post we're gonna write our first program.

  1. Open your Notepad
  2. OK, let's do coding.


                             public class First{
                                 public static void main(String []args){
                                                System.out.println("Hello Blogger") :
                                 }
                             }

Description

  1. public class First {  -   We started a java class & its name is 'First'.
  2. public static void main(String []args) { -   This is the built in main method.
  3. System.out.println("Hello Blogger") :  -   We print "Hello World" on the screen
  •  Now save it as 'First.java' (save it in Local Disk C or D, trust me unless you'll face lot of problems)
  • Open Command Prompt
  • Type 'cd..'  twice.
  • Then type 'javac First.java '
  • Now type 'java First'
  • Press Enter

Eclipse

It's so hard to compile using cmd & notepad

So why are we waiting let's do this easy way ...





Data Types


The Java programming language is statically-typed, which means that all variables must first be declared before they can be used. This involves stating the variable's type and name.

Data types :-

  • byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127. The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.
  • short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.
  • int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer. See the section The Number Classes for more information. Static methods like compareUnsigneddivideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.
  • long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use thelong data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. Use this data type when you need a range of values wider than those provided by int. The Long class also contains methods like compareUnsigneddivideUnsigned etc to support arithmetic operations for unsigned long.
  • float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead.Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.
  • double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
  • boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.
  • char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff'
In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java.lang.String class. Enclosing your character string within double quotes will automatically create a new String object; for example, String s = "this is a string";String objects are immutable, which means that once created, their values cannot be changed. The String class is not technically a primitive data type, but considering the special support given to it by the language, you'll probably tend to think of it as such.

Using int and String


Now you have a rough idea about the Data Types. So now it's time for a simple calculation.

We know numeric values can be used in 'int' data type ant texts in 'String'.
Okay let's go...

  1. Open Eclipse
  2. File >  New > Java Project 
  3. Type a project name
  4. Right click 'src'
  5. New > Class
  6. Give it a name



Now it's for the coding

   public class main {

   public static void main(String []args){
int total;
int x = 20 ;
int y = 10 ;
total = x+y ;
System.out.println(total);
       }
 }



Let's Print a name

  

public class main {
public static void main(String []args){
String fname = "David" ;
String sname = "Miller";
String fullname = fname + sname ;
System.out.println(fullname);
}
}



Getting User Inputs


In this Post we're gonna learn how to get user inputs to our program. Ex :- When we are creating calculator you need to get inputs from the user. 


OK Let's create a simple program to display your name using 'Scanners'

  1. Open the Eclipse
  2. Then let's code...
In here we're gonna import a package called 'util'. It has the this object called 'Scanner'. OK What is this Scanner ? It's really not like a scanner... it only allows the user to enter text into the computer as a String.

import java.util.*;
public class main {
public static void main(String []args){
System.out.println("Enter your first name...");
Scanner scan = new Scanner(System.in);
String fname = scan.nextLine();
System.out.println("Enter your second name...");
Scanner scan2 = new Scanner(System.in);
String sname = scan.nextLine();
System.out.println("Your name is " +fname + sname);
}
}

            (Don't copy & paste this code, try understand and write it again for your best.....)
  1. First it prints a line "Enter your first name..."
  2. Then user can input the name
  3. That input we take into computer by the scanner called 'scan'
  4. That input will save in the fname variable
  5. Then it  prints next line "Enter your second name..."
  6. Then user can input the second name
  7. That input we take into computer by the scanner called 'scan2'
  8. That input will save in the sname variable
  9. Finally it displays/prints "Your name is DavidMiller" or whatever the name is.





Calculating with User Inputs


Hey guys, by this post we're gonna learn how to do calculations with user inputs. 


  1. As usual open the Eclipses
  2. Now import java util package   

Coding :-

  1. First we wanna declare 2 variables.
  2. Next, display message to enter the first number.
  3. Create a scanner to get that number (SN :- When using scanners we get user inputs as Strings)
  4. Initialize that string to first variable.
  5. Do the same to the second number.
  6. Display the answer using System.out.println concept.
     (You also can declare another variable as int total and initialize it as total = fnum + snum; )

import java.util.*;
public class main {
public static void main(String []args){
int fnum;
int snum;
System.out.println("Enter first number");
Scanner s1 = new Scanner(System.in);
fnum = s1.nextInt();
System.out.println("Enter second number");
Scanner s2 = new Scanner(System.in);
snum = s2.nextInt();
System.out.println("Answer is" +fnum+snum);
}
}

Don't try to copy this source code, understand and try this your own )


Increment Operators


Hey guys, over the past few posts we learnt about math operations. Now we're gonna learn about Increment Operators.

What are these Increment and Decrement Operators ?

Increment and decrement operators are unary operators that add or subtract one from their operand, respectively. They are commonly implemented in imperative programming languages.

It's very simple. let's go through simple exercises

As usual open Eclipses. Then type....

import java.util.*;
public class main {
public static void main(String []args){

int x = 10;

x = x + 1 ;

System.out.println(x);

}
}

OK. Let's see what happened here...

  1. We declare and initialize x variable to 10
  2. Then we say, x equals to x + 1
Yeah I know you are confused. As we learnt in mathematics classes this is a illegal expression. Because in maths ,
                            x = x + 1
                            x - x = 1
                            0 = 1 ????

            Never can be happened !!!!!!!!!!

But in programming of course it is happening...

That means 'x' variable is changing; you are adding '1'  to the value of  'x' . In this case '10 + 1'

How about ...

  1.  x = x + 2;
  2. x = x - 1;
  3. x = x - 2;


Another Example :-

import java.util.*;
public class main {
public static void main(String []args){

int x = 10;

x = x++ ;

System.out.println(x);

}
}

This also means the 'x = x + 1'. 

Conditional Statements

Hey guys, today we're gonna learn about Condition Statements and how it works in java.

Conditional statementsconditional expressions and conditional constructs are features of a programming language, which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false. Apart from the case of branch predication, this is always achieved by selectively altering the control flow based on some condition.
In imperative programming languages, the term "conditional statement" is usually used, whereas in functional programming, the terms "conditional expression" or "conditional construct" are preferred, because these terms all have distinct meanings.
Although dynamic dispatch is not usually classified as a conditional construct, it is another way to select between alternatives at runtime

Ex ; - Student gets the results of an exam and we wanna check 'if' he is pass or fail. 
         Let's take margin as 50 marks.

class main{
public static void main(String []args){
int results = 68;
if (results < 50){
System.out.println("Student is FAIL");
}else{
System.out.println("Student is PASS");

}
}
}
  • Up in there we declared a variable called 'results' as integer & initialized to 68
  • Next a Conditional Statements to check whether the student is pass or fail.
  • In this case 'else' means " if results more than 50 (results > 50).

                               Nested IF Statements

Now we're gonna do something advanced. Now we need find out the 'grade' of the result.
Here we go....

class main{
public static void main(String []args){

int results = 68;

if (results > 75){
System.out.println("Student has A grade");
}else if (results > 60){
System.out.println("Student has B grade");

}else if (results > 50){
System.out.println("Student has C grade");
}else{
System.out.println("Student has FAILED");
}
}

}

  • in first if condition we check whether result is more than 75 or not.
  • If the condition true it executes the code "System.out.println("Student has A grade");"
  • Unless it skips it goes to the next one. If it's true then executes "System.out.println("Student has A grade");"
  • Unless skips & moves onto the next.
  • Finally last code.
That's how the nested if condition works in JAVA


Logic Operations

Hey guys, Today we're gonna learn about Logic Operations.  Logic Operators is a symbol or word
used to connect two or more sentences (of either a formal or a natural language) in a grammatically valid way, such that the sense of the compound sentence produced depends only on the original sentences.

Logic Operators


Simple Assignment Operator

=       Simple assignment operator

Arithmetic Operators

+       Additive operator (also used
        for String concatenation)
-       Subtraction operator
*       Multiplication operator
/       Division operator
%       Remainder operator

Unary Operators

+       Unary plus operator; indicates
        positive value (numbers are 
        positive without this, however)
-       Unary minus operator; negates
        an expression
++      Increment operator; increments
        a value by 1
--      Decrement operator; decrements
        a value by 1
!       Logical complement operator;
        inverts the value of a boolean

Equality and Relational Operators

==      Equal to
!=      Not equal to
>       Greater than
>=      Greater than or equal to
<       Less than
<=      Less than or equal to

Conditional Operators

&&      Conditional-AND
||      Conditional-OR
?:      Ternary (shorthand for 
        if-then-else statement)

Type Comparison Operator

instanceof      Compares an object to 
                a specified type 

Bitwise and Bit Shift Operators

~       Unary bitwise complement
<<      Signed left shift
>>      Signed right shift
>>>     Unsigned right shift
&       Bitwise AND
^       Bitwise exclusive OR
|       Bitwise inclusive OR

See y'll next post..

Switch Statements

Welcome back guys, this time we're gonna learn about Switch Statements.

You may wonder what're these switch statements.. Simply "Multiple IF conditions". 

Let's get ordinary IF condition

         if(x == 0){
System.out.println("Small");
} else if(x== 1){
System.out.println("Medium");
} else if(x == 2){
System.out.println("large");
}else
System.out.println("extra large");

}
You see when comes to a big conditional coding, over and over you have to type if conditions. But using switch statements it's gonna be easy. Take this example and try your own idea.

int x = 3;

switch (x){

case 1: 
System.out.println("Small");
break;
case 2:
System.out.println("Medium");
break;
case 3:
System.out.println("Large");
break;
case 4:
System.out.println("Very Large");
break;
case 5:
System.out.println("Extra Large");
break;
default:
System.out.println("Normal");
break;

}



  1. Always remember to put "break;" to finish the condition. Unless all the conditions will apply.
  2. "default :" should be there, it act as "else". 
That's all...





While Loop

Hey guys, today we're gonna learn about "While Loop".

Then what's this while loop?
In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.

if you have an idea about Flow Charts this would be helpful.

Image result for what's while loop

public class main {

public static void main(String []args){

int counter = 0;                                                             * variable called "counter"

while (counter < 10 ){                                                  * Start the while loop
System.out.println("Hello Blogger!!");             * Print "Hello Blogger"

}                                                                                     * While loop ends

}
}

You'll see this loop will never ever ends because condition always correct. OK let's take an example like this. You wanna display 'Hello World' 10 times.
Simple logic add 1 to counter each time. Let's go ahead

public class main {

public static void main(String []args){

int counter = 0;

while (counter < 10 ){
System.out.println("Hello World!!");
counter = counter + 1;                                           
}

}
}


  1. At the start 'counter' equals to 0. Dispaly "Hello World"
  2. Next add 1. Now the counter equals to 1. Dispaly "Hello World" again.
  3. Again Add 1. counter equals to 2. Dispaly "Hello World".
  4. And so on
When the condition becomes wrong it exits from the loop and go to next statement.






Try your own to make this.

 X = 18. Put X into a while loop & run for 10 times. finally the value of thee X must be 28.


Do-While Loop

Hey guys, now we're gonna learn about Do-While Loop. Yeah I know I know you may wonder the heck is this do-while & what's the difference between while and Do - while loop.

Another simple thing... 

  • While Loop runs the code inside loop, if the condition is true. It's checked from very beginning.  
  • But Do - While Loop runs the code inside loop once, then check whether the condition is true/false.
I think you guys have a good knowledge about while loop & done the exercise that I've given in the previous post.

  • Let's recap...

public class main {

public static void main(String []args){

int counter = 0;

while (counter < 10 ){
System.out.println("Hello World!!");
counter = counter + 1;                                             
}

}
}

  • Now Do- While....


public class main {

public static void main(String []args){
int counter = 0;
do{
System.out.println("Hello World!!");
                        counter = counter + 1;
}
while(counter < 10);
}
}

No difference in with previous the one and this.


Now see this

public class main {

public static void main(String []args){
int counter = 20;
do{
System.out.println("Hello World!!");
                        counter = counter + 1;
}
while(counter < 10);
}
}

Amazing huh !!! It displays "Hello World" once though the condition is false.. That's the Specialty of this Do -While loop