Saturday 15 September 2018

Getting Input From User




In this post, we are going to learn how to get input from the User. Then will do some programming exercises to enhance our programming knowledge.

There are Different - Different ways to get an input from the console -- Go HERE.
 but right now will stick to Scanner Class, because it is the most common and easiest way.

using Scanner Class will get the input from the user,

   
- The Scanner is a  class in java.
- present in java.util package
- which allows the user to read values of various types.
- There are far more methods in class Scanner than you will need in this course.

Syntax:- 


Scanner - is a class in java.

sc - is an object of Scanner class (you can give any name).

new - is an operator which is used to make an object of a class.

Scanner() - is a constructor in Scanner Class(Don't Worry will talk it later).

System - is a class in java, represents your computer system (helps to provide us system-level methods)

in - stands for input (s).

System.in - getting input from the system and it passes as an argument to Scanner Constructor.(Don't Worry, if you are unable to get it). 



# Scanner Class has Somes Methods to get Different kinds of values from the console.

- For different types of values different, types of methods are available.
- For int type nextInt() method is used,
- For double type nextDouble() method used,
- All the methods called by using Scanner Object (sc.method name).
- for example (String value) -- we have to use next() or nextLine().


String s; // variable -- where data store
Scanner sc = new Scanner(System,in); // creating Scanner class object 
s = sc.next(); // getting input from user and assgin it to "s" variable  
sc.close(); // good practic to close resourses.







Question -- WAP to Take two number from the user and return its sum.
Answer -- 



# Code 

package scannerClass;

import java.util.Scanner;

public class Sum {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
System.out.println("Enter 1st number : ");
int num1 =sc.nextInt();
System.out.println("Enter 2nd number : ");
int num2 = sc.nextInt();
int add=num1+num2;
System.out.println("Sum = "+add);
}
}








Friday 14 September 2018

Control Statements (Part 3)




In this post will strictly discuss break and continue statement and then will see some of the programs that will help you to understand the concepts.


Break - 
+ Break statement (Keyword) in java. 
+ When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
+* It can be used to terminate a case in the switch statement.


Continue - 
+ The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.
+ In a for loop, the continue keyword causes control to immediately jump to the update statement(Step).
In a while loop or do/while loop, control immediately jumps to the Boolean expression.




Let's See Some Programs based on this...



Ques 1: WAP (Write a program) to get a number user (1-7) and print its equivalent day.
(without break)



Explanation -  

User enter 5 in the console,
week = 5;
case 5 matches, after execution of case 5
all the rest case will execute because execution of program follows top to down approach.
that why you are getting
Thursday
Friday
Saturday
Invalid day  as an output



Ques 2: WAP (Write a program) to get a number user (1-7) and print its equivalent day.
(with break)




Explanation -  

User enter 5 in the console,
week = 5;
case 5 matches, after execution of case 5 (output is Thursday)
JVM encounter break statement,
all the rest case will not execute because execution of program follows top to down approach.
so after execution of case 5, break statement execute and break statements immediately terminated switch.



Ques 3: WAP (Write a program) to print number from 1 to 10. (Using for loop)

Will see three (3) cases --
 flow of execution of for loop Initialisation -> Condition check -> Loop body -> Iteration/Increment




Case 1: using for loop, printing 1 to 10.


Explanation -  
- for loop is used for counting.
- i =1 (counting start from 1)
- i<=10 (condition - till contidion setisfied, it will counting) 
- i++ increment (every time i=current value of i +1)
- output is 1 to 10.


Case 2:  using for loop, printing 1 to 10 ( with continue).


Explanation -  
- for loop is used for counting.
- i =1 (counting start from 1)
- i<=10 (condition - till condition satisfied, it will counting) 
- i++ increment (every time i=current value of i +1)
- there is an if condition,
  • if condition true - control goes inside if block and continues execute, so when i=5  condition became true and continue statement executed then control goes for next iteration.
  • if condition false - control never goes inside if block so the program will work as above case.




Case 3: using for loop, printing 1 to 10 ( with break).


Explanation -  
- for loop is used for counting.
- i =1 (counting start from 1)
- i<=10 (condition - till condition satisfied, it will counting) 
- i++ increment (every time i=current value of i +1)
- there is an if condition,



  • if condition true - control goes inside if block and continues execute, so when i=5  condition became true and continue statement executed then control goes out of the loop.
  • if condition false - control never goes inside if block so the program will work as above case.



Link to download these two programs... Click Here.



Now, In next post, I will tell you how to get INPUT From USER.
Using Scanner Class.




Control Statements (Part 2)




In this post, will talk about all Control Statements in details and Will see the syntax of it.
In next couple of part will see some of the examples that will definitely help you to understand better,
as well as I will going to give you some basics programming question to solve it.



Syntax - Syntax is the set of rules that defines the combinations of symbols that are considered to be a correctly structured document. (or in short, it is a grammar of programming)


Expression  - Expression is a valid and logical combination of the operator ( athematic and relational ) and number.


Boolean Expression - Boolean Expression is an expression which always gives its result either "true" or "false".




# if Statement


+ If the Boolean Expression / Condition gives true, then whatever written inside if block will execute.
+ If the Boolean Expression / Condition gives false, then whatever written inside if block will never execute.
+ Note - In the place of Boolean Expression / Condition, you can not use 0 or  1 (java is unlike C or C++).



# if else Statement 

+ If the Boolean Expression / Condition gives true, then whatever written in the place of "do this work 1" will execute.
+ If the Boolean Expression / Condition gives false, then whatever written in the place of "do this work 2" will never execute.
Note - In the place of Boolean Expression / Condition, you can not use 0 or  1 (java is unlike C or C++).



# switch Statement


+ The switch statement is also called Integer Based Decision Maker ( till Java 1.4).
+  X can be constant (final) and in the range.
+ in the place of X you can use Number (byte, short, integer), character, wrapper classes (will See later) and string (Sequence of characters).  
+ default is also a case if no case matches then default case will be executed. 
+*  in switch "break" and "continue", these two keywords will be used frequently. (will discuss in next post).



# while loop
+ it is also called Entry Controlled loop because it will check the condition before execution.
+ If the Boolean Expression / Condition gives true, then whatever written inside the block will execute repeatedly.
+ If the Boolean Expression / Condition return false, then whatever written inside the block will never execute and control goes out of the loop.
Note - In the place of Boolean Expression / Condition, you can not use 0 or  1 (java is unlike C or C++).



# do while loop
+ it is also called Exit Controlled loop because condition checks at the time of exit.
+ it will definitely going to be executed at once then checks for the condition.
+ If the Boolean Expression / Condition gives true, then whatever written inside the block will execute again.
+ If the Boolean Expression / Condition return false, then control goes out of the loop.
Note - In the place of Boolean Expression / Condition, you can not use 0 or  1 (java is unlike C or C++).



# for loop


+ it is used for counting purpose
+  it has three steps

  • initialization - counting start from
  • condition - do it, till the condition satisfied
  • step - ascending to descending or descending to ascending
+ above steps are optional 
+ ; (semi-colon) is mandatory.







Control Statements (Part 1)




Control Statements are the statements which are used to make a group of statements and those groups of statements execute on some certain conditions. These are very useful while taking a decision on the basis of some boolean conditions.



In Java, control statements can be divided into the following three categories:

♣  Sequential Statement (Liner Statement)
♣  Selection Statements (Branching)
♣  Iteration Statements (Loop)


# Sequential Statement (Liner Statement) 

In a program, all statements execute one by one.
Staring from 1st statement to till the last statement.
This is called Sequential Statements.

For Example:-

  


# Selection Statements (Branching)

In Selection/Branching, you just make a group of some similar kinds of statement that together performs some specific kind of job.
We use if, if else to make the group of statements.
It is very useful for decision making on the basis of right or wrong  / true false.

For Example:- if, if else, switch



# Iteration Statements (Loop)

these are some group of statements that executed rapidly till a certain condition is not satisfied.
There are only three kinds of looping/iterative statements till now.
1-for loop
2-while loop (Entry Control loop)
3-do while loop (Exit Control loop)









Wednesday 12 September 2018

Operators In JAVA ( Part 2 )




In this post, we discuss some programs and try to understand some core concepts(Remarkable points). One more thing I would like to share with you...

I am not able to write all the programs using all operators .. I can write some important one (That follows some different rules).

But please you guys, practice as much as you can, this is the only way to learn to programming.


 Assignment Operator 

-- Assignment has LOWEST Priority.
-- it is denoted by " = " (equal to sign)
-- always value assign from RIGHT to LEFT


Now, There are three cases may arise.


case 1 - Destination and Source will be EQUAL.

If this is the scenario, then there is no problem.

Let's Take an EXAMPLE -

suppose you have a glass of water ... and you want to transfer it in the different glass with the same type, then you can easily do it without any problem.

case 2 - Destination is GREATER THAN Source.

If this is the scenario, then there is no problem.
It is also called Widening Conversion. 


Let's Take an EXAMPLE -

suppose you have a small glass of water ... and you want to transfer it in a large glass, then you can easily do it without any problem.




case 3 - Destination is SMALLER THAN Source.

If this is the scenario, then you are in big problem.
It is also called Narrow Conversion.
The main problem is that when you are doing this your data may be loose.
And Compiler will not allow Narrow Conversion Directly.

Let's Take an EXAMPLE -

suppose you have a large glass of water ... and you want to transfer it in a small glass, then if water is full in the large glass then some water will be lost during transfer, so you can't do it easily. It is a problem.


To Solve this problem we use TYPE CASTING.

Definition -  Forcing Compiler to allow Narrow Conversion.




Modulus Operator


-- This operator helps to give us the reminder.
-- % (per cent sign) is used for modulus operator. 

System.out.println( 5 % 2 );       // output = 1
System.out.println( -5 % 2 );      // output = 1
System.out.println( 5 % -2 );      // output = -1
System.out.println(-5 % -2);      // output = -1 

Note - In Modulus Operator, Reminder Sign is depends on DENOMINATOR. 



Shift Operator

  1. a>>>n
    • Shift bits of  "a" n times right filling with 0 from left.
  2. a>>n
    • Shift bits of "a" n times right filling with sign bit from left
  3. a<<n
    • Shift bits of "a" n times left filling with 0 from the right.




Now There are some points that you must know -


  1. When every you try to store negative number in your program, then those negative numbers store in 2's compliment.
  2. By default all the numerical value are of type int (means to say that all the calculation internally done in 32 bit memory)
  3. By default all the floating point are of type double (means to say that all the calculation internally done in 64 bit memory) 
  4. if both the operand are either int type or smaller then int (calculation done in 32 bit)
  5. if one or both operand bigger then int type then smaller type promoted to bigger type.
  6. any Integer arithmetic (except /0 or %0 ) always gives result within the range.
  7. Any Integer value  divided by zero gives -- ArithmeticException
  8. Floating point Numbers goes INFINITY.
    • System.out.println(5.0/0); // INFINITY
    • System.out.println(5/0.0); // INFINITY
    • System.out.println(5.0/0.0); // INFINITY
  9. Any Operation which is not possible -- for that java gives NaN (Not a Number) 
  10. we can not use/assign ++ or --  to any constant, it can be only for variable.




Question - Why float f = 10.5; gives error?
Answer - 
//float f = 10.5;  //ERROR
 // error because all the operation done in double (64 bit).So we have to typecast it.
// These are the 3 ways to do it.
float fl = 55.5f;
float f2 = 55.55F;
float  f3 = (float) 555.55;

Question - Full Form & Example of NaN?

Answer - NaN ==> Not a Number 
It comes when you are trying to do the operation at are not possible mathematically.
like finding the square root of a negative number.


        System.out.println(2.0 % 0);
        System.out.println(0.0 / 0);
        System.out.println(Math.sqrt(-1));


*Question - When we use "=" or "= ="?

Answer - " = " used for assignment, from right to left.
" ==  " used for comparison. [will descuss it later]

*Question - How can you say Compound Operators are implicit typecasting?



short s=5;
//short result =s+s;// ERROR Bcoz all the calculation done in 32 bit (int);
short result = (short)(s+s); // type casting required
System.out.println(result);

Or

instead off writing short result = (short)(s+s);
we can also write -- short result +=(s+s); // Called Short Hand Operator.








Operators In JAVA ( Part 1 )




Definition


Operators are the symbols which perform some operation on operands. "



" Expression is any valid combination of operators, constants and variables. "





Before, Start Lets understand two small concept - 
  1. Precedence Level
  2. Associativity Rule
(For more Information - Click Here (Redirect to some other Page) )

# Precedence and Associativity

When expressions contain more than one operator, the order in which the operators are evaluated depends on their precedence levels. A higher precedence operator is evaluated before a lower precedence operator. If the precedence levels of operators are the same, then the order of evaluation depends on their associativity (or, grouping). 


Types of operators

There are two types of operators

     a) On the basis of type of operands 
              1- Unary operator
              2- Binary operator
              3- Ternary operator
     b) On the basis of type, operation performed 
              1- Arithmetic operator
              2- Logical operator
              3- Relational operator
              4- Bitwise operator
              5- Assignment operator
              6- Increment and Decrements operator
              7- Shorthand operator
              8- Conditional operator



A)  On The Basis Of Type Of Number Operands


1- Unary Operator -
These are the operator which operates upon a single operand.
Eg-  +5, +7, -6, -54.7, x++; y--   etc

2-Binary Operator -
These are the operator which operates upon two operands.
Eg-  5+7, 10-8, 15%3, x&&y, a||b   etc.

3- Ternary Operator -
It is the operator which operates upon three operands. It is also called Conditional Operator.
Eg- ?:  (Question mark and colon)



B)  On The Basis Of  Type Of Number Operands

1- Arithmetic Operator- 
This operator is used for the performing arithmetic operation in the Expression.



2- Logical Operator- 
This operator is used to combine logical expiration. It works on Control Statement.



3- Relational Operator-
This operator is used to determine the relationships among different operand.


4- Bitwise Operator- 
This operator is used as like gates. It works on mathematical Expression

 


5- Assignment Operator-
It is used to assign a value to a variable.
Eg-  x=5;

6- Increment and Decrement Operator- 

 


7- Shorthand Operator-
Is used to minimize code length.


8- Conditional Operator-
This operator is used like to select one thing from two things based on the situation.
It is also called Ternary Operator.





Tuesday 11 September 2018

Data Type




Before goes to our Topic, Let's try to understand some basics ...

# KEYWORD 


  • The keyword is the predefined word and it has a predefined meaning.
  • we cannot use it for some other purpose.
  • all the keyword in Java is in a small case.
  • total 53 keywords in java.

Definition - "The Java programming language has 53 keywords. Each keyword has a specific meaning in the language. You can’t use a keyword for anything other than its pre-assigned meaning."


For Ex - 



Now ,
Data Type is also a keyword.
Total 8 Data Types in Java



Question - Suppose I have to store something in the program. Let Say I have to store age, So how I can store age in the program.????

Answer -  Whenever, we need to store something, we need memory. For that, we have to provide its size and type.

Providing size and its type, we have to declare a DATATYPE and to give the name of the memory location is called  VARIABLE.

So, VARIABLE - is the name given to the memory location where some value can be stored.
and
DATA TYPE - is means to identify the type of data and associated operation of handling it.


Now, Come to the question...

To do so, you have to think like... 
  • What I have to store?  ==> I have to story AGE
  • What type of DATA it is?  ==> Number(Numerical kind)
  • How Big Data It is?  ==> maximum 3 digits (Range of the data). 




In Java, We have Four Types Of Data
  • Character Type --> char
  • Numerical Type --> byte, short, int, long
  • Floating Point Type --> float,double
  • Boolean Type (Flag) --> boolean




As a programmer, You don't need to remember the range all the data type.
In Java, you have methods that will tell you all these.

just you have to learn Range Formula.
[WHERE - N SHOULD BE IN BITS]


For Example - 

For Byte -

-128  to  127



# Code 



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

// Integer
byte b = 10;
int i = 11; 
short s = 12;
long l = 129846;

// Double 
float f1 = 1.5f;
//or
float f2 = (float)2.5;
double d = 22.5; // Double

boolean bb1 = true;
boolean bb2 = false;

System.out.println(b+" "+i+" "+s+" "+l); 
System.out.println(f1+" "+f2+" "+d);
System.out.println(bb1+" "+bb2);
}
}


Question --  Why we are getting error " float f = 1.5; "?

Answer -- We have to write this ... because
by default float value is double literal, So to tell the compiler to treat it as float explicitly ---- we have to write it in below ways...

float f1 = 1.5f;  
//or
float f2 = (float)2.5;

Note - [ we can use  " f  " or " F "]