Java Part 1 Notes

Page 1

JAVA Notes Form 3 – Part 1

Java Programming Notes 1. What is Java Programming Language? - High Level Language like Pascal, C, … - Object Oriented i.e. using ‘objects’ e.g. Why Java? - Object Oriented i.e. can be used from time to time - Portable i.e. run on different computers - Small in Size (memory, efficiency) - Secure - Concurrence i.e. more than one activity at a time - Used in different applications/technology i.e. Browsers, Mobiles, etc Features - Simple - Object Oriented - Platform independent (may be used easily on different computer/systems) - Safe (prohibits viruses…) - High performance (Compiled fast… recall of compilation, briefly explain Java not .exe) - Multi-threading (Multi-tasking- different tasks processed independently & at same time)

2. JAVA Programming // Construction of a JAVA program public class FirstProgram{ public static void main (String args[]){ System.out.println("Hello World"); //Prints Hello World on Screen } } Tips on the program: • • • • • • • • • • •

// Indicate a remark (comment) /* ….. */ is used for more than one line of comments class – every program begins with this (small letters) public – program available from outside the class (package – all in small letters.) static – means it can be used without creating an instance of the class void – returns no value main – the name of the method String args[] OR String[] args – the same - (S in CAPITAL) is an array of type String called args ,……- indicate scope of that section – click on open bracket i.e. { to see its closure System.out.print(“…”) – displays output on screen System.out.println(“…”) - gives output on separate line

Mr Noel Attard

Page: 1


JAVA Notes Form 3 – Part 1

// The println() class SecondProgram{ public static void main (String args []){ System.out.println("Hello World"); System.out.println("I am David Vella"); System.out.println("I am Sarah Borg"); System.out.println(); // Output a blank line System.out.println("----------------------"); Escape Characters: Used to display output better Escape Character Description \’ i.e. \’ …. \’ To display single quotes To display in double quotes \’’ i.e. \’’ … \’’ To display the backslash \\ \n New line (a line feed) \t Tab Backspace \b // The print() and println() class DisplayDemo{ public static void main (String args []){ System.out.print("My name is "); // we use .print here System.out.println("David Vella"); // .println moves cursor to next line System.out.print("and mine is "); // we use .print here System.out.println("Sarah Borg"); // .println moves cursor to next line System.out.println(); // output a blank line System.out.println("----------------------"); } // Use of Escape characters in OUTPUT class EscapeChar{ public static void main (String args[]){ System.out.println("\"Name\t\t\tMarks\""); // 3 tabs System.out.println("-------------\n\n"); // 2 blank lines System.out.println("Abela A.\t\t50"); // 2 tabs System.out.println("Borg B.\t\t\t60"); // 3 tabs System.out.println("Calleja C.\t\t70\n"); // 2 tabs System.out.println("\'End of Report\'"); // single quote } } Mr Noel Attard

Page: 2


JAVA Notes Form 3 – Part 1

3. Variables and Data Types

Primitive values do not share state with other primitive values. A variable whose type is a primitive type always holds a primitive value of that same type. The value of a variable of primitive type can be changed only by assignment operations on that variable The numeric types are the integral types and the floating-point types. The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing UTF-16 code units. The floating-point types are float, whose values include the 32-bit IEEE 754 floating-point numbers, and double, whose values include the 64-bit IEEE 754 floating-point numbers. The boolean type has exactly two values: true and false. Primitive Types and Values A primitive type is predefined by the Java programming language and named by its reserved keyword

PrimitiveType: •

NumericType

boolean

NumericType: •

IntegralType

FloatingPointType

IntegralType: one of •

byte short int long char

FloatingPointType: one of •

float double

Mr Noel Attard

Page: 3


JAVA Notes Form 3 – Part 1

4. What are Variables? Storage location in the computer’s memory. In programming variables are given names – in Java variable names are in lowercase and for clarity GIIVE THEM A NAME THAT make sense e.g. name, age, etc. and Not a, b, etc.. When programming one won’t know the values of particular data and these are called variables.

Variables in Java – Primitive Data Types 8 bits -128 to 127 16 bits -32,768 to 32,767 32 bits -2,147,483,648 to 2,147,483,647 64 bits -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 32 bits 1.4e-045 to 3.4e+308 64 bits 4.9e-324 to 1.8e+308 16 bits 0 to 65,536 1 bit True or False

byte short int Long float double char boolean

Java Variable Names: - Must be a valid identifier - Must NOT be a keyword (see table below) - Must NOT be Boolean literal or null - Must be unique within its scope i.e. cannot use same name for different variables within the same { } - Must NOT contain blank spaces - int and double are mostly used in our programs

Java Keywords Boolean break class const else enum for goto

abstract catch do finally

assert char double float

import new short

instanceof package shortstatic

int private strictfp

interface protected super

long public switch

this volatile

throw while

throws true

transient false

try null

Mr Noel Attard

byte continue extends if

case Default Final Implement s Native return synchroniz ed void

Page: 4


JAVA Notes Form 3 – Part 1

How to Declaring a Variables in JAVA: Syntax: datatype variablename; // Declaring Integer types class StoreIntegers{ public static void main (String args[]){ // declaring integer types byte day; short refnum; int num; long itemno; // more program statements here // to make use of integers } }

Examples 1. Declare One variable: int num1; ( Declare a variable with name: num1 that may contain an integer)

2. Declare Multiple variables: int num1, num2, highest, lowest;

3. Declare a variable with an initial value: int counter = 0;

4. Declare Dynamic initialization: int num1 = 10, num2 = 20; int total = num1 + num2; another example (using Math class to find square root – Math class to be covered after) double a = 3.0, b = 4.0; double c = Math.sqrt(a*a + b*b);

// Storing data in variables class VarDemo1{ public static void main (String args []){ // declare three variables int num1; int num2; int sum; Mr Noel Attard

Page: 5


JAVA Notes Form 3 – Part 1

// store data in two variables num1 = 12; num2 = 3; /* add the two numbers and store the result in sum */ sum = num1 + num2; // output the result System.out.println(sum); } }

// Storing data in variables class VarDemo2{ public static void main (String args []){ // declare variable sum int sum; // initialize two variables int num1 = 12; int num2 = 3; /* add the two numbers and store the result in sum */ sum = num1 + num2; // output the result System.out.println(sum); } }

// Declaring Integer types class StoreIntegers{ public static void main (String args[]){ // declaring integer types byte day; short refnum; int num; long itemno; // more program statements here // to make use of integers } } Mr Noel Attard

Page: 6


JAVA Notes Form 3 – Part 1

5. Constants A constant like a variable holds a place in memory, but the value of constants don’t change like in variables. E.g. pi can be used as a constant, VAT, etc….. The word final is used to declare constants in Java; constant names are in UPPERCASE. Examples: o static final int NUM = 10; o final double PI = 3.143;

//How to declare a constant in JAVA class Constants1{ static final int NUM = 10; //declare NUM with integer value of 10 final double PI = 3.143; //declare PI with double (decimal) value of 3.142 public static void main (String args[]){ System.out.println(NUM); System.out.println(PI); } }

6. Arithmetic Operators Arithmetic operators are used in mathematical expressions (as seen in previous examples, such as additions, subtractions, multiplications, divisions, areas, volumes, etc.). The table below shows a list of BASIC Arithmetic Operators Operator Operation Addition + Subtraction Multiplication * Division / Remainder e.g. 16 % 5 = 3 % Examples using Arithmetic operations: // Addition of two integer numbers class AddNums{ public static void main (String args[]){ int num1 = 12; int num2 = 3; int sum = num1 + num2; System.out.println(sum); } } Mr Noel Attard

Page: 7


JAVA Notes Form 3 – Part 1

// Addition of two integer numbers class SubtNumbers{ public static void main (String args[]){ int num1 = 12; int num2 = 3; int diff = num1 - num2; System.out.println(diff); } } ================================================== // Add, subtract, multiply and divide two numbers class Calcs1{ public static void main (String args[]){ // initialize the variables int num1 = 24; // book uses 24 so output is different int num2 = 6; // book uses 6 so output is different // processing section int sum = num1 + num2; int subt = num1 - num2; int mult = num1 * num2; int divis = num1/num2; // output the results System.out.println("Addition : " + sum); System.out.println("Subtraction : " + subt); System.out.println("Multiplication : " + mult); System.out.println("Division : " + divis); } } Formatting of values – printf (f for Format Specifier): To format the output we can use printf() instead of println(). To use printf note the following (see example after): - Output has to be within double quotes (“ “) but the variable outside the quotes after a comma (,) - As before text within the quotes will be outputted as it is - The % sign is required as part of the format specifier - The 10 (or any other number) is the length of the output field i.e. space for number - The .2 (or any other number) is the number of decimal - The \n is called an escape character to insert a new line - Also: … %015.4f\n – the 0 (zero) here causes the field to be padded with zeros i.e. fill in front with zeroes till you have 15 digits; the f is for float - Apart from f we can use: - d for an integer - c for a character - b for a Boolean - s for a string - t or T for time and date Mr Noel Attard

Page: 8


JAVA Notes Form 3 – Part 1

The table below shows a list of PREFIX & POSTFIX Arithmetic Operators Operator Equivalent to Operation n=n+1 Increment by 1 ++ n=n-1 Decrement by 1 -n=n+x Addition assignment += n=n-x Subtraction assignment -= n=n*x Multiplication assignment *= n=n/x Division assignment /= n=n%x Remainder assignment %=

Examples: a=a+7 b=b–3 c=c*5 d=d/9

a += 7 b -= 3 c *= 5 d /= 9

// Unary prefix and postfix class PostPreFix{ public static void main (String args[]){ // Prefix int n = 12; int m = ++n; // First adds 1 to n then stores it in m System.out.println("Prefix ++n : m = " + m); System.out.println(); // Postfix n = 12; // First stores n in m and then adds 1 to n m= n++; System.out.println("Postfix n++ : m = " + m); // show contents of n System.out.println("Value of n = " + n); } }

==================================================

// Demonstration of the modulus (remainder) (%) class ModulusDemo{ public static void main (String args []){ System.out.println("19 modulus 5 = " + 19 % 5); System.out.println("39 modulus 11 = " + 39 % 11); System.out.println("13 modulus 2 = " + 13 % 2); System.out.println("14 modulus 2 = " + 14 % 2); } } Mr Noel Attard

Page: 9


JAVA Notes Form 3 – Part 1

7. Reading data from keyboard Data from the keyboard can be entered (read) either using the scanner class or the keyboard class. In our case we are going to use the keyboard class •

To use the keyboard class insert the keyboard class (2 files) in the folder where you’re going to save your programs.

If the scanner class is going to be used we have to import it from the java.util and so at the beginning we use: import java.util.Scanner; •

If we type import.java.util.*; we import all utilities.

Used in many programs when using different utilities.

Using the keyboard class e.g. System.out.print(“Enter a number: “); int num1 = Keyboard.readInt(); (data types MUST match)

//Keyboard Entry Demo – Using the Keyboard class for input with different data types class KeyboardDemo{ public static void main (String args[]){ System.out.print("Enter an integer number(32 bit): "); // input data from keyboard int num1 = Keyboard.readInt(); System.out.print("Enter a number from -128 to 127: "); byte num2 = Keyboard.readByte(); System.out.print("Enter a number from -32,768 to 32,767: "); short num3 = Keyboard.readShort(); System.out.print("Enter a long number (64 bit): "); long num4 = Keyboard.readLong(); System.out.print("Enter a float number number (decimal - 32 bit): "); //decimal float num5 = Keyboard.readFloat(); System.out.print("Enter a double precision number (decimal - 64 bit): "); double num6 = Keyboard.readDouble(); System.out.print("Enter a character: "); char ch = Keyboard.readChar(); System.out.print("Enter true or false: "); boolean tf = Keyboard.readBoolean(); Mr Noel Attard

Page: 10


JAVA Notes Form 3 – Part 1

// output data on screen System.out.println("-------------------"); System.out.println("Integer: "+num1); System.out.println("Byte: "+num2); System.out.println("Short: "+num3); System.out.println("Long: "+num4); System.out.println("Float: "+num5); System.out.println("Double: "+num6); System.out.println("Character: "+ch); System.out.println("Boolean: "+tf); System.out.println("-------------------"); } } ================================================== //Using the Keyboard class class KeyboardInp1{ public static void main (String args []){ // declare three variables int num1; int num2; int sum; // Ask user to input data System.out.print("Enter first integer number: "); // a prompt num1 = Keyboard.readInt(); System.out.print("Enter second number: "); num2 = Keyboard.readInt(); // add the two numbers and store the result in sum sum = num1 + num2; // output the result System.out.println("Addition = " + sum); } }

7. The Math Class - The Math class has functions which we use in Mathematical problems - The functions we are going to use are: • • • • • • •

pow() – powers e.g. 28 sqrt() – square root abs() –absolute value i.e. abs(4) = 4 and abs(-4) = 4 random() – to generate random nos. from 0 to 1 less than number in bracket round() – to round numbers i.e. without decimal numbers ceil() – returns the smallest integer which is not less than the value given floor() – returns the largest integer which is not greater than the value given

Mr Noel Attard

Page: 11


JAVA Notes Form 3 – Part 1

- Math class can be used in two ways: •

By importing at the beginning all the class i.e. typing at the beginning (1st line) – EXAMPLE 2 below - import static java.lang.Math.*

By using Math.function() e.g Math.pow(2,8)

pow() – To find the power of a number

Using powers //Math Class: Pow() using the Math.pow() method public class Power1{ public static void main (String args[]){ int a = 2; int b = 8; System.out.println("pow(2.0, 2.0) is: "+Math.pow(2.0,2.0)); System.out.println("pow(a, b) is: "+Math.pow(a,b)); } }

sqrt() – returns the square root of the value in the brackets Finding square root of a number //Math Class: sqrt() - Find the square root of a number public class SquareRoot{ public static void main (String args[]){ int num = 81; System.out.println("Square root of 16 is: " +Math.sqrt(16)); System.out.println("Square root of num is: " +Math.sqrt(num)); } }

abs() – returns always a positive number Finding the absolute number of different numbers //Abs() Example public class AbsDemo{ public static void main (String args[]){ int i = 7; int j = -9; Mr Noel Attard

Page: 12


JAVA Notes Form 3 – Part 1

double x = 72.3; double y = 0.34; System.out.println("i is " +i); System.out.println("j is " +j); System.out.println("x is " +x); System.out.println("y is " +y); System.out.println("Abs() of " +i +": " +Math.abs(i)); System.out.println("Abs() of " +j +": " +Math.abs(j)); System.out.println("Abs() of " +x +": " +Math.abs(x)); System.out.println("Abs() of " +y +": " +Math.abs(y)); }

random() – generates a random number from 0 to 1 less than the number in the bracket. Since random generates a double precision number, type casting will be needed with int. Generates different ranges of random numbers //Math Class: random() - generate a random number between 0 and 1 less than number in bracket public class RandomNum{ public static void main (String args[]){ //type casting using (int) is required //to give precise answer as integer not decimal int num1 = (int)(Math.random() * (10)) + 1; int num2 = (int)(Math.random() * (100)) + 1; int num3 = (int)(Math.random() * (6)) + 1; int num4 = (int)(Math.random() * (2)) + 1; System.out.println("Random number between 1 and 10: " +num1); System.out.println("Random number between 1 and 100: " +num2); System.out.println("Throw a dice (1 to 6): " +num3); System.out.println("Toss a coin: 1=Heads 2=Tails " +num4);

Mr Noel Attard

Page: 13


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.