Basic Java

Add to Favourites
Post to:

Keep in mind that I am assuming that you know nothing about programming. Here are several vocabulary terms that will make things understandable: Computer program - A computer program is a set of instructions that tell a computer exactly what to do. The instructions might tell the computer to add up a set of numbers, or compare two numbers and make a decision based on the result, or whatever. But a computer program is simply a set of instructions for the computer, like a recipe is a set of instructions for a cook or musical notes are a set of instructions for a musician. The computer follows your instructions exactly and in the process does something useful -- like balancing a checkbook or displaying a game on the screen or implementing a word processor. Programming language - In order for a computer to recognize the instructions you give it, those instructions need to be written in a language the computer understands -- a programming language. There are many computer programming languages -- Fortran, Cobol, Basic, Pascal, C, C++, Java, Perl -- just like there are many spoken languages. They all express approximately the same concepts in different ways. Compiler - A compiler translates a computer program written in a human-readable computer language (like Java) into a form that a computer can execute. You have probably seen EXE files on your computer. These EXE files are the output of compilers. They contain executables -- machine-readable programs translated from human-readable programs. In order for you to start writing computer programs in a programming language called Java, you need a compiler for the Java language In order to teach you about computer programming, I am going to make several assumptions from the start: I am going to assume that you know nothing about computer programming now. If you already know something then the first part of this article will seem elementary to you. Please feel free to skip forward until you get to something you don't know. I am going to assume you do know something about the computer you are using. That is, I am going to assume you already know how to edit a file, copy and delete files, rename files, find information on your system, etc. For simplicity, I am going to assume that you are using a machine running Windows 95, 98, 2000, NT or XP. It should be relatively straightforward for people running other operating systems to map the concepts over to those. I am going to assume that you have a desire to learn. All of the tools you need to start programming in Java are widely available on the Web for free. There is also a huge amount of educational material for Java available on the Web, so once you finish this article you can easily go learn more to advance your skills. You can learn Java programming here without spending any money on compilers, development environments, reading materials, etc. Once you learn Java it is easy to learn other languages, so this is a good place to start. Having said these things, we are ready to go. Let's get started!  Be Careful When You Type Type all code, commands, and file names exactly as shown. Both the compiler (javac) and launcher tool (java) are case-sensitive, so you must capitalize consistently. Example example Once the byte code is generated it can be run on any platform using Java Interpreter (JVM). It interprets byte code (.class file) and converts into machine specific binary code. Then JVM runs the binary code on the host machine Variables All programs use variables to hold pieces of data temporarily The Name of a Variable When you want the compiler to reserve an area of memory for some values used in your program, you must set a name, also called an identifier that will allow you to refer to that area of memory. The name can be anything of your choice but there are rules you must follow: The name of a variable can be made of one letter (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, or Z) only The name of a variable can start with a letter, an underscore "_", or the dollar sign $. The name cannot start with a digit. If the name starts with an underscore, the second character must be an alphabetical letter After the first character, the name of the variable can include letters, digits (0, 1, 2, 3, 4, 5, 6, 7, 8, or 9), or underscores in any combination The name of a variable cannot be one of the words that the JAVA languages has reserved for its own use. A reserved word is also called a keyword. This means that you cannot use one of the following keywords to name your variable: Java Primitive Data Types Data Type Purpose Contents Default Value* boolean Truth value true or false false char Character Unicode characters \u0000 byte Signed integer 8 bit two's complement (byte) 0 short Signed integer 16 bit two's complement (short) 0 int Signed integer 32 bit two's complement 0 long Signed integer 64 bit two's complement 0L float Real number 32 bit IEEE 754 floating point 0.0f double Real number 64 bit IEEE 754 floating point 0.0d One way to remember the Java primitive data types is by using this mnemonic aid: Be Careful, Bears Shouldn't Ingest Large Furry Dogs Examples boolean result = true; char capitalC = 'C'; byte b = 100; short s = 10000; int i = 100000; double d1 = 123.4; double d2 = 1.234e2; // same value as d1, but in scientific notation float f1 = 123.4f; Java Object References Java object references are variables which hold references to objects. Unlike Java primitive data types which store actual data, object references store only a reference to the actual data object. Arrays An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail. An array of ten elements Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8 The following program, ArrayDemo, creates an array of integers, puts some values in it, and prints each value to standard output. class ArrayDemo { public static void main(String[] args) { int[] anArray; // declares an array of integers anArray = new int[10]; // allocates memory for 10 integers anArray[0] = 100; // initialize first element anArray[1] = 200; // initialize second element anArray[2] = 300; // etc. anArray[3] = 400; anArray[4] = 500; anArray[5] = 600; anArray[6] = 700; anArray[7] = 800; anArray[8] = 900; anArray[9] = 1000; System.out.println("Element at index 0: " + anArray[0]); System.out.println("Element at index 1: " + anArray[1]); System.out.println("Element at index 2: " + anArray[2]); System.out.println("Element at index 3: " + anArray[3]); System.out.println("Element at index 4: " + anArray[4]); System.out.println("Element at index 5: " + anArray[5]); System.out.println("Element at index 6: " + anArray[6]); System.out.println("Element at index 7: " + anArray[7]); System.out.println("Element at index 8: " + anArray[8]); System.out.println("Element at index 9: " + anArray[9]); } } The output from this program is: Element at index 0: 100 Element at index 1: 200 Element at index 2: 300 Element at index 3: 400 Element at index 4: 500 Element at index 5: 600 Element at index 6: 700 Element at index 7: 800 Element at index 8: 900 Element at index 9: 1000 Declaring a Variable to Refer to an Array The above program declares anArray with the following line of code: int[] anArray; // declares an array of integers Similarly, you can declare arrays of other types: byte[] anArrayOfBytes; short[] anArrayOfShorts; long[] anArrayOfLongs; float[] anArrayOfFloats; double[] anArrayOfDoubles; boolean[] anArrayOfBooleans; char[] anArrayOfChars; String[] anArrayOfStrings; Questions : Variables Questions The term "instance variable" is another name for ___. The term "class variable" is another name for ___. A local variable stores temporary state; it is declared inside a ___. A variable declared within the opening and closing parenthesis of a method signature is called a ____. What are the eight primitive data types supported by the Java programming language? Character strings are represented by the class ___. An ___ is a container object that holds a fixed number of values of a single type Answers to Questions The term "instance variable" is another name for non-static field. The term "class variable" is another name for static field. A local variable stores temporary state; it is declared inside a method. A variable declared within the opening and closing parenthesis of a method is called a parameter. What are the eight primitive data types supported by the Java programming language? byte, short, int, long, float, double, boolean, char Character strings are represented by the class java.lang.String. An array is a container object that holds a fixed number of values of a single type. The Equality and Relational Operators The equality and relational operators determine if one operand is greater than, less than, equal to, or not equal to another operand. The majority of these operators will probably look familiar to you as well. Keep in mind that you must use "==", not "=", when testing if two primitive values are equal. == equal to != not equal to > greater than >= greater than or equal to < less than <= less than or equal to The following program, ComparisonDemo, tests the comparison operators: class ComparisonDemo { public static void main(String[] args){ int value1 = 1; int value2 = 2; if(value1 == value2) System.out.println("value1 == value2"); if(value1 != value2) System.out.println("value1 != value2"); if(value1 > value2) System.out.println("value1 > value2"); if(value1 < value2) System.out.println("value1 < value2"); if(value1 <= value2) System.out.println("value1 <= value2"); } } Output: value1 != value2 value1 < value2 value1 <= value2 The Conditional Operators The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed. && Conditional-AND || Conditional-OR The following program, ConditionalDemo1, tests these operators: class ConditionalDemo1 { public static void main(String[] args){ int value1 = 1; int value2 = 2; if((value1 == 1) && (value2 == 2)) System.out.println("value1 is 1 AND value2 is 2"); if((value1 == 1) || (value2 == 1)) System.out.println("value1 is 1 OR value2 is 1"); } } Summary of Operators The following quick reference summarizes the operators supported by the Java programming language. Simple Assignment Operator = Simple assignment operator Arithmetic Operators + Additive operator (also used for String concatenation) - Subtraction operator * Multiplication operator / Division operator % Remainder operator Unary Operators + Unary plus operator; indicates positive value (numbers are positive without this, however) - Unary minus operator; negates an expression ++ Increment operator; increments a value by 1 -- Decrement operator; decrements a value by 1 ! Logical compliment operator; inverts the value of a boolean Equality and Relational Operators == Equal to != Not equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to Conditional Operators && Conditional-AND || Conditional-OR ?: Ternary (shorthand for if-then-else statement) Type Comparison Operator instanceof Compares an object to a specified type Bitwise and Bit Shift Operators ~ Unary bitwise complement << Signed left shift >> Signed right shift >>> Unsigned right shift & Bitwise AND ^ Bitwise exclusive OR | Bitwise inclusive OR Questions: Operators Questions Consider the following code snippet. arrayOfInts[j] > arrayOfInts[j+1] Which operators does the code contain? Consider the following code snippet. int i = 10; int n = i++%5; What are the values of i and n after the code is executed? What are the final values of i and n if instead of using the postfix increment operator (i++), you use the prefix version (++i))? To invert the value of a boolean, which operator would you use? Which operator is used to compare two values, = or == ? Explain the following code sample: result = someCondition ? value1 : value2; Answers to Questions Consider the following code snippet: arrayOfInts[j] > arrayOfInts[j+1] Question: What operators does the code contain? Answer: >, + Consider the following code snippet: int i = 10; int n = i++%5; Question: What are the values of i and n after the code is executed? Answer: i is 11, and n is 0. Question: What are the final values of i and n if instead of using the postfix increment operator (i++), you use the prefix version (++i))? Answer: i is 11, and n is 1.  Question: To invert the value of a boolean, which operator would you use? Answer: The logical complement operator "!".  Question: Which operator is used to compare two values, = or == ? Answer: The == operator is used for comparison, and = is used for assignment.  Question: Explain the following code sample: result = someCondition ? value1 : value2; Answer: This code should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result." Expressions, Statements, and Blocks Now that you understand variables and operators, it's time to learn about expressions, statements, and blocks. Operators may be used in building expressions, which compute values; expressions are the core components of statements; statements may be grouped into blocks. Expressions An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value. You've already seen examples of expressions, illustrated in bold below: int cadence = 0; anArray[0] = 100; System.out.println("Element 1 at index 0: " + anArray[0]); int result = 1 + 2; // result is now 3 if(value1 == value2) System.out.println("value1 == value2"); The data type of the value returned by an expression depends on the elements used in the expression. The expression cadence = 0 returns an int because the assignment operator returns a value of the same data type as its left-hand operand; in this case, cadence is an int. As you can see from the other expressions, an expression can return other types of values as well, such as boolean or String. The Java programming language allows you to construct compound expressions from various smaller expressions as long as the data type required by one part of the expression matches the data type of the other. Here's an example of a compound expression: 1 * 2 * 3 In this particular example, the order in which the expression is evaluated is unimportant because the result of multiplication is independent of order; the outcome is always the same, no matter in which order you apply the multiplications. However, this is not true of all expressions. For example, the following expression gives different results, depending on whether you perform the addition or the division operation first: x + y / 100 // ambiguous You can specify exactly how an expression will be evaluated using balanced parenthesis: ( and ). For example, to make the previous expression unambiguous, you could write the following: (x + y) / 100 // unambiguous, recommended If you don't explicitly indicate the order for the operations to be performed, the order is determined by the precedence assigned to the operators in use within the expression. Operators that have a higher precedence get evaluated first. For example, the division operator has a higher precedence than does the addition operator. Therefore, the following two statements are equivalent: x + y / 100 x + (y / 100) // unambiguous, recommended When writing compound expressions, be explicit and indicate with parentheses which operators should be evaluated first. This practice makes code easier to read and to maintain. Statements Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon (;). Assignment expressions Any use of ++ or -- Method invocations Object creation expressions Such statements are called expression statements. Here are some examples of expression statements. aValue = 8933.234; // assignment statement aValue++; // increment statement System.out.println("Hello World!"); // method invocation statement Bicycle myBike = new Bicycle(); // object creation statement In addition to expression statements, there are two other kinds of statements: declaration statements and control flow statements. A declaration statement declares a variable. You've seen many examples of declaration statements already: double aValue = 8933.234; //declaration statement Finally, control flow statements regulate the order in which statements get executed. You'll learn about control flow statements in the next section, Control Flow Statements Blocks A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed. The following example, BlockDemo, illustrates the use of blocks: class BlockDemo { public static void main(String[] args) { boolean condition = true; if (condition) { // begin block 1 System.out.println("Condition is true."); } // end block one else { // begin block 2 System.out.println("Condition is false."); } // end block 2 } } Questions Operators may be used in building ___, which compute values. Expressions are the core components of ___. Statements may be grouped into ___. The following code snippet is an example of a ___ expression. 1 * 2 * 3 Statements are roughly equivalent to sentences in natural languages, but instead of ending with a period, a statement ends with a ___. A block is a group of zero or more statements between balanced ___ and can be used anywhere a single statement is allowed. Answers Operators may be used in building expressions, which compute values. Expressions are the core components of statements. Statements may be grouped into blocks. The following code snippet is an example of a compound expression. 1 * 2 * 3 Statements are roughly equivalent to sentences in natural languages, but instead of ending with a period, a statement ends with a semicolon. A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.

Comments
M.Muazzam Khan
By: M.Muazzam Khan
444 days 10 hours 12 minutes ago

Sir, could you please guide me that how can i access next tutorials. As, 1st time i found java easy because of your teaching and guiding technique.

Want to learn?

Sign up and browse through relevant courses.

Name:
Your Email:
Password:
Country:
Contact no:


Area code Number
Subjects you are interested in:
Word verification: (Enter the text as in image)


Sign Up Already a member? Sign In
I agree to WizIQ's User Agreement & Privacy Policy
Mohammed Habeeb vulla
Computer Lecturer
User
5 Members Recommend
33 Followers

Your Facebook Friends on WizIQ

Explore Similar Courses

Develop Android Apps with Java

Price:$300
$40

SAVE 86%

Give live classes, create & sell online courses

Try it free Plans & Pricing

Connect