0% found this document useful (0 votes)
6 views

Programming Notes

class notes programming java

Uploaded by

hachemcaren
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Programming Notes

class notes programming java

Uploaded by

hachemcaren
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 7

Command prompt:

cd desktop
javac Name.java
java Name
************************
Java is case sensitive
In Java, class names starts with an uppercase letter

comments are ignored by Java


Single-line comment: //
Multi-line comments:
/* */

3 categories of identifiers:
**1st category: identifier that we made up:(names of these identifiers can be made
up of any
combination of letters, digits, special symbols. However, these names cannot start
with a digit
**2nd category: identifiers that someone else created (Examples include String,
System)
**3rd category: reserved words (have a special meaning): void, public, class
(start with lowercase letter)

3 types of errors:
- Compile-time error: a) syntax-related; b) detected by the compiler'
- Logical errors: when we don't get the intended result. In this case, code
compiles correctly.
Even worse, the code produces a result.
- Run-time errors: a) discovered by the interpreter during the execution. They are
also called
Exceptions.

System.out: object representing the screen

Nature of data: text


"1" --> 1 as text (String)
"" ---> empty string (0 chars)
" " ---> Not empty string (1 char ===> space)

Concatenation operator: +

"hi" + "5" ---> "hi5"


"hi" + 5 ---> "hi" + "5" ---> "hi5"
5 + 2 ---> 7
1 + 2 + "" ===> output: "3"
"" + 1 + 2 ===> output: "12"
"" + (1 + 2) ===> output: "3"

Variable: Name given to a memory location


DIU (Declare, Initialize, then Use)

8 primitive data types:


byte, short, int, long (integer value)
float, double (floating point values)
char (characters)
boolean (true or false)
byte ---> 8 bits; short: 16 bits; int: 32 bits; long: 64 bits
float: 32 bits; double: 64 bits
char: 16 bits

1 bit ===> 0 or 1 (2 values)


2 bits ===> 00, 01, 10, 11 (4 values)
... n bits ===> 2^n values

Decimal literal value (34.6) is by default considered to be a double unless I


append at its
end the letter (f or F) to force Java to treat it as a float (34.6f)

By default, integer literal values like 12 are considered to be int value unless
you put an
l or L at its end to force Java to treat it as a long value. (12 is an int; 12L is
a long)

int val = 12L; // compile-time error

Data types:
Primitive data types (8)
byte, short, int, long ==> integer values (without decimal part)
float, double ==> decimal values

Unicode character set ---> 16 bits ---> 2^16 characters (approx. 65000 characters)

'0' ---> 48

'9' ---> 57

digits: '0' < '1' < '2' ... <'9' ....< 'A' (65) < 'B' < 'C' ... 'Z' (90) ... 'a'
(65 + 32) ... 'z'

char letter1 = 'a', letter2 = 'b;


System.out.println(letter1 + letter2); // 97 + 98 = 195
System.out.println("" + letter1 + letter2); // "ab"
System.out.println(letter1 + letter2 + ""); // "195" ---> logical error
System.out.println((char) ('a' + 2)); // 'c'

'12' ---> invalid ===> "12"

Arithmetic Expressions:
% (remainder operator)

8 % 3 = 2
4 % 2 = 0

If either one of the operands or both are floating point values then the answer
will be a floating
point value.
2 + 3 ===> 5
2.0 + 3 ===> 5.0

3 / 2 ===> 1 (integer division is an example of a logical error)


3.0 / 2, 3 / 2.0, 3.0/2.0 ===> 1.5 (floating point division)

Operator precedence:
14 + 8 / 2 ---> 14 + 4 ---> 18
(14 + 8) / 2 ---> 11

***********************************************************************************
******************
Increment + decrement operators

To increment a variable called val by 1:


a) val = val + 1;
b) val += 1;
c) val++; or ++val;

val++; // Postfix increment operator


++val; // Prefix increment operator
val--;
or --val; // Decrement the value by 1
***********************************************************************************
******************

Data conversion:

In Java, conversions happen in one of three ways:


a) Via the assignment operator
b) Via promotion
c) Via casting

a) Assignment operator:
int dollars = 23;
double money = dollars; // Widening conversion supported by the assignment operator
// dollars = money; // Narrowing conversion attempt ==> compile-time error

b) Promotion:
9.0 / 2 ===> 9.0 / 2.0 = 4.5
"hi" + 5 ===> "hi" + "5" ===> "hi5"

a) Widening conversion: you go from one type to another that uses more space (safe)
b) Narrowing conversions: you go from one type ot another using less space

Casting:
(double)
The cast operator has higher precedence than /
***********************************************************************************
*****************

Scanner: Interactive programs

Scanner: class data type (starts with a capital S)


Objective: Read a line of text from the user and then echo it back to the screen

a) int is a primitive data type ==> val is a primitive variable

Scanner scan = new Scanner(System.in); // Declaration + Initialization


(instantiation)
a) Scanner is a class data type ==> scan is an object reference variables

import java.util.Scanner
Scanner offers a method called nextLine that has the following signature:
public String nextLine() ---->
a) String: type of method's output
b) nextLine: name of the method
c) (): empty list of parameters

- Not including import java.util.Scanner ===> compile-time error


- int val = scan.nextDouble(); ===> compile-time error ==> storing a double in an
int (narrowing)
- Providing a double value for an int variable during the execution through
scan.nextInt ===>
run-time error
***********************************************************************************
***************

Objects ---> Built-in Java classes


All the classes of the java.lang package are automatically imported
Examples include: System, String, etc...

To interact with the String object, we have to use the dot operator:
b) int len = str.length(); //length start from 1

2 variables pointing to the same object are said to be aliases of each other
I lost the last reference ==> This object becomes garbage (collected by garbage
collector)
We can force garbage collection in Java: System.gc();

In Java, String objects are immutable


To create a mutable String in Java, we have to use another class called
StringBuilder

In addition to equals and equalsIgnoreCase, String offers a method called compareTo


that returns
an int value:
****************
System.out.println(str1.compareTo(str2)); // 0 ---> values referenced by str1 and
str2 are same
// Positive value if object used to call compareTo (str1) follows the parameter
(str2)
// Negative value if object used to call compareTo (str1) precedes the parameter
(str2)

String: is an ordered set of characters where every character occupies a different


position
that has an index associated with it.

***************substring(int beginning, int end): beginning (inclusive) and end


(exclusive)

**************indexOf

String str = "Electrical";


System.out.println(str.indexOf('c')); // 3
System.out.println(str.indexOf('z')); // -1

***********************************************************************************
******************
Random class (java.util)
Random rnd = new Random();

- nextInt() or nextInt(int upperbound) ---> discrete random values


nextInt() ---> a random int between the smallest (Integer.MIN_VALUE) and largest
(Integer.MAX_VALUE)
int values
- nextInt(bound) ---> returns a random int value between 0 (inclusive) and bound -
1 (inclusive)a

rnd.nextInt(6) ---> 0 (inclusive) and 5 (inclusive)


rnd.nextInt(6) + 1 ---> 1 (inclusive) and 6 (inclusive)

int in the range of [lower; upper]

rnd.nextInt(a) + b ---> [0; a-1] + b ---> [b; b+a-1]


==> b = lower and b + a - 1 = upper

lower + a - 1 = upper ==> a = upper - lower + 1

nextFloat() ---> continuous random value


Generates a random floating point value between 0.0 (inclusive) and 1.0 (exclusive)

Challenge: use nextFloat to generate a random int value between 1 (inclusive) and 6
(inclusive)

nextFloat ---> [0.0; 1.0[

rnd.nextFloat() * a + b ---> rnd.nextFloat() * 6 + 1

[0.0; 1.0[ * 6 ---> [0.0; 6.0[ + 1 ---> [1.0; 7.0[ ---> (int) [1.0; 7.0[ --->
random int between
1 and 6.

(int) rnd.nextFloat() * 6 + 1 ---> output is always 1 because of the cast operator


(int) (rnd.nextFloat() * 6 + 1) ---> random int value between 1 and 6

***********************************************************************************
**********************

Math class (java.lang)

IMPPPPPPPPP:
***************
If the methods of the class are static ===> You just use the method through the
name of the class

Math.sqrt(4) --> 2.0


Math.pow(3, 2) ---> 9.0
Math.pow(4, 0.5) ---> 2.0
Math.pow(4, 1/2) ---> Math.pow(4, 0) ---> 1.0
cos, sin---> The parameter is an angle measured in radians
Math.PI() ---> invalid because PI is not a method
Math.PI ---> valid

Math.cos(Math.PI/2) ---> 0.0


Math.abs(-4) ---> 4 (type of output depends on type of the input)

All of its methods are static:


===> You can call the method using the class name

Math.sqrt(4) ---> 2.0

***********************************************************************************
***********************
DecimalFormat ---> java.text
a) DecimalFormat fmt = new DecimalFormat("0.###");
b) fmt.format(value to be formatted)

We cannot use a string to perform calculation.


Obstacle: How to convert a String into a number?

String str = "23.6";


double StrAsDouble = Double.parseDouble(str); // 23.6
str = "12A";
Double.parseDouble(str); // Runtime error because the string does not store a valid
number

Let us address the following question first:


How do we convert a number into a String?

First way: 12.5 + "" --> "12.5"


Second way: Double.toString(12.5) ---> "12.5"

12.5.concat("") // Invalid because primitve values don't offer methods

byte ---> Byte (Wrapper class)


short ---> Short (Wrapper class)
int ---> Integer (Wrapper class)
long ---> Long (Wrapper class)
float ---> Float (Wrapper class)
double ---> Double (Wrapper class)
char ---> Character (Wrapper class)
boolean ---> Boolean (Wrapper class)

===> All of the wrapper classes are part of java.lang

- Wrapper classes:
There 8 wrapper classes

They offer both non-static as well as static methods

double val = 23.5;


Aim: turn val into an object?

First approach:
Double valAsObj = new Double(val);
System.out.println(valsAsObj.intValue()); // 23

Second approach:
Double valAsObj = val; // Thanks to autoboxing:
// Autoboxing: automatic conversion between a primitive data type and
// the corresponding wrapper class
Unboxing:
Integer valAsObj = new Integer(23);
int val = valAsObj; // Unboxing
Automatic conversion between the wrapper class and its corresponding primitive data
type.

- JOptionPane ---> javax.swing

There are two types of dialog boxes:


a) Input Dialog Box: Gather values from the user
String valAsStr =
JOptionPane.showInputDialog("Please enter an int: ");

b) Output Dialog Box: Display an output message to the user

Example#2: JOptionPaneDemo.java

Kotlin ---> Use Android Studio to develop native Android Application

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy