Download Java programming.it will help you and more Cheat Sheet Journalism in PDF only on Docsity!
JAVA for
Beginners
nd
Edition
An introductory course for Advanced IT Students and those who would
like to learn the Java programming language.
Riccardo
Flask
Contents
- Introduction
- About JAVA
- OOP – Object Oriented Programming
- Part 1 - Getting Started
- The Java Development Kit – JDK
- My first Java program.........................................................................................................................................
- Using an IDE
- Variables and Data Types
- Test your skills – Example3................................................................................................................................
- Mathematical Operators
- Logical Operators
- Character Escape Codes
- Test your skills – Example7...............................................................................................................................
- Data Types
- Introducing Control Statements
- Blocks of Code
- Test your skills – Example14
- The Math Class
- Scope and Lifetime of Variables
- Type Casting and Conversions
- Console Input
- Using the Keyboard Class
- Using the Scanner Class
- Using Swing Components
- Part 2 - Advanced Java Programming
- Control Statements - The if Statement
- Guessing Game (Guess.java)
- Nested if
- if-else-if Ladder
- Ternary (?) Operator
- switch Statement (case of)
- Nested switch
- Mini-Project – Java Help System (Help.java) - Complete Listing
- The for Loop..........................................................................................................................................................
- Multiple Loop Control Variable
- Terminating a loop via user intervention
- Interesting For Loop Variations
- Infinite Loops
- No ‘Body’ Loops................................................................................................................................................
- Declaring variables inside the loop
- Enhanced For loop
- The While Loop
- Mini-Project 2– Java Help System (Help2.java) - Complete listing
- Using Break to Terminate a Loop
- Terminating a loop with break and use labels to carry on execution
- Use of Continue (complement of Break)
- Continue + Label...............................................................................................................................................
- Mini-Project 3– Java Help System (Help3.java) - Complete Listing
- Nested Loops
- Class Fundamentals
- Definition
- The Vehicle Class
- Using the Vehicle class
- Creating more than one instance
- Creating Objects
- Reference Variables and Assignment
- Methods
- Returning from a Method
- Returning a Value
- Methods which accept Parameters:
- Project: Creating a Help class from the Help3.java
- Method helpon( )
- Method showmenu( )
- Method isvalid( )
- Class Help
- Main Program:
- Constructors
- Constructor having parameters
- Overloading Methods and Constructors
- Method Overloading
- Automatic Type Conversion for Parameters of overloaded Methods
- Overloading Constructors
- Access Specifiers: public and private
- Arrays and Strings
- Arrays
- One-dimensional Arrays
- Sorting an Array – The Bubble Sort
- Two-Dimensional Arrays:
- Different syntax used to declare arrays:
- Array References:.......................................................................................................................................
- The Length Variable:
- Using Arrays to create a Queue data structure **
- The Enhanced ‘for’ Loop:
- Strings
- Using String Methods
- String Arrays
- Vector and ArrayList - Employee.java - ComparableDemo.java
- File Operations in Java
- Template to read data from disk
- Template to write (save) data to disk
- Introduction to GUI using AWT/Swing
- Using Swing to create a small Window...............................................................................................................
- Inserting Text inside Window
- Creating a simple application implementing JButton, JTextfield and JLabel
Introduction About JAVA
“Java refers to a number of computer software products and specifications from Sun Microsystems
(the Java™ technology) that together provide a system for developing and deploying cross-platform
applications. Java is used in a wide variety of computing platforms spanning from embedded devices
and mobile phones on the low end to enterprise servers and super computers on the high end. Java
is fairly ubiquitous in mobile phones, Web servers and enterprise applications, and somewhat less
common in desktop applications, though users may have come across Java applets when browsing
the Web.
Writing in the Java programming language is the primary way to produce code that will be deployed
as Java bytecode, though there are compilers available for other languages such as JavaScript,
Python and Ruby, and a native Java scripting language called Groovy. Java syntax borrows heavily
from C and C++ but it eliminates certain low-level constructs such as pointers and has a very simple
memory model where every object is allocated on the heap and all variables of object types are
references. Memory management is handled through integrated automatic garbage collection
performed by the Java Virtual Machine (JVM).”
1 OOP – Object Oriented Programming
OOP is a particular style of programming which involves a particular way of designing solutions to
particular problems. Most modern programming languages, including Java, support this paradigm.
When speaking about OOP one has to mention:
Inheritance
Modularity
Polymorphism
Encapsulation (binding code and its data)
However at this point it is too early to try to fully understand these concepts.
This guide is divided into two major sections, the first section is an introduction to the language and
illustrates various examples of code while the second part goes into more detail.
(^1) http://en.wikipedia.org/wiki/Java_%28Sun%
At this point one needs some basic DOS commands in order to get to the directory (folder), where
the java class resides:
cd\ (change directory)
cd[folder name] to get to the required folder/directory
When you get to the required destination you need to type the following:
c:[folder name]\javac Example1.java
The above command will compile the java file and prompt the user with any errors. If the
compilation is successful a new file containing the bytecode is generated: Example1.class
To execute the program, we invoke the interpreter by typing:
c:[folder name]\java Example
The result will be displayed in the DOS window.
Using an IDE
Some of you might already be frustrated by this point. However there is still hope as one can forget
about the command prompt and use an IDE (integrated development environment) to work with
Java programming. There are a number of IDE’s present, all of them are fine but perhaps some are
easier to work with than others. It depends on the user’s level of programming and tastes! The
following is a list of some of the IDE’s available:
BlueJ – www.bluej.org (freeware)
NetBeans – www.netbeans.org (freeware/open-source)
JCreator – www.jcreator.com (freeware version available, pro version purchase required)
Eclipse – www.eclipse.org (freeware/open-source)
IntelliJ IDEA – www.jetbrains.com (trial/purchase required)
JBuilder – www.borland.com (trial/purchase required)
Beginners might enjoy BlueJ and then move onto other IDE’s like JCreator, NetBeans, etc. Again it’s
just a matter of the user’s tastes and software development area.
Variables and Data Types Variables
A variable is a place where the program stores data temporarily. As the name implies the value
stored in such a location can be changed while a program is executing (compare with constant).
class Example2 { public static void main(String args[]) { int var1; // this declares a variable int var2; // this declares another variable var1 = 1024; // this assigns 1024 to var System.out.println("var1 contains " + var1); var2 = var1 / 2; System.out.print("var2 contains var1 / 2: "); System.out.println(var2); } }
Predicted Output:
var2 contains var1 / 2: 512
The above program uses two variables, var1 and var2. var1 is assigned a value directly while var2 is
filled up with the result of dividing var1 by 2, i.e. var2 = var1/2. The words int refer to a particular
data type, i.e. integer (whole numbers).
Test your skills – Example
As we saw above, we used the ‘/’ to work out the quotient of var1 by 2. Given that ‘+’ would
perform addition, ‘-‘ subtraction and ‘*’ multiplication, write out a program which performs all the
named operations by using two integer values which are hard coded into the program.
Hints:
You need only two variables of type integer
Make one variable larger and divisible by the other
You can perform the required calculations directly in the print statements, remember to
enclose the operation within brackets, e.g. (var1-var2)
Operator Description
& AND gate behaviour (0,0,0,1)
| OR gate behaviour (0,1,1,1)
^ XOR – exclusive OR (0,1,1,0)
&& Short-circuit AND
|| Short-circuit OR
! Not
class Example5 { public static void main(String args[]) { int n, d; n = 10; d = 2; if(d != 0 && (n % d) == 0) System.out.println(d + " is a factor of " + n); d = 0; // now, set d to zero // Since d is zero, the second operand is not evaluated. if(d != 0 && (n % d) == 0) System.out.println(d + " is a factor of " + n); /* Now, try same thing without short-circuit operator. This will cause a divide-by-zero error. */ if(d != 0 & (n % d) == 0) System.out.println(d + " is a factor of " + n); } }
Predicted Output:
*Note if you try to execute the above program you will get an error (division by zero). To be able to
execute it, first comment the last two statements, compile and then execute.
2 is a factor of 10
Trying to understand the above program is a bit difficult, however the program highlights the main
difference in operation between a normal AND (&) and the short-circuit version (&&). In a normal
AND operation, both sides of the expression are evaluated, e.g.
if(d != 0 & (n % d) == 0) – this returns an error as first d is compared to 0 to check inequality and then
the operation (n%d) is computed yielding an error! (divide by zero error)
The short circuit version is smarter since if the left hand side of the expression is false, this mean
that the output has to be false whatever there is on the right hand side of the expression, therefore:
if(d != 0 && (n % d) == 0) – this does not return an error as the (n%d) is not computed since d is
equal to 0, and so the operation (d!=0) returns false, causing the output to be false. Same applies for
the short circuit version of the OR.
Character Escape Codes
The following codes are used to represents codes or characters which cannot be directly accessible
through a keyboard:
Code Description
\n New Line
\t Tab
\b Backspace
\r Carriage Return
\ Backslash
\’ Single Quotation Mark
\” Double Quotation Mark
* Octal - * represents a number or Hex digit
\x* Hex
\u* Unicode, e.g. \u2122 = ™ (trademark symbol)
class Example6 { public static void main(String args[]) { System.out.println("First line\nSecond line"); System.out.println("A\tB\tC"); System.out.println("D\tE\tF") ; } }
Predicted Output:
First Line Second Line A B C D E F
Predicted Output:
P Q PANDQ PORQ PXORQ NOTP true true true true false fals true false false true true fals false true false true true true false false false false false true Data Types
The following is a list of Java’s primitive data types:
Data Type Description
int Integer – 32bit ranging from -2,147,483,648 to 2,147,483,
byte 8-bit integer ranging from -128 to 127
short 16-bit integer ranging from -32,768 to 32,
long 64-bit integer from -9,223,372,036,854,775,808 to -9,223,372,036,854,775,
float Single-precision floating point, 32-bit
double Double-precision floating point, 64-bit
char Character , 16-bit unsigned ranging from 0 to 65,536 (Unicode)
boolean Can be true or false only
The ‘String’ type has not been left out by mistake. It is not a primitive data type, but strings (a
sequence of characters) in Java are treated as Objects.
class Example8 { public static void main(String args[]) { int var; // this declares an int variable double x; // this declares a floating-point variable var = 10; // assign var the value 10 x = 10.0; // assign x the value 10. System.out.println("Original value of var: " + var); System.out.println("Original value of x: " + x); System.out.println(); // print a blank line
// now, divide both by 4 var = var / 4; x = x / 4; System.out.println("var after division: " + var); System.out.println("x after division: " + x); } }
Predicted output:
Original value of var: 10 Original value of x: 10. var after division: 2 x after division: 2.
One here has to note the difference in precision of the different data types. The following example
uses the character data type. Characters in Java are encoded using Unicode giving a 16-bit range, or
a total of 65,537 different codes.
class Example9 { public static void main(String args[]) { char ch; ch = 'X'; System.out.println("ch contains " + ch); ch++; // increment ch System.out.println("ch is now " + ch); ch = 90; // give ch the value Z System.out.println("ch is now " + ch); } }
Introducing Control Statements
These statements will be dealt with in more detail further on in this booklet. For now we will learn
about the if and the for loop.
class Example11 { public static void main(String args[]) { int a,b,c; a = 2; b = 3; c = a - b; if (c >= 0) System.out.println("c is a positive number"); if (c < 0) System.out.println("c is a negative number"); System.out.println(); c = b - a; if (c >= 0) System.out.println("c is a positive number"); if (c < 0) System.out.println("c is a negative number"); } }
Predicted output:
c is a negative number c is a positive number
The ‘if’ statement evaluates a condition and if the result is true, then the following statement/s are
executed, else they are just skipped (refer to program output). The line System.out.println() simply
inserts a blank line. Conditions use the following comparison operators:
Operator Description
< Smaller than
> Greater than
<= Smaller or equal to, (a<=3) : if a is 2 or 3, then result of comparison is TRUE
>= Greater or equal to, (a>=3) : if a is 3 or 4, then result of comparison is TRUE
== Equal to
!= Not equal
The for loop is an example of an iterative code, i.e. this statement will cause the program to repeat a
particular set of code for a particular number of times. In the following example we will be using a
counter which starts at 0 and ends when it is smaller than 5, i.e. 4. Therefore the code following the
for loop will iterate for 5 times.
class Example12 { public static void main(String args[]) { int count; for(count = 0; count < 5; count = count+1) System.out.println("This is count: " + count); System.out.println("Done!"); } }
Predicted Output:
This is count: 0 This is count: 1 This is count: 2 This is count: 3 This is count: 4 Done!
Instead of count = count+1, this increments the counter, we can use count++
The following table shows all the available shortcut operators:
Operator Description Example Description
++ Increment a++ a = a + 1 (adds one from a)
-- Decrement a-- a = a – 1 (subtract one from a)
+= Add and assign a+=2 a = a + 2
-= Subtract and assign a-=2 a = a – 2
= Multiply and assign a=3 a = a * 3
/= Divide and assign a/=4 a = a / 4
%= Modulus and assign a%=5 a = a mod 5
public static void main (String args []){ double eu; System.out.println("Euro conversion table:"); System.out.println(); for (eu=1;eu<101;eu++) System.out.println(eu+" Euro is euqivalent to Lm "+(eu*0.43)); } } The Math Class
In order to perform certain mathematical operations like square root (sqrt), or power (pow); Java
has a built in class containing a number of methods as well as static constants, e.g.
Pi = 3.141592653589793 and E = 2.718281828459045. All the methods involving angles use radians
and return a double (excluding the Math.round()).
class Example15 { public static void main(String args[]) { double x, y, z; x = 3; y = 4; z = Math.sqrt(xx + yy); System.out.println("Hypotenuse is " +z); } }
Predicted Output:
Hypotenuse is 5.
Please note that whenever a method is called, a particular nomenclature is used where we first
specify the class that the particular method belongs to, e.g. Math.round( ); where Math is the class
name and round is the method name. If a particular method accepts parameters, these are placed in
brackets, e.g. Math.max(2.8, 12.9) – in this case it would return 12.9 as being the larger number. A
useful method is the Math.random( ) which would return a random number ranging between 0.
and 1.0.
Scope and Lifetime of Variables
The following simple programs, illustrate how to avoid programming errors by taking care where to
initialize variables depending on the scope.
class Example16 { public static void main(String args[]) { int x; // known to all code within main x = 10; if(x == 10) { // start new scope int y = 20; // known only to this block // x and y both known here. System.out.println("x and y: " + x + " " + y); x = y * 2; } // y = 100; // Error! y not known here // x is still known here. System.out.println("x is " + x); } }
Predicted Output:
x and y: 10 20 x is 40
If we had to remove the comment marks from the line, y = 100; we would get an error during
compilation as y is not known since it only exists within the block of code following the ‘if’
statement.
The next program shows that y is initialized each time the code belonging to the looping sequence is
executed; therefore y is reset to - 1 each time and then set to 100. This operation is repeated for
three (3) times.