Week of 11-28, ArrayList and Vocab
- Trimester 1 Notes
Trimester 1 Notes
Casting Notes
- Casting is when programmers are trying to assign a value from one data type to another data type
- Widening Casting is when smaller data types convert to bigger data types
- Happens automatically
- Narrowing Casting is when larger data types convert to smaller data types
- Happens manually
- Widening Casting is when smaller data types convert to bigger data types
- The chain of smallest to biggest data types is
- byte, short, char, int, long, float, double
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
Main.main(null);
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
}
}
Main.main(null);
Casting with Division
- Java typically assumes that an integer result is appropriate when doing division with integers
- However, using a mixture of integers (int) and floating point numbers (double), Java assumes that a double result is appropriate
- To do this though, one must use casting
- Cast one of the integers to a double using (double), changing the “shape” or the data type of the variable
- To do this though, one must use casting
- However, using a mixture of integers (int) and floating point numbers (double), Java assumes that a double result is appropriate
public class Test
{
public static void main(String[] args)
{
// automatic casting here
System.out.println(1 / 3);
System.out.println(1.0 / 3);
System.out.println(1 / 3.0);
// manual casting here
System.out.println((float) 1 / 3);
}
}
Test.main(null);
import java.io.*;
public class TrunctionExample1
{
//driver code
public static void main(String args[])
{
//the number to truncate
double num = 19.87874548973101;
//number of digits to take after decimal
int digits = 5;
System.out.println("The number before truncation is: "+num);
//calling user-defined method that truncates a number
truncateNumber(num, digits);
}
//user-defined method to truncate a number
static void truncateNumber(double n, int decimalplace)
{
//moves the decimal to the right
n = n* Math.pow(10, decimalplace);
//determines the floor value
n = Math.floor(n);
//dividing the floor value by 10 to the power decimalplace
n = n / Math.pow(10, decimalplace);
//prints the number after truncation
System.out.println("The number after truncation is: "+n);
}
}
TrunctionExample1.main(null);
Wrapper Classes
- Is essentially the practice of using primitive data types as objects
- You can use certain methods to get information about the specific object
Methods like the following are used to get the value associated with the respective wrapper object
intValue(), byteValue(), shortValue(), longValue(), floatValue(), doubleValue(), charValue(), booleanValue()
public class Main {
public static void main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
System.out.println(myInt.intValue());
System.out.println(myDouble.doubleValue());
System.out.println(myChar.charValue());
}
}
Main.main(null);
- The
to String()
method can be used when converting wrapper object to strings- The
length()
outputs the length of the "string" when converting an int to a string
- The
public class Main {
public static void main(String[] args) {
Integer myInt = 100;
String myString = myInt.toString();
System.out.println(myString.length());
}
}
Main.main(null);
Concatenation
- Combining two or more strings to form a new string
- Happens by appending the next string to the end of the previous strings
- In Java, two strings can be concatenated by using the + or += operator, or the
concat()
method in the java.lang.String class
- Example
- H E L L O + W O R L D becomes
- H E L L O W O R L D
class HelloWorld {
public static void main( String args[] ) {
String first = "Hello";
String second = "World";
// way 1
String third = first + second;
System.out.println(third);
// way 2
first += second;
System.out.println(first);
}
}
HelloWorld.main(null);
class HelloWorld {
public static void main( String args[] ) {
String first = "Hello";
String second = "World";
String third = first.concat(second);
System.out.println(third);
}
}
HelloWorld.main(null);
public class MathClass
{
public static void main(String[] args)
{
// generate random number
double a = Math.random();
double b = Math.random();
// Output is different every time this code is executed
System.out.println(a);
System.out.println(b);
}
}
MathClass.main(null);
public class RangedResult
{
public static void main(String[] args)
{
// Generate random number between 0 to 20
double a = Math.random() * 20;
double b = Math.random() * 20;
// Output is different every time this code is executed
System.out.println(a);
System.out.println(b);
}
}
RangedResult.main(null);
Compound Boolean Expressions
- Three compound boolean logical operators
- Operand1 must be a boolean variable and op may be &, |, or ^
- Java does not have any operators like &&= and ||=
- Compound Boolean Logical Assignment Operators are used in the form
operand1 op= operand2
which essentially meansoperand1 = operand1 op operand2
- For &= operator, if both operands evaluate to true, &= returns true. Otherwise, it returns false.
boolean b = true; b &= true; // Assigns true to b b &= false; // Assigns false to b
public class Permission
{
public static void main(String[] args)
{
boolean cleanedRoom = true;
boolean didHomework = false;
if (cleanedRoom && didHomework)
{
System.out.println("You can go out");
}
else
{
System.out.println("No, you can't go out");
}
}
}
Permission.main(null);
Truth Tables
- Shows result for P && Q when P and Q are both boolean expressions (can be true or false)
- An expression involving logical operators like (P && Q) evaluates to a Boolean value, true or false
- P && Q is only true if both P and Q are true.
- Shows the result for P || Q when P and Q are both boolean expressions
- P || Q is true if either P or Q is true
- Also true when both of them are true
- P || Q is true if either P or Q is true
De Morgan's Law
- This law came after the man named Augustus De Morgan who developed it in the 1800s. The law states how to determine what the code will execute when negation rules are applied. For example, if a and b are both boolean values, then:
- !(a && b) is equivalent to !a || !b
- !(a || b) is equivalent to !a && !b
The following negation conditions will also apply under De Morgan's law:
- < becomes >=
- ">" becomes <=
- == becomes !=
- <= becomes >
- = becomes <
- != becomes ==
String state = "HI";
// !(a || b) is equivalent to !a && !b
if (!(state.equals("TX") || state.equals("HI"))) {
System.out.println("The state is not Texas or Hawaii");
}
else {
System.out.println("The state is either Texas or Hawaii");
}
// !(a && b) is equivalent to !a || !b
if (!(state.equals("TX") && state.equals("HI"))) {
System.out.println("The state is either Texas or Hawaii");
}
else {
System.out.println("The state is not Texas or Hawaii");
}
public class CompareNum {
public static void main( String args[] ) {
Integer val1 = new Integer(5);
Integer val2 = new Integer(5);
Integer val3 = new Integer(10);
System.out.println("Integer 1 = "+val1);
System.out.println("Integer 2 = "+val2);
System.out.println("Integer 3 = "+val3);
System.out.println("val1 is equal to val2 = "+(val1 == val2));
System.out.println("val2 is not equal to val3 = "+(val2 != val3));
}
}
CompareNum.main(null);
Comparing Strings
- There are five different ways to compare strings in Java
- Using user-defined function
- Using
String.equals()
- Using
String.equalsIgnoreCase()
- Using
Objects.equals()
- Using
String.compareTo()
- In general both equals() and == operator both are used to compare objects to check equality
- There are some differences between the two
- one is method and other is operator
- == operators is for reference comparison and .equals() method is for content comparison
- Essentially, == checks if both objects point to the same memory location whereas .equals() actually compares the values of two objects
- There are some differences between the two
Comparing Objects
- You can compare objects in Java by using the == and != operators, which tells if two Java objects are the same or not
- This also works when comparing a primitive value with its wrapper type counterpart
Integer a = new Integer(1); assertThat(1 == a).isTrue();
- This also works when comparing a primitive value with its wrapper type counterpart
- The equals method can also be used to compare objects
- The methods returns true if both objects are the same and false if the two objects are different
For, Enhanced For, While, and Nested Loops
For Loops
- simplifies code by allowing it to repeat itself
- while loops have two portions: the boolean expression and the brackets that have some code in them
- the boolean expression is checked before the loop starts
- every time the loop ends and is about to start anew
- changes conditions again and again until returns false and ends the while loop
- iterates over numerous elements
- the boolean expression is checked before the loop starts
- for loops has three portions: initialization, test condition, and change
for (int x = 1; x <= 5; x++) { System.out.println(x); }
- when the loop condition is false, execution will continue at the next statement after the body of the loop.
- strings can also be manipulated through the use of iteration ``` String name = "CodeCodeCode";
for (int i = 0; i < name.length(); i+=2) { System.out.println(name.substring(i,i+2)); } ```
public class ForEachLoops {
public static void main(String[] args) {
// create an array
int[] data = {2, 10, 5, 12};
// for each loop
for (int number: data) {
System.out.println(number);
}
}
}
ForEachLoops.main(null);
Creating a Class
- There are a couple of steps to writing a class
- make sure to use the class keyword to create a class in the start
- To create an object of Main, specify the class name, followed by the object name, and use the keyword new
- Constructors are used to create new objects
- Instance variables are used to store any information regarding objects created in a class
- Methods are used to show programs a new command they must run
- specific methods are used to perform specific tasks in a class
Naming Conventions
- For variables, the Java naming convention is to always start with a lowercase letter and then capitalize the first letter of every subsequent word
- Variables can't contain white space, so variables made from compound words are to be written with a lower camel case syntax
- firstName
- timeToFirstLoad
- index
- Variables can't contain white space, so variables made from compound words are to be written with a lower camel case syntax
public class Main {
int x; // Create a class attribute
// Create a class constructor for the Main class
public Main() {
x = 5; // Set the initial value for the class attribute x
}
public static void main(String[] args) {
Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
System.out.println(myObj.x); // Print the value of x
}
}
Main.main(null);
No Returns
- What actually happens with the constructor is that the runtime uses type data generated by the compiler to determine how much space is needed to store an object instance in memory
- Includes all members variables and after the space is designated, the constructor is called as an internal part of the instantiation and initialization process
- The constructor exits, the runtime returns the newly-created instance
- Can't return a value because it's not called directly by your code, it's called by the memory allocation and object initialization code in the runtime