Bollywoodfeeder

Latest Updates

Saturday, 18 November 2017

Every Programmer Should know these 7 Things About Coding

Posted By: Oladiti Atm - November 18, 2017


Learn about the underlying systems

 To have knowledge about programming languages is the main part of software development. It is also very important for developers to be aware about what’s going on lower down the stack.Pete Bull, a support engineer at Acquia said, “Lots of languages abstract away from what is happening at the system level, and that abstraction is useful because it allows developers to be more productive much of the time. But when you hit a roadblock, a really nasty bug, and need a deeper understanding of what’s happening under the hood, well it’s a useful skill to be able to debug a process and look at the system calls and really see how a piece of code is interacting with the rest of the system.
Similarly, Robert Douglass, VP of Customer Satisfaction with Platform.sh told IT World that “When I was just beginning programming, there were a lot of things that I really didn’t understand about computers themselves. File systems, networking, and how things are kept in memory are three obvious examples. This meant that I would not necessarily understand the goals of some of the programming constructs I was being presented with.”

Know command line tools

There are chances that as a developer you may spend most of your time working on a code editor or a fancy IDE. However, also knowing how to execute things at the command line could sometimes make your life easier.
A 20-year veteran programmer, who wished to remain anonymous, told IT World, “Sometimes you find yourself on a machine where stuff has to be done right now and tools are very limited. Know the shell like you know how to breathe. Tools like find, comm, diff, vi/vim, sed, awk. How to write little scripts right on the command line to find the file that needs to change right f’ing now because production is broken and Joe who fat fingered a URL in said unknown file is on vacation in Fiji.”
Bull, who started using Microsoft tools, then slowly moved to Linux, agreed, saying, “I would have learned the ins and outs of the command line and all of the useful utilities that are available on a *nix system. I can actually recall code that I wrote years ago, and probably spent days or weeks working on, that probably could have been done better in a grep + awk one-liner.”

Your debugger is your friend

As a coder, you will be spending majority of your time in tracking down bugs. Dave Varon, a bioinformatics developer at Novartis, highlighted the advantage of a debugger and it how can overshadow the initial costs of your time. “Learn to use your debugger!” he told IT World. “Take that extra day or two to configure it. When you don’t see the expected result, just debug it: set breakpoints, step through your code, and esp. 3rd party code. It will save you days of frustration, and even better, you will learn things about coding you can only learn by reading someone else’s code.”

Learn to write tests

Some developers feel that it is critical to do unit testing, which means to write tests to authenticate that small units of code are doing what they should. Among those people is Richard Handloff, a database developer with Strategic Power Systems. In an email to IT World, he wrote, “I think the best bit of advice I’d give someone who wants to learn to program is to learn to write good tests and learn to write your tests really early in the process.”

Plan on change and learning new systems

With technology changing quickly these days, the underlying systems, languages, and tools used by programmers also go through changes.
Adam Wulf, a mobile developer and founder of Milestone Made, suggests that new coders need to be prepared, and stay ahead of change. “Right now, I’m of the mind that you should plan to learn essentially brand new technology stack every ~ 4 years,” he said. “Good foundational knowledge is always applicable, but the tools and tech you’ll use every day will be completely different every 4 years.”
“Projects are never written in just one language using one framework anymore,” said the developer who wished to remain anonymous. “You are never going to work on just one thing in one project, get used to moving from project to project and from language/technology to language/technology,” he wrote.

Play well with others

Even though the conventional thought is that programmers work alone, developers still have to work with other people. Ben Miller, the CTO of Sinclair Digital Ventures, stressed on the significance of being able to work as a part of team to your career success. “Big projects mean lots of moving parts coming together and how they fit together and divide up the problem can create impossible engineering problems if you aren’t careful.” he wrote via email to IT World. “Before trying to optimize that one algorithm, work with the team and make sure there isn’t a re-division of the problem that makes each person’s problem simpler. Coding is a team sport!”
Reiterating the significance of people skills, Varon says, “If you can’t figure it out yourself by re-intuiting the API or debugging, ask for help. Just because you think you’ve written a masterpiece doesn’t mean it isn’t crap or can’t be better. Just like in college, other people in the room have the same questions, or questions only you can answer. Develop a rapport with colleagues. Often just stating the problem aloud enables a eureka moment.”
An anonymous source who shared a similar thought on the advantages about being a team player told IT World, “Stepping up to the plate and doing what is asked of you even though it is grunt work will keep you employed as well,” he said. In that situation, he also warned, “But be careful, you may get stuck doing it all the time.”

Don’t be afraid to code yourself out of a job

Miller had a rather interesting piece of advice which, at first blush, may not appear instinctive. “Coding yourself out of a job gets you promoted,” he told IT World. “Find the simplest way to solve problems and make your code resilient and maintenance free and people will give you more and more to do. They will even ask you to teach others to do what you do,” he explained. “In short, worrying about (or at least coding for) job security puts a damper on your career.”

INTRODUCTION TO JAVA

Posted By: Oladiti Atm - November 18, 2017

What is Java technology and why do I need it?

Java is a programming language and computing platform first released by Sun Microsystems in 1995. There are lots of applications and websites that will not work unless you have Java installed, and more are created every day. Java is fast, secure, and reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere!
Is Java free to download?
Yes, Java is free to download. Get the latest version at java.com.
If you are building an embedded or consumer device and would like to include Java, please contact Oracle for more information on including Java in your device.
Why should I upgrade to the latest Java version?
The latest Java version contains important enhancements to improve performance, stability and security of the Java applications that run on your machine. Installing this free update will ensure that your Java applications continue to run safely and efficiently.

MORE TECHNICAL INFORMATION
What will I get when I download Java software?
The Java Runtime Environment (JRE) is what you get when you download Java software. The JRE consists of the Java Virtual Machine (JVM), Java platform core classes, and supporting Java platform libraries. The JRE is the runtime portion of Java software, which is all you need to run it in your Web browser.
What is Java Plug-in software?
The Java Plug-in software is a component of the Java Runtime Environment (JRE). The JRE allows applets written in the Java programming language to run inside various browsers. The Java Plug-in software is not a standalone program and cannot be installed separately.
I have heard the terms Java Virtual Machine and JVM. Is this Java software?
The Java Virtual Machine is only one aspect of Java software that is involved in web interaction. The Java Virtual Machine is built right into your Java software download, and helps run Java applications.
» Learn more about Java Technology

1.  Getting Started – Write your First Java Program

You should have already installed Java Development Kit (JDK). Otherwise, Read “How to Install JDK and Get Started with Java Programming“.
Let us begin by writing our first Java program that prints a message “Hello, world!” to the display console, as follows:
Hello, world!
Step 1: Write the Source Code: Enter the following source codes using a programming text editor (such as TextPad or NotePad++ for Windows; jEdit or gedit for Mac OS X; gedit for Ubuntu); or an Interactive Development Environment (IDE) (such as Eclipse or NetBeans).
Do not enter the line numbers (on the left panel), which were added to aid in the explanation. Save the source file as “Hello.java“. A Java source file should be saved with a file extension of “.java“. The filename shall be the same as the classname – in this case “Hello“.
1
2
3
4
5
6
7
8
<span class="color-comment">/*
 * First Java program, which says "Hello, world!"
 */</span>
public class <strong>Hello</strong> {   <span class="color-comment">// Save as "Hello.java"</span>
   public static void main(String[] args) {
      System.out.println("Hello, world!");   <span class="color-comment">// print message</span>
   }
}
Step 2: Compile the Source Code: Compile the source code “Hello.java” into portable bytecode “Hello.class” using JDK Compiler “javac“. Start a CMD Shell (Windows) or Terminal (UNIX/Linux/Mac OS X) and issue this command:
prompt&gt; <strong>javac Hello.java</strong>
There is no need to explicitly compile the source code under IDEs (such as Eclipse or NetBeans), as they perform incremental compilation implicitly.
Step 3: Run the Program: Run the program using Java Runtime “java“, by issuing this command:
prompt&gt; <strong>java Hello</strong>
Hello, world!
Take note that the Run command is “java Hello” without the “.class” extension.
On IDEs (such as Eclipse or NetBeans), right-click on the source file ⇒ Run As… ⇒ Java Application.
Brief Explanation of the Program
/* …… */
// … until the end of the line

These are called comments. Comments are NOT executable and are ignored by the compiler. But they provide useful explanation and documentation to your readers (and to yourself three days later). There are two kinds of comments:
  1. Multi-line Comment: begins with /* and ends with */, and may span more than one lines (as in Lines 1-3).
  2. End-of-line Comment: begins with // and lasts until the end of the current line (as in Lines 4 and 6).
public class Hello { …… }
The basic unit of a Java program is a class. A class called “Hello” is defined via the keyword “class” in Lines 4-8. The {...} is the body of the class. The keyword public will be discussed later.
In Java, the name of the source file must be the same as the name of the public class with a mandatory file extension of “.java“. Hence, this file MUST be saved as “Hello.java“.
public static void main(String[] args) { …… }
Lines 5-7 defines the so-called main() method, which is the starting point, or entry point for program execution. The {...} is the body of the method which contains programming statements.
System.out.println(“Hello, world!”);
In Line 6, the statement System.out.println("Hello, world!") is used to print the message string “Hello, world!” to the display console. A string is surrounded by a pair of double quotes and contain texts. The text will be printed as it is, without the double quotes.

2.  Java Terminology and Syntax

Statement: A programming statement performs a piece of programming action. It must be terminated by a semi-colon (;) (just like an English sentence is ended with a period) as in Lines 6.
Block: A block is a group of programming statements enclosed by braces { }. This group of statements is treated as one single unit. There are two blocks in this program. One contains the body of the classHello. The other contains the body of the main() method. There is no need to put a semi-colon after the closing brace.
Comments: A multi-line comment begins with /* and ends with */. An end-of-line comment begins with // and lasts till the end of the line. Comments are NOT executable statements and are ignored by the compiler. But they provide useful explanation and documentation. Use comments liberally.
Whitespaces: Blank, tab, and newline are collectively called whitespace. Extra whitespaces are ignored, i.e., only one whitespace is needed to separate the tokens. But they could help you and your readers better understand your program. Use extra whitespaces liberally.
Case Sensitivity: Java is case sensitive – a ROSE is NOT a Rose, and is NOT a rose. The filename is also case-sensitive.

3.  Java Program Template

You can use the following template to write your Java programs. Choose a meaningful “Classname” that reflects the purpose of your program, and write your programming statements inside the body of themain() method. Don’t worry about the other terms and keywords now. I will explain them in due course.
1
2
3
4
5
public class <span class="color-new"><em>Classname</em></span> {  <span class="color-comment"> // Choose a meaningful <em>Classname</em>. Save as "<em>Classname</em>.java"</span>
   public static void main(String[] args) {
      <span class="color-new">// Your programming statements here!</span>
   }
}

4.  Output via System.out.println() and System.out.print()

You can use System.out.println() or System.out.print() to print message to the display console:
  • System.out.println(aString) (Print-Line) prints the given aString, and brings the cursor to the beginning of the next line.
  • System.out.print(aString) prints aString but places the cursor after the printed string.
Try the following program and explain the output produced:
1
2
3
4
5
6
7
8
9
10
11
12
<span class="color-comment">/* Test System.out.println() and System.out.print() */</span>
public class <strong>PrintTest</strong> {  <span class="color-comment"> // Save as "PrintTest.java"</span>
   public static void main(String[] args) {
      System.out.println("Hello, world!"); <span class="color-comment">// Advance the cursor to the beginning of next line after printing</span>
      System.out.println();   <span class="color-comment">             // Print a empty line</span>
      System.out.print("Hello, world!");   <span class="color-comment">// Cursor stayed after the printed string</span>
      System.out.println("Hello,");
      System.out.print(" ");   <span class="color-comment">            // Print a space</span>
      System.out.print("world!");
      System.out.println("Hello, world!");
   }
}
Hello, world!
 
Hello, world!Hello,
 world!Hello, world!
Exercises
  1. Print each of the following patterns. Use one System.out.println(...) statement for each line of outputs.
    * * * * *      * * * * *    * * * * *
     * * * * *     *       *     *     *
    * * * * *      *       *      *   * 
     * * * * *     *       *       * *
    * * * * *      * * * * *        *
       (a)            (b)          (c)

5.  Let’s Write a Program to Add a Few Numbers

Let us write a program to add five integers as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<span class="color-comment">/*
 * Sum five numbers and print the result
 */</span>
public class <strong>FiveNumberSum</strong> {  <span class="color-comment"> // Save as "FiveNumberSum.java"</span>
   public static void main(String[] args) {
      int number1 = 11;  <span class="color-comment">// Declare 5 int variables to hold 5 integers</span>
      int number2 = 22;
      int number3 = 33;
      int number4 = 44;
      int number5 = 55;
      int sum;           <span class="color-comment">// Declare an int variable called sum to hold the sum</span>
      sum = number1 + number2 + number3 + number4 + number5;
      System.out.print("The sum is ");   <span class="color-comment">// Print a descriptive string</span>
      System.out.println(sum);   <span class="color-comment">        // Print the value stored in sum</span>
   }
}
The sum is 165
int number1 = 11;
int number2 = 22;
int number3 = 33;
int number4 = 44;
int number5 = 55;

declare five int (integer) variables called number1number2number3number4, and number5; and assignvalues of 11, 22, 33, 44 and 55 to the variables, respectively, via the so-called assignment operator'='. You could also declare many variables in one statement, separating with commas, e.g.,
int number1 = 11, number2 = 22, number3 = 33, number4 = 44, number5 = 55;<code></code>
int sum;
declares an int (integer) variable called sum, without assigning an initial value.
sum = number1 + number2 + number3 + number4 + number5;
computes the sum of number1 to number5 and assign the result to the variable sum. The symbol ‘+‘ denotes arithmetic addition, just like Mathematics.
System.out.print(“The sum is “);
System.out.println(sum);

Line 13 prints a descriptive string. A String is surrounded by double quotes, and will be printed as it is(but without the double quotes). Line 14 prints the value stored in the variable sum (in this case, the sum of the five numbers). You should not surround a variable to be printed by double quotes; otherwise, the text will get printed instead of the value stored in the variable.
READ  How to define and open a file in C programming
Exercise
  1. Modify the above program to print the product of 5 integers. Use a variable called product to hold the product, and * for multiplication.

6.  What is a Program?

sequential flow
program is a sequence of instructions (called programming statements), executing one after another – usually in a sequential manner, as illustrated in the following flow chart.
Example
The following program prints the area and circumference of a circle, given its radius. Take note that the programming statements are executed sequentially – one after another in the order that they are written.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<span class="color-comment">/*
 * Print the area and circumference of a circle, given its radius.
 */</span>
public class <strong>CircleComputation</strong> {  <span class="color-comment">// Saved as "CircleComputation.java"</span>
   public static void main(String[] args) {
      <span class="color-comment">// Declare variables</span>
      double radius, area, circumference;
      final double PI = 3.14159265;
      
      <span class="color-comment">// Assign a value to radius</span>
      radius = 1.2;
      
      <span class="color-comment">// Compute area and circumference</span>
      area = radius * radius * PI;
      circumference = 2.0 * radius * PI;
      
      <span class="color-comment">// Print results</span>
      System.out.print("The radius is ");  <span class="color-comment">// Print description</span>
      System.out.println(radius);          <span class="color-comment">// Print the value stored in the variable</span>
      System.out.print("The area is ");
      System.out.println(area);
      System.out.print("The circumference is ");
      System.out.println(circumference);
   }
}
The radius is 1.2
The area is 4.523893416
The circumference is 7.5398223600000005
double radius, area, circumference;declare three double variables radiusarea and circumference. A double variable can hold real numbers (or floating-point numbers, with an optional fractional part).
final double PI = 3.14159265;declare a double variables called PI and assign a value. PI is declared final, i.e., its value cannot be changed.
radius = 1.2;
assigns a value to the variable radius.
area = radius * radius * PI;
circumference = 2.0 * radius * PI;
compute the area and circumference, based on the radius.
System.out.print(“The radius is “);
System.out.println(radius);
System.out.print(“The area is “);
System.out.println(area);
System.out.print(“The circumference is “);
System.out.println(circumference);
print the results with proper descriptions.

Take note that the programming statements inside the main() are executed one after another, in a sequential manner.
Exercises
  1. Follow the above example, write a program (called RectangleComputation) to print the area and perimeter of a rectangle, given its length and width in doubles.
  2. Follow the above example, write a program (called CylinderComputation) to print the surface area and volume of a cylinder, given its radius and height in doubles.

7.  What is a Variable?

Computer programs manipulate (or process) data. A variable is used to store a piece of data for processing. It is called variable because you can change the value stored.
More precisely, a variable is a named storage location, that stores a value of a particular data type. In other words, a variable has a name, a type and stores a value of that type.
  • A variable has a name (or identifier), e.g., radiusareaageheight. The name is needed to uniquely identify each variable, so as to assign a value to the variable (e.g., radius=1.2), and retrieve the value stored (e.g., radius*radius*3.1416).
  • A variable has a type. Examples of type are:
    • int: for integers (whole numbers) such as 123 and -456;
    • double: for floating-point or real numbers, such as 3.1416-55.667.8e9-1.2e3.4 having an optional decimal point and fractional part, in fixed or scientific notations;
    • String: for texts such as "Hello""Good Morning!". Text strings are enclosed within a pair of double quotes.
  • A variable can store a value of that particular type. It is important to take note that a variable in most programming languages is associated with a type, and can only store value of the particular type. For example, a int variable can store an integer value such as 123, but NOT real number such as 12.34, nor texts such as "Hello". The concept of type was introduced into the early programming languages to simplify interpretation of data.
The following diagram illustrates three types of variables: intdouble and String. An int variable stores an integer (whole number). A double variable stores a real number. A String variable stores texts.
variable
To use a variable, you need to first declare its name and type, in one of the following syntaxes:
<em>varType</em> <em>varName</em>;                 <span class="color-comment">// Declare a variable of a type</span>
<em>varType</em> <em>varName1</em>, <em>varName2</em>,...;  <span class="color-comment">// Declare multiple variables of the same type</span>
<em>varType</em> <em>varName </em>= <em>initialValue</em>;  <span class="color-comment">// Declare a variable of a type, and assign an initial value</span>
<em>varType</em> <em>varName1 </em>= <em>initialValue1</em>, <em>varName2 </em>= <em>initialValue2</em>,... ;  <span class="color-comment">// Declare variables with initial values</span>
Take note that:
  • Each declaration statement is terminated with a semi-colon (;).
  • In multiple-variable declaration, the names are separated by commas (,).
  • The symbol =, known as the assignment operator, can be used to assign an initial value (of the declared type) to the variable.
For example,
int sum;              <span class="color-comment">// Declare a variable named "sum" of the type "int" for storing an integer.
                      // Terminate the statement with a semi-colon.</span>
int number1, number2; <span class="color-comment">// Declare 2 "int" variables named "number1" and "number2", separated by a comma.</span>
double average;       <span class="color-comment">// Declare a variable named "average" of the type "double" for storing a real number.</span>
int height = 20;      <span class="color-comment">// Declare an "int" variable, and assign an initial value.</span>
Once a variable is declared, you can assign and re-assign a value to the variable, via the so-called assignment operator'='. For example,
int number;   <span class="color-comment">        // Declare a variable named "number" of the type "int" (integer).</span>
number = 99;  <span class="color-comment">        // Assign an integer value of 99 to the variable "number".</span>
number = 88;  <span class="color-comment">        // Re-assign a value of 88 to "number".</span>
number = number + 1;  <span class="color-comment">// Evaluate "number + 1", and assign the result back to "number".</span>
int sum = ;  <span class="color-comment">        // Declare an int variable named "sum" and assign an initial value of 0.</span>
sum = sum + number;  <span class="color-comment"> // Evaluate "sum + number", and assign the result back to "sum", i.e. add number into sum.</span>
int num1 = 5, num2 = 6;  <span class="color-comment">// Declare and initialize two int variables in one statement, separated by a comma.</span>
double radius = 1.5;  <span class="color-comment">// Declare a variable name "radius", and initialize to 1.5.</span>
<span class="color-error">int number;</span>           <span class="color-comment">// ERROR: A variable named "number" has already been declared.</span>
<span class="color-error">sum = 55.66;</span>          <span class="color-comment">// ERROR: The variable "sum" is an int. It cannot be assigned a floating-point number.</span>
<span class="color-error">sum = "Hello";</span>        <span class="color-comment">// ERROR: The variable "sum" is an int. It cannot be assigned a text string.</span>
Take note that:
  • Each variable can only be declared once. (You cannot have two houses with the same address.)
  • You can declare a variable anywhere inside the program, as long as it is declared before it is being used.
  • Once the type of a variable is declared, it can only store a value of this particular type. For example, an int variable can hold only integer such as 123, and NOT floating-point number such as -2.17 or text string such as "Hello".
  • The type of a variable cannot be changed inside the program, once declared.
I have shown your two data types in the above example: int for integer and double for floating-point number (or real number). Take note that in programming, int and double are two distinct types and special caution must be taken when mixing them in an operation, which shall be explained later.
x=x+1?
Assignment (=) in programming is different from equality in Mathematics. e.g., “x=x+1” is invalid in Mathematics. However, in programming, it means compute the value of x plus 1, and assign the result back to variable x.
“x+y=1” is valid in Mathematics, but is invalid in programming. In programming, the RHS of “=” has to be evaluated to a value; while the LHS shall be a variable. That is, evaluate the RHS first, then assign to LHS.
Some languages uses := as the assignment operator to avoid confusion with equality.

8.  Basic Arithmetic Operations

The basic arithmetic operations are:
OperatorMeaningExample
+Additionx + y
-Subtractionx - y
*Multiplicationx * y
/Divisionx / y
%Modulus (Remainder)x % y
++Increment by 1 (Unary)++x or x++
--Decrement by 1 (Unary)--x or x--
Addition, subtraction, multiplication, division and remainder are binary operators that take two operands (e.g., x + y); while negation (e.g., -x), increment and decrement (e.g., x++--x) are unary operatorsthat take only one operand.
Example
The following program illustrates these arithmetic operations:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<span class="color-comment">/**
 * Test Arithmetic Operations
 */</span>
public class <strong>ArithmeticTest</strong> {     <span class="color-comment">// Save as "ArithmeticTest.java"</span>
   public static void main(String[] args) {
   
      int number1 = 98;     <span class="color-comment">// Declare an int variable number1 and initialize it to 98</span>
      int number2 = 5;      <span class="color-comment">// Declare an int variable number2 and initialize it to 5</span>
      int sum, difference, product, quotient, remainder;  <span class="color-comment">// Declare five int variables to hold results</span>
   
      <span class="color-comment">// Perform arithmetic Operations</span>
      sum = number1 + number2;
      difference = number1 - number2;
      product = number1 * number2;
      quotient = number1 / number2;
      remainder = number1 % number2;
  
      <span class="color-comment">// Print results</span>
      System.out.print("The sum, difference, product, quotient and remainder of ");  <span class="color-comment">// Print description</span>
      System.out.print(number1);      <span class="color-comment">// Print the value of the variable</span>
      System.out.print(" and ");
      System.out.print(number2);
      System.out.print(" are ");
      System.out.print(sum);
      System.out.print(", ");
      System.out.print(difference);
      System.out.print(", ");
      System.out.print(product);
      System.out.print(", ");
      System.out.print(quotient);
      System.out.print(", and ");
      System.out.println(remainder);
   
      ++number1;  <span class="color-comment">// Increment the value stored in the variable "number1" by 1
                  // Same as "number1 = number1 + 1"</span>
      --number2;  <span class="color-comment">// Decrement the value stored in the variable "number2" by 1
                  // Same as "number2 = number2 - 1"</span>
      System.out.println("number1 after increment is " + number1);<span class="color-comment">  // Print description and variable
</span>      System.out.println("number2 after decrement is " + number2);
      quotient = number1 / number2; 
      System.out.println("The new quotient of " + number1 + " and " + number2 
            + " is " + quotient);
   }
}
The sum, difference, product, quotient and remainder of 98 and 5 are 103, 93, 490, 19, and 3
number1 after increment is 99
number2 after decrement is 4
The new quotient of 99 and 4 is 24
Dissecting the Program
int number1 = 98;
int number2 = 5;
int sum, difference, product, quotient, remainder;
declare all the int (integer) variables number1number2sumdifferenceproductquotient, and remainder, needed in this program.
READ  Every Programmer Should know these 7 Things About Coding
sum = number1 + number2;
difference = number1 – number2;
product = number1 * number2;
quotient = number1 / number2;
remainder = number1 % number2;
carry out the arithmetic operations on number1 and number2. Take note that division of two integers produces a truncated integer, e.g., 98/5 → 1999/4 → 24, and 1/2 → 0.
System.out.print(“The sum, difference, product, quotient and remainder of “);
……
prints the results of the arithmetic operations, with the appropriate string descriptions in between. Take note that text strings are enclosed within double-quotes, and will get printed as they are, including the white spaces (but without the double quotes). To print the value stored in a variable, no double quotes should be used. For example,
System.out.println("sum");   <span class="color-comment">// Print text string "sum" - as it is</span>
System.out.println(sum);     <span class="color-comment">// Print the value stored in variable sum, e.g., 98</span>
++number1;
–number2;
illustrate the increment and decrement operations. Unlike '+''-''*''/' and '%', which work on two operands (binary operators), '++' and '--' operate on only one operand (unary operators). ++x is equivalent to x = x + 1, i.e., increment x by 1. You may place the increment operator before or after the operand, i.e., ++x (pre-increment) or x++(post-increment). In this example, the effects of pre-increment and post-increment are the same. I shall point out the differences in later section.
System.out.println(“number1 after increment is ” + number1);
System.out.println(“number2 after decrement is ” + number2);
print the new values stored after the increment/decrement operations. Take note that instead of using many print()statements as in Lines 17-30, we could simply place all the items (text strings and variables) into one println(), with the items separated by '+'. In this case, '+' does not perform addition. Instead, it concatenates or joins all the items together.
Exercises
  1. Combining Lines 19-32 into one single println() statement, using '+' to concatenate all the items together.
  2. Introduce one more int variable called number3, and assign it an integer value of 77. Compute and print the sum and product of all the three numbers.
  3. In Mathematics, we could omit the multiplication sign in an arithmetic expression, e.g., x = 5a + 4b. In programming, you need to explicitly provide all the operators, i.e., x = 5*a + 4*b. Try printing the sum of 31 times of number1 and 17 times of number2 and 87 time of number3.

9.  What If Your Need To Add a Thousand Numbers? Use a Loop

Suppose that you want to add all the integers from 1 to 1000. If you follow the previous example, you would require a thousand-line program! Instead, you could use a so-called loop in your program to perform a repetitive task, that is what the computer is good at.
Example
Try the following program, which sums all the integers from a lowerbound (=1) to an upperbound (=1000) using a so-called while-loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<span class="color-comment">/*
 * Sum from a lowerbound to an upperbound using a while-loop
 */</span>
public class RunningNumberSum { <span class="color-comment"> // Save as "RunningNumberSum.java"</span>
   public static void main(String[] args) {
      int lowerbound = 1;     <span class="color-comment"> // Store the lowerbound</span>
      int upperbound = 1000;  <span class="color-comment"> // Store the upperbound</span>
      int sum = 0;  <span class="color-comment"> // Declare an int variable "sum" to accumulate the numbers</span>
                    <span class="color-comment"> // Set the initial sum to 0</span>
     <span class="color-comment"> // Use a while-loop to repeatitively sum from the lowerbound to the upperbound</span>
      int number = lowerbound;
      while (number &lt;= upperbound) {
         sum = sum + number; <span class="color-comment"> // Accumulate number into sum</span>
         ++number;           <span class="color-comment"> // Next number</span>
      }
     <span class="color-comment"> // Print the result</span>
      System.out.println("The sum from " + lowerbound + " to " + upperbound + " is " + sum);
   }
}
The sum from 1 to 1000 is 500500
Dissecting the Program
int lowerbound = 1;
int upperbound = 1000;
declare two int variables to hold the upperbound and lowerbound, respectively.
int sum = 0;declares an int variable to hold the sum. This variable will be used to accumulate numbers over the steps in the repetitive loop, and thus initialized to 0.
int number = lowerbound;
while (number <= upperbound) {
sum = sum + number;
++number;
}
This is the so-called while-loop. A while-loop takes the following syntax:
for-loop
<em>initialization-statement</em>;
<strong>while (</strong><em>test</em><strong>) {</strong>
   <em>loop-body</em><strong>;</strong>
<strong>}</strong>
<em>next-statement</em>;
As illustrated in the flow chart, the initialization statement is first executed. The test is then checked. If the test is true, the body is executed. The test is checked again and the process repeats until the testis false. When the test is false, the loop completes and program execution continues to the next statement after the loop.
In our program, the initialization statement declares an int variable named number and initializes it to lowerbound. The test checks if number is equal to or less than the upperbound. If it is true, the current value of number is added into the sum, and the statement ++number increases the value ofnumber by 1. The test is then checked again and the process repeats until the test is false (i.e., number increases to upperbound+1), which causes the loop to terminate. Execution then continues to the next statement (in Line 23).
In this example, the loop repeats upperbound-lowerbound+1 times. After the loop is completed, Line 17 prints the result with a proper description.
System.out.println(“The sum from ” + lowerbound + ” to ” + upperbound + ” is ” + sum);prints the results.
Exercises
  1. Modify the above program to sum all the numbers from 9 to 888. (Ans394680.)
  2. Modify the above program to sum all the odd numbers between 1 to 1000. (Hint: Change the post-processingstatement to “number = number + 2“. Ans250000)
  3. Modify the above program to sum all the numbers between 1 to 1000 that are divisible by 7. (Hint: Modify the initialization and post-processing statements. Ans71071.)
  4. Modify the above program to find the sum of the square of all the numbers from 1 to 100, i.e. 1*1 + 2*2 + 3*3 +... (Ans338350.)
  5. Modify the above program (called RunningNumberProduct) to compute the product of all the numbers from 1 to 10. (Hint: Use a variable called product instead of sum and initialize product to 1. Ans:3628800.)

10.  Conditional (or Decision)

What if you want to sum all the odd numbers and also all the even numbers between 1 and 1000? There are many ways to do this. You could declare two variables: sumOdd and sumEven. You can then use aconditional statement to check whether the number is odd or even, and accumulate the number into the respective sums. The program is as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
23
24
<span class="color-comment">/*
 * Sum the odd numbers and the even numbers from a lowerbound to an upperbound
 */</span>
public class <strong>OddEvenSum</strong> {  <span class="color-comment">// Save as "OddEvenSum.java"</span>
   public static void main(String[] args) {
      int lowerbound = 1, upperbound = 1000;  <span class="color-comment">// lowerbound and upperbound</span>
      int sumOdd  = 0;    <span class="color-comment">// For accumulating odd numbers, init to 0</span>
      int sumEven = 0;    <span class="color-comment">// For accumulating even numbers, init to 0</span>
      int number = lowerbound;
      while (number &lt;= upperbound) {
         if (number % 2 == 0) {  <span class="color-comment">// Even</span>
            sumEven += number;   <span class="color-comment">// Same as sumEven = sumEven + number</span>
         } else {   <span class="color-comment">             // Odd</span>
            sumOdd += number;    <span class="color-comment">// Same as sumOdd = sumOdd + number</span>
         }
         ++number;  <span class="color-comment">// Next number</span>
      } 
      <span class="color-comment">// Print the result</span>
      System.out.println("The sum of odd numbers from " + lowerbound + " to " + upperbound + " is " + sumOdd);
      System.out.println("The sum of even numbers from " + lowerbound + " to " + upperbound + "  is " + sumEven);
      System.out.println("The difference between the two sums is " + (sumOdd - sumEven));
   }
}
The sum of odd numbers from 1 to 1000 is 250000
The sum of even numbers from 1 to 1000  is 250500
The difference between the two sums is -500
Dissecting the Program
int lowerbound = 1, upperbound = 1000;declares the upperbound and lowerbound for the loop.
int sumOdd = 0;
int sumEven = 0;
declare two int variables named sumOdd and sumEven and initialize them to 0, for accumulating the odd and even numbers, respectively.
if (number % 2 == 0) {
sumEven = sumEven + number;
} else {
sumOdd = sumOdd + number;
}
This is a conditional statement. The conditional statement can take one these forms: if-then or if-then-else.
if-then-elseif-then
<span class="color-comment">// if-then</span>
<strong>if (</strong> <em>test</em> <strong>) {</strong>
   <em>true-body</em><strong>;</strong>
<strong>}</strong>
<span class="color-comment">// if-then-else</span>
<strong>if (</strong> <em>test</em> <strong>) {</strong>
   <em>true-body</em><strong>;</strong>
<strong>} else {</strong>
   <em>false-body</em><strong>;</strong>
<strong>}</strong>
For a if-then statement, the true-body is executed if the test is true. Otherwise, nothing is done and the execution continues to the next statement. For a if-then-else statement, the true-body is executed if the test is true; otherwise, the false-body is executed. Execution is then continued to the next statement.
READ  How to define and open a file in C programming
In our program, we use the remainder operator (%) to compute the remainder of number divides by 2. We then compare the remainder with to test for even number.
Comparison Operators
There are six comparison (or relational) operators:
OperatorMeaningExample
==Equal tox == y
!=Not equal tox != y
>Greater thanx > y
>=Greater than or equal tox >= y
<Less thanx < y
<=Less than or equal tox <= y
Take note that the comparison operator for equality is a double-equal sign (==); whereas a single-equal sign (=) is the assignment operator.
Combining Simple Conditions
Suppose that you want to check whether a number x is between 1 and 100 (inclusive), i.e., 1 <= x <= 100. There are two simple conditions here, (x >= 1) AND (x <= 100). In programming, you cannot write 1 <= x <= 100, but need to write (x >= 1) && (x <= 100), where “&&” denotes the “AND” operator. Similarly, suppose that you want to check whether a number x is divisible by 2 OR by 3, you have to write (x % 2 == 0) || (x % 3 == 0) where “||” denotes the “OR” operator.
There are three so-called logical operators that operate on the boolean conditions:
OperatorMeaningExample
&&Logical AND(x >= 1) && (x <= 100)
||Logical OR(x < 1) || (x > 100)
!Logical NOT!(x == 8)
For examples:
<span class="color-comment">// Return true if x is between 0 and 100 (inclusive)</span>
(x &gt;= 0) &amp;&amp; (x &lt;= 100)  <span class="color-comment">// AND (&amp;&amp;)</span>
<span class="color-comment">// Incorrect to use 0 &lt;= x &lt;= 100</span>
  
<span class="color-comment">// Return true if x is outside 0 and 100 (inclusive)</span>
(x &lt; 0) || (x &gt; 100)       <span class="color-comment">// OR (||)</span>
!((x &gt;= 0) &amp;&amp; (x &lt;= 100))  <span class="color-comment">// NOT (!), AND (&amp;&amp;)</span>
 
<span class="color-comment">// Return true if "year" is a leap year</span>
<span class="color-comment">// A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400.</span>
((year % 4 == 0) &amp;&amp; (year % 100 != 0)) || (year % 400 == 0)
Exercises
  1. Write a program to sum all the integers between 1 and 1000, that are divisible by 13, 15 or 17, but not by 30.
  2. Write a program to print all the leap years between AD1 and AD2010, and also print the number of leap years. (Hints: use a variable called count, which is initialized to zero. Increment the countwhenever a leap year is found.)

11.  Type double and Floating-Point Numbers

Recall that a variable in Java has a name and a type, and can hold a value of only that particular type. We have so far used a type called int. A int variable holds an integer, such as 123 and -456; it cannot hold a real number, such as 12.34.
In programming, real numbers such as 3.1416 and -55.66 are called floating-point numbers, and belong to a type called double. You can express floating-point numbers in fixed notation (e.g., 1.23-4.5) or scientific notation (e.g., 1.2e3-4E5.6) where e or E denote the exponent of base 10.
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<span class="color-comment">/*
 * Convert temperature between Celsius and Fahrenheit
 */</span>
public class ConvertTemperature { <span class="color-comment"> // Save as "ConvertTemperature.java"</span>
   public static void main(String[] args) {
      double celsius, fahrenheit;
 
      celsius = 37.5;
      fahrenheit = celsius * 9.0 / 5.0 + 32.0;
      System.out.println(celsius + " degree C is " + fahrenheit + " degree F.");
 
      fahrenheit = 100.0;
      celsius =  (fahrenheit - 32.0) * 5.0 / 9.0;
      System.out.println(fahrenheit + " degree F is " + celsius + " degree C.");
 
   }
}
37.5 degree C is 99.5 degree F.
100.0 degree F is 37.77777777777778 degree C.

12.  Mixing int and double, and Type Casting

Although you can use a double to keep an integer value (e.g., double count = 5.0), you should use an int for integer, as int is far more efficient than double (e.g., in terms of running times, storage, among others).
At times, you may need both int and double in your program. For example, keeping the sum from 1 to 1000 as int, and their average as double. You need to be extremely careful when different types are mixed.
It is important to note that:
  • Arithmetic operations ('+''-''*''/') of two int‘s produce an int; while arithmetic operations of two double‘s produce a double. Hence, 1/2 → 0 and 1.0/2.0 → 0.5.
  • Arithmetic operations of an int and a double produce a double. Hence, 1.0/2 → 0.5 and 1/2.0 → 0.5.
You can assign an integer value to a double variable. The integer value will be converted to a double value automatically, e.g., 3 → 3.0. For example,
int i = 3;
double d;
d = i;    <span class="color-comment">// 3 → 3.0, d = 3.0</span>
d = 88;   <span class="color-comment">// 88 → 88.0, d = 88.0</span>
double nought = ;  <span class="color-comment">// 0 → 0.0; there is a subtle difference between int 0 and double 0.0</span>
However, you CANNOT assign a double value directly to an int variable. This is because the fractionalpart could be lost, and the compiler signals an error in case that you were not aware. For example,
double d = 5.5;
int i;
<span class="color-error">i = d;</span>     <span class="color-comment">// error: possible loss of precision</span>
<span class="color-error">i = 6.6;</span>   <span class="color-comment">// error: possible loss of precision</span>
Type Casting Operators
To assign an double value to an int variable, you need to explicitly invoke a type-casting operation to truncate the fractional part, as follows:
(<em>new-type</em>)<em>expression</em>;
For example,
double d = 5.5;
int i;
i = (int) d;   <span class="color-comment">     // Type-cast the value of double d, which returns an int value,
                    // assign the resultant int value to int i</span>.
<span class="color-comment">                    // The value stored in d is not affected.</span>
i = (int) 3.1416;   <span class="color-comment">// i = 3</span>
Take note that type-casting operator, in the form of (int) or (double), applies to one operand immediately after the operator (i.e., unary operator).
Type-casting is an operation, like increment or addition, which operates on a operand and return a value (in the specified type), e.g., (int)3.1416 takes a double value of 3.1416 and returns 3 (of type int);(double)5 takes an intvalue of 5 and returns 5.0 (of type double).
Example
Try the following program and explain the outputs produced:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<span class="color-comment">/*
 * Find the sum and average from a lowerbound to an upperbound
 */</span>
public class <strong>TypeCastingTest</strong> {   <span class="color-comment">// Save as "TypeCastingTest.java"</span>
   public static void main(String[] args) {
      int lowerbound = 1, upperbound = 1000;
      int sum = 0;      <span class="color-comment">// sum is "int"</span>
      double average;   <span class="color-comment">// average is "double"</span><span class="color-comment">
 
      // Compute the sum (in "int")</span>
      int number = lowerbound;
      while (number &lt;= upperbound) {
         sum = sum + number;
         ++number;
      }
      System.out.println("The sum from " + lowerbound + " to " + upperbound + " is " + sum);
 
      <span class="color-comment">// Compute the average (in "double")</span>
      average = sum / (upperbound - lowerbound + 1);
      System.out.println("Average 1 is " + average);
      average = (double)sum / (upperbound - lowerbound + 1);
      System.out.println("Average 2 is " + average);
      average = sum / 1000;
      System.out.println("Average 3 is " + average);
      average = sum / 1000.0;
      System.out.println("Average 4 is " + average);
      average = (double)(sum / 1000);
      System.out.println("Average 5 is " + average);
   }
}
The sum from 1 to 1000 is 500500
Average 1 is 500.0  <span class="color-comment">&lt;== incorrect</span>
Average 2 is 500.5
Average 3 is 500.0  <span class="color-comment">&lt;== incorrect</span>
Average 4 is 500.5
Average 5 is 500.0  <span class="color-comment">&lt;== incorrect</span>
The first average is incorrect, as int/int produces an int (of 500), which is converted to double (of 500.0) to be stored in average (of double).
For the second average, the value of sum (of int) is first converted to double. Subsequently, double/intproduces a double.
For the fifth average, int/int produces an int (of 500), which is casted to double (of 500.0) and assigned to average (of double).
Exercises
  1. Write a program called HarmonicSeriesSum to compute the sum of a harmonic series 1 + 1/2 + 1/3 + 1/4 + .... + 1/n, where n = 1000. Keep the sum in a double variable, and take note that1/2gives but 1.0/2 gives 0.5.
    Try computing the sum for n=100050001000050000100000.
    Hints:
    public class <strong>HarmonicSeriesSum</strong> {   <span class="color-comment">// Saved as "HarmonicSeriesSum.java"</span>
       public static void main (String[] args) {
          int numTerms = 1000;
          double sum = 0.0;      <span class="color-comment">// For accumulating sum in double</span>
          int denominator = 1;
          while (denominator &lt;= numTerms) {
              <span class="color-comment">// Beware that int/int gives int</span>
              ......
              ++denominator;  <span class="color-comment">// next</span>
          }
          <span class="color-comment">// Print the sum</span>
          ......
       }
    }
  2. Modify the above program (called GeometricSeriesSum) to compute the sum of this series: 1 + 1/2 + 1/4 + 1/8 + .... (for 1000 terms). (Hints: Use post-processing statement of denominator = denominator * 2.)

Copyright © 2017 Bollywoodfeeder™

Designed by Trendnewsng