Tuesday, January 26, 2016

Java Primitive Data Types and Operations

Topic 01 : Introduction


  • Trace a Program Execution 



Topic 02  : Identifiers & Variables 


  • Identifiers


  1. An identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($).
  2. An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit.
  3. An identifier cannot be a reserved word.
  4. An identifier cannot be true, false, or null.
  5. An identifier can be of any length.

  • Declaring Variables 


              int x;   // Declare x to be an integer variable;               double radius;  // Declare radius to be a double variable;               char a;   // Declare a to be a character variable; 

  • Assignment Variables
            x = 1;   // Assign 1 to x; 


             radius = 1.0;  // Assign 1.0 to radius;
             a = ‘A’;   // Assign ‘A’ to a;

  • Declaring and Initializing in One Step 


            int x = 1;  // Declare x to be an integer variable    // And assign 1 to x
            double d = 1.4;  // Declare d to be a double variable    // And assign 1.4 to d

  • Constants 
final datatype CONSTANTNAME = VALUE; 


             final double PI = 3.14159; 

             final int SIZE = 3; 

Topic 03 : Numbers 

  • Numerical Data Types

  • Numeric Operators



  • 5 / 2 yields an integer 2 
  • 5.0 / 2 yields an double value 2.5 
  •  5 % 2 yields 1 (the remainder of the division)

  • Remainder Operator

          Remainder is very useful in programming. For example, an even number % 2 is always 0 and an odd number % 2 is always 1. So you can use this property to determine whether a number is even or odd. Suppose today is Saturday and you and your friends are going to meet in 10 days. What day is in 10 days? You can find that day is Tuesday using the following expression:


Example : Displaying Time

        Write a program that obtains hours and minutes from seconds. 

         public class DisplayTime {     
              public static void main(String[] args) {  
                     int seconds = 10000;          
                     int totalMinutes = seconds / 60;         
                     int hours =  totalMinutes / 60;  
                     int minutes = totalMinutes % 60;  
                     System.out.println( seconds + " seconds is " + hours +  " hours and " + minutes + "                                                           minutes");      
                 } 
            } 


  • NOTE 
           Calculations involving floating-point numbers are approximated because these numbers are not stored with complete accuracy. For example,

System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);
 displays 0.5000000000000001, not 0.5, and   
System.out.println(1.0 - 0.9); 
displays 0.09999999999999998, not 0.1. 
 Integers are stored precisely. Therefore, calculations with integers yield a precise integer result. 

  • Number Literals 

     A literal is a constant value that appears directly in the program. For example, 34, 1,000,000, and 5.0 are literals in the following statements:
              - int i = 34;
              - long x = 1000000;
              - double d = 5.0;

  • Integer Literals 


     An integer literal can be assigned to an integer variable as long as it can fit into the variable. A compilation error would occur if the literal were too large for the variable to hold.       For example, the statement byte b = 1000 would cause a compilation error, because 1000 cannot be stored in a variable of the byte type.
     An integer literal is assumed to be of the int type, whose value is between -231 (-2147483648) to 231–1 (2147483647).
     To denote an integer literal of the long type, append it with the letter L or l. L is preferred because l (lowercase L) can easily be confused with 1 (the digit one).

  • Floating-Point Literals 


     Floating-point literals are written with a decimal point. By default, a floating-point literal is treated as a double type value.      For example, 5.0 is considered a double value, not a float value.
     You can make a number a float by appending the letter f or F, and make a number a double by appending the letter d or D.       For example, you can use 100.2f or 100.2F for a float number, and 100.2d or 100.2D for a double number.

  • Scientific Notation 

     Floating-point literals can also be specified in scientific notation, for example, 1.23456e+2, same as 1.23456e2, is equivalent to 123.456, and 1.23456e-2 is equivalent to 0.0123456. E (or e) represents an exponent and it can be either in lowercase or uppercase.

  • Arithmetic Expressions 


Example : Converting Temperatures 

     Write a program that converts a Fahrenheit degree to Celsius using

the formula: 


            public class CLASSNAME {
                      public static void main(String[] args) {
                      // your statements…
                            System.out.println ( “RESULT MESSAGE“ );
                       }
                }

Example : Converting Temperatures 

public class FahrenheitToCelsius {    
        public static void main(String[] args) {
              double fahrenheit = 100;      
              double celsius = (5.0 / 9) * (fahrenheit - 32);

               System.out.println(“Fahrenheit " + fahrenheit +  " is " +  celsius + " in Celsius");    
         } }

  • Shortcut Assignment Operators 


  • Increment and Decrement Operators


        Using increment and decrement operators makes expressions short, but it also makes them complex and difficult to read. Avoid using these operators in expressions that modify multiple variables, or the same variable for multiple times such as this : int k = ++i + i.

  • Numeric Type Conversion 


     When performing a binary operation involving two operands of different types, Java automatically converts the operand based on the following rules:  
1. If one of the operands is double, the other is converted into double.
2. Otherwise, if one of the operands is float, the other is converted into float.
3. Otherwise, if one of the operands is long, the other is converted into long.
4. Otherwise, both operands are converted into int.


  • Type Casting 


            Implicit Casting 

                double d = 3; ( Type Widening )

            Explicit Casting 

                 int i = (int)3.0; (type narrowing)
                 int i = (int)3.9; (Fraction part is truncated)

  • Range



Monday, January 25, 2016

Anatomy of a JAVA Program


  • Comments 

    In Java, comments are preceded by two slashes (//) in a line, or enclosed between /* and */ in one or multiple lines. When the compiler sees //, it ignores all text after // in the same line. When it sees /*, it scans for the next */ and ignores any text between /* and */.

  • Package 

    A package is a grouping of related types providing access protection and name space management. Note that types refers to classes, interfaces, enumerations, and annotation types. Enumerations and annotation types are special kinds of classes and interfaces, respectively, so types are often referred to in this lesson simply as classes and interfaces.

  • Reserved Words

  • Reserved words or keywords are words that have a specific meaning to the compiler and cannot be used for other purposes in the program. For example, when the compiler sees the word class, it understands that the word after class is the name for the class. Their use will be introduced later in the course.

  • Modifiers


    Java uses certain reserved words called modifiers that specify the properties of the data, methods, and classes and how they can be used. Examples of modifiers are public and static. Other modifiers are private, final, abstract, and protected. A public datum, method, or class can be accessed by other programs. A private datum or method cannot be accessed by other programs. Modifiers are discussed in later chapter.
  • Statements

  • A statement represents an action or a sequence of actions. The statement System.out.println("Welcome to Java!") in the program is a statement to display the greeting "Welcome to Java!“. Every statement in Java ends with a semicolon (;).
  • Blocks

  • A pair of braces in a program forms a block that groups components of a program.

  • Classes


    The class is the essential Java construct. A class is a template or blueprint for objects. To program in Java, you must understand classes and be able to write and use them. The mystery of the class will continue to be unveiled throughout this course. For now, though, understand that a program is defined by using one or more classes.

  • Methods


    What is System.out.println? It is a method : a collection of statements that performs a sequence of operations to display a message on the console. It can be used even without fully understanding the details of how it works. It is used by invoking a statement with a string argument. The string argument is enclosed within parentheses. In this case, the argument is "Welcome to Java!" You can call the same println method with a different argument to print a different message.

  • The main method


    The main method provides the control of program flow. The Java interpreter executes the application by invoking the main method.
      public static void main( String[] args ) {
      // Statements;
      }

A Simple JAVA Program

// This program prints Welcome to JAVA!
public class Welcome {
public static void main ( String[] args ) {
System.out.println(“ Welcome to Java!” );
}
}

Creating and Editing

You can use WordPad, NotePad, etc.

Creating, Compiling and Running Programs



Trace a Program Execution



Java Development Kit (JDK) Editions


  • Java Standard Edition (J2SE) :  J2SE can be used to develop client-side standalone applications or applets.
  • Java Enterprise Edition (J2EE) :  J2EE can be used to develop server-side applications such as Java servlets and Java ServerPages.
  • Java Micro Edition (J2ME) :  J2ME can be used to develop applications for mobile devices such as cell phones.
  • This course uses J2SE to introduce Java programming.

  • Integrated Development Environments Tools

Elements of Programming

Your First Java Program: Hello World

In this area, we will probably lead you into the universe of Java taking so as to programme you through the three essential steps required to get a straightforward system running. The Java framework is an accumulation of utilizations much the same as any of alternate applications that you are acclimated to utilizing, (for example, your assertion processor, email program, or web program). Likewise with any application, you should make sure that Java is legitimately introduced on your PC. You likewise require a proofreader and a terminal application. Here are framework particular guidelines for three well known home working frameworks. [ Mac OS X · Windows · Linux ]

Programming in Java. We soften the procedure of programming up Java into three stages:


  1. Make the system by writing it into a word processor and sparing it to a record named, say, MyProgram.java. 
  2. Aggregate it by writing "javac MyProgram.java" in the terminal window. 
  3. Run (or execute) it by writing "java MyProgram" in the terminal window. 


The initial step makes the system; the second makes an interpretation of it into a dialect more suitable for machine execution (and puts the outcome in a document named MyProgram.class); the third really runs the project.


  • Making a Java program. A system is just a grouping of characters, similar to a sentence, a passage, or a ballad. To make one, we require just characterize that grouping characters utilizing a content tool as a part of the same path as we accomplish for email. HelloWorld.java is a case program. Sort these character into your content manager and spare it into a document named HelloWorld.java. 


   open class HelloWorld {

           open static void main(String[] args) {

                         System.out.println("Hello, World");

                   }

               }


  • Accumulating a Java program. At to begin with, it may appear to you just as the Java programming dialect is intended to be best comprehended by the PC. Really, actually, the dialect is intended to be best comprehended by the software engineer (that is you). A compiler is an application that deciphers programs from the Java dialect to a dialect more suitable for executing on the PC. It brings a content record with the .java expansion as data (your project) and creates a document with a .class augmentation (the scripting language variant). To incorporate HelloWorld.java sort the obvious content beneath at the terminal. (We utilize the % image to mean the charge brief, however it might seem distinctive relying upon your framework.) 


                   % javac HelloWorld.java

On the off chance that you wrote in the project accurately, you ought to see no mistake messages. Something else, backpedal and ensure you wrote in the system precisely as it shows up above.


  • Executing a Java program. When you gather your system, you can run it. This is the energizing part, where the PC takes after your directions. To run the HelloWorld program, sort the accompanying at the terminal: 


                  % java HelloWorld

In the event that all goes well, you ought to see the accompanying reaction

                 Hi, World


  • Understanding a Java program. The key line with System.out.println() send the content "Hi, World". When we start to compose more convoluted projects, we will examine the importance of open, class, principle, String[], args, System.out, et cetera. 



  • Making your own particular Java program. For the present, the majority of our projects will be much the same as HelloWorld.java, aside from with an alternate arrangement of articulations in fundamental(). The most effortless approach to compose such a system is to: 
              1. Duplicate HelloWorld.java into another record whose name is the project name took after by .java.

              2. Supplant HelloWorld with the system name all around.

              3. Supplant the print proclamation by a succession of explanations.

Blunders. Most mistakes are effectively settled via deliberately looking at the project as we make it, in simply the same route as we alter spelling and linguistic blunders when we write an email message.

-Compile Time Error: These blunders are gotten by the framework when we incorporate the project, since they keep the compiler from doing the interpretation (so it issues a mistake message that tries to clarify why).

-Run-time Error :  These blunders are gotten by the framework when we execute the project, on the grounds that the system tries to peform an invalid operation (e.g., division by zero).

-Logical errors :These mistakes are (ideally) gotten by the developer when we execute the project and it creates the wrong reply. Bugs are the most despicable aspect of a developer's presence. They can be unpretentious and elusive.

One of the first abilities that you will learn is to distinguish blunders; one of the following will be to be adequately watchful when coding to maintain a strategic distance from a significant number of them.

Include and yield. Normally, we need to give info to our projects: information that they can procedure to create an outcome. The least difficult approach to give info information is delineated in UseArgument.java. At whatever point this system is executed, it peruses the charge line contention that you write after the project name and prints it retreat to the terminal as a feature of the message.

             % javac UseArgument.java

              % java UseArgument Alice

              Woow, Roow. How are you?

              % java UseArgument Bob

              Howdy, Bob. How are you?

Question + Answers

Q. Why Java?

A. The projects that we are composing are fundamentally the same to their partners in a few different dialects, so our decision of dialect is not essential. We utilize Java since it is generally accessible, grasps a full arrangement of cutting edge deliberations, and has an assortment of programmed checks for slip-ups in projects, so it is suitable for figuring out how to program. There is no immaculate dialect, and you absolutely will be customizing in different dialects later on.

Q. Do I truly need to sort in the projects in the book to give them a shot?

A. Everybody ought to sort in HelloWorld.java, however you can discover the majority of the code in this book (and substantially more) on this booksite.

Q. What are Java's guidelines in regards to tabs, spaces and newline characters?

A. There are relatively few. Java compilers treat every one of them to be identical. For instance, we could likewise compose HelloWorld as takes after:

open class HelloWorld { open static void fundamental (

String [] args) { System.out.println("Hello World") ; }

Yet, we do regularly hold fast to separating and indenting traditions when we compose Java programs, pretty much as we generally indent passages and lines reliably when we compose composition or verse.

Q. What are the tenets with respect to quotes?

A. Material inside quotes is an exemption to the standard of the past inquiry: things inside of quotes are taken truly with the goal that you can absolutely determine what gets printed. On the off chance that you put any number of progressive spaces inside of the quotes, you understand that number of spaces in the yield. In the event that you incidentally overlook a quote, the compiler might get extremely befuddled, in light of the fact that it needs that stamp to recognize characters in the string and different parts of the project. To print a quote, a newline, or a tab, use \", \n, or \t, individually, inside of the quotes.

Q. What is the significance of the words open, static and void?

A. These catchphrases determine certain properties of principle() that you will find out about later in the book. For the occasion, we simply incorporate these catchphrases in the code (since they are required) yet don't allude to them in the content.

Q. What happens when you overlook a support or incorrectly spell one of the words, similar to open or static or principle? A. It relies on exactly what you do. Such blunders are called grammar mistakes. Give it a shot and see.

Q. Will a system utilize more than one summon line contention?

A. Yes, you can put a few, however we regularly utilize just a couple. You allude to the second one as args[1], the third one as args[2], et cetera. Note that we begin including from 0 Java.

Q. What Java frameworks libraries and systems are accessible for me to utilize?

A. There are a large number of them, however we acquaint them with you in a conscious manner in this book to abstain from overpowering you with decisions.

Q. By what means would it be advisable for me to organize my code? In what capacity would it be a good idea for me to remark my code?

A. Developers use coding rules to make programs simpler to peruse, comprehend, and keep up. As you pick up experience, you will build up a coding style, pretty much as you create style while composing composition. Informative supplement B gives a few rules to organizing and remarking your code. We prescribe coming back to this informative supplement after you've composed a couple programs.

Q. What precisely is a .class record?

A. It's a twofold document (grouping of 0s and 1s). In the event that you are utilizing Unix or OS X, you can analyze its substance by writing od - x HelloWorld.class at the order brief. This shows the outcomes in hexadecimal (base 16). In reverence to Java's name, the first expression of each .class document is bistr

Wednesday, January 20, 2016

Introduction to Java

Introduction. Our objective in this part is to persuade you that written work a PC project is less demanding than composing a bit of content, for example, a section or an article. In this part, we take you through these building squares, kick you off on programming in Java, and study an assortment of intriguing projects.
1.1 Elements of Programming instructs you on how to create, compile, and execute a Java program on your system.
1.2 Built-in Types of Data describes Java's built-in data types for manipulating strings, integers, real numbers, and booleans.
1.3 Conditionals and Loops introduces Java structures for control flow, including if-else statements, while loops, and for loops.
1.4 Arrays considers a data structure known as the array for organizing large quantities of data.
1.5 Input and Output extends the set of input and output abstractions (command-line arguments and standard output) to include standard input, standard drawing, and standard audio.
1.6 Random Web Surfer presents a case study that models the behavior of a web surfer using a Markov chain.


  • Why Java? 

       The answer is that Java enables users to develop and deploy applications on the Internet for servers, desktop computers, and small hand-held devices. The future of computing is being profoundly influenced by the Internet, and Java promises to remain a big part of that future. Java is the Internet programming language.
  1.   Java is a general purpose programming language
  2.   Java is the Internet programming language


Java, Web, and Beyond
  •   Java can be used to develop Web applications
  •  Java Applets
  •  Java Servlets and Java Server Pages
  •  Java can also be used to develop applications for hand-held devices such as Palm cell phones
Java’s History
  • James Gosling and Sun Microsystems
  •  Oak
  •  Java, May 20, 1995
  •  Hot Java : The first Java-enabled Web browser

Characteristics of Java

JAVA : A simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, potable, high-performance, multithreaded, dynamic language

  • Java is simple

Java is partially modeled on C++, but greatly simplified and improved. Some people refer to Java as "C++" because it is like C++ but with more functionality and fewer negative aspects.

  • Java is Object-oriented

Java is inherently object-oriented. Although many object-oriented languages began strictly as procedural languages, Java was designed from the start to be object-oriented. Object-oriented programming (OOP) is a popular programming approach that is replacing traditional procedural programming techniques.
One of the central issues in software development is how to reuse code. Object-oriented programming provides great flexibility, modularity, clarity, and reusability through encapsulation, inheritance, and polymorphism.

  • Java is Distributed

Distributed computing involves several computers working together on a network. Java is designed to make distributed computing easy. Since networking capability is inherently integrated into Java, writing network programs is like sending and receiving data to and from a file.

  • Java is Interpreted

You need an interpreter to run Java programs. The programs are compiled into the Java Virtual Machine code called bytecode. The bytecode is machineindependent and can run on any machine that has a Java interpreter, which is part of the Java Virtual Machine (JVM).

  • Java is Robust

Java compilers can detect many problems that would first show up at execution time in other languages. Java has eliminated certain types of error-prone programming constructs found in other languages. Java has a runtime exception-handling feature to provide programming support for robustness.

  • Java is Secure

Java implements several security mechanisms to protect your system against harm caused by stray programs.

  • Java is Architecture-Neutral : Write once, run anywhere

With a Java Virtual Machine (JVM), you can write one program that will run on any platform.

  • Java is Portable

Because Java is architecture neutral, Java programs are portable. They can be run on any platform without being recompiled.

  • Java is High-Performance

Java’s performance Because Java is architecture neutral, Java programs are portable. They can be run on any platform without being recompiled.

  • Java is Multithreaded

Multithread programming is smoothly integrated in Java, whereas in other languages you have to call procedures specific to the operating system to enable multithreading.

  • Java is Dynamic

Java was designed to adapt to an evolving environment. New code can be loaded on the fly without recompilation. There is no need for developers to create, and for users to install, major new software versions. New features can be incorporated transparently as needed.