Java Programming Basics
Introduction
Structured languages use control structures and code blocks with independent subroutines that support recursion and local variables. Object-oriented programming (OOP) combines the best ideas of structured programming with new organizational concepts.
OOP decomposes a program into related groups, forming self-contained objects with their own instructions and data. Three key features of OOP languages are encapsulation, polymorphism, and inheritance.
Encapsulation
Encapsulation acts like a protective case around code and data. It defines behavior and restricts arbitrary access by other code. The advantage is that everyone knows how to access the code, enabling independent usage regardless of implementation details. In Java, the basis of encapsulation is the class (a set of objects sharing the same structure and behavior). A class is defined by methods that operate on its data. A method is a message to an object to perform an action.
Inheritance
Inheritance organizes objects hierarchically. A general class (superclass) with common attributes defines more specific classes (subclasses) with specialized attributes.
Polymorphism
Polymorphism allows methods to act on objects based on the information passed to them. These parameters represent input values to a function. Polymorphism means a method has multiple implementations selected based on the object type passed.
First Program
Java source code files are saved with the .java extension. Compiling this code creates a .class file. Java requires all code to reside within a named class. The filename must match the class name containing the main
function.
public class HelloWorld { public static void main(String[] args) { System.out.println("HELLO WORLD"); }}
To compile, use the javac
compiler, and then use java
to run the application.
C:\> javac HelloWorld.javaC:\> java HelloWorld
Variables
A variable is the basic unit of storage. Its creation involves an identifier, a type, and a scope. Java has eight primitive data types.
Syntax:
type identifier = value;
Type | Size | Range |
---|---|---|
byte | 8 bits | -128 to 127 |
short | 16 bits | -32,768 to 32,767 |
int | 32 bits | -2,147,483,648 to 2,147,483,647 |
long | 64 bits | No limit |
float | 32 bits | Up to 38 digits |
double | 64 bits | Up to 308 digits |
char | 16 bits | Alphanumeric characters |
boolean | 8 bits | true or false |
Arrays use []
to group variables of the same type.
Example:
class Hello { public static void main(String[] args) { int x, y; x = 42; y = 12; System.out.print("X = " + x); System.out.println("Y = " + y); }}
Arrays
An array is a group of variables with the same name and type. Elements within an array are accessed by their index. Array types are the same as variable types. There are one-dimensional and two-dimensional arrays.
One-Dimensional:
type[] array_name = new type[size];type[] array_name = {values};
Two-Dimensional:
type[][] array_name = new type[rows][columns];type[][] array_name = {{values}};
Example (One-Dimensional):
class Months { public static void main(String[] args) { int[] monthDays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; System.out.println("April has " + monthDays[3] + " days"); }}
Example (Two-Dimensional):
class Multi { public static void main(String[] args) { int[][] m = new int[3][3]; m[0][0] = 1; m[1][1] = 1; m[2][2] = 1; System.out.println(m[0][0] + " " + m[0][1] + " " + m[0][2]); System.out.println(m[1][0] + " " + m[1][1] + " " + m[1][2]); System.out.println(m[2][0] + " " + m[2][1] + " " + m[2][2]); }}
Operators
Arithmetic Operator | Description |
---|---|
+ | Addition |
– | Subtraction |
* | Multiplication |
/ | Division |
% | Modulo (remainder) |
++ | Increment |
— | Decrement |
* Only applicable to numeric types.
Relational Operator | Description |
---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
* Applicable to all data types.
Logical Operator | Description |
---|---|
&& | AND |
|| | OR |
! | NOT |
Data Input
In MS-DOS applications, input values are taken using the String[] args
argument of the main
function. These values are entered when running the program from the MS-DOS prompt. Note that these values are always strings, and must be converted to numeric types for mathematical operations. This method is outdated for applets.
Example:
class Name { public static void main(String[] args) { System.out.println("Hello " + args[0]); System.out.println("Hello " + args[1]); }}
When run: c:\> java Name Pepe Antonio
Data Conversion
Java provides functions for converting between data types. These include character to number, number to string, between numbers, character to string, and string to number. These functions are also used in applets.
Character to Number:
char_var = Character.forDigit(num_var, base);
Number to String:
String str_var = String.valueOf(numeric_var);
Between Numbers:
Number num_obj = new Number(value);target_type var = num_obj.targetTypeValue();
Example:
Float f = new Float(3.1416);int i = f.intValue();long l = f.longValue();float fl = f.floatValue();double d = f.doubleValue();
Number to Character:
num_var = Character.digit(char_var, base);
Character to String:
Character char_obj = new Character('A');String str_var = char_obj.toString();
String to Number:
Number num_obj = new Number(str_var);num_type num_var = num_obj.numTypeValue();
Example 1:
class Conver2 { public static void main(String[] args) { int n1 = Character.digit('7', 10); int n2 = 1; Character letter = new Character('z'); double n3 = 150.50; String str1 = "Number"; String str = String.valueOf(n3); String str2 = letter.toString(); System.out.println(str1 + str + str2); System.out.println(n1 + n2); char nletra = Character.forDigit(n2, 10); System.out.println(n1 + "" + nletra); }}
Example 2:
class Conversion { public static void main(String[] args) { Integer integer = new Integer(args[0]); double n1 = integer.doubleValue(); double n2 = 150.50; System.out.println(n1 + n2); }}