The document discusses the use of arrays and control flow statements in programming, including examples of using 'break' and 'continue' in loops. It also covers sorting arrays and objects, demonstrating natural sorting with a 'Person' class and alternative sorting using a 'Comparator'. Additionally, it includes conditional statements to output messages based on time values.
Download as TXT, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
2 views
Java learnings
The document discusses the use of arrays and control flow statements in programming, including examples of using 'break' and 'continue' in loops. It also covers sorting arrays and objects, demonstrating natural sorting with a 'Person' class and alternative sorting using a 'Comparator'. Additionally, it includes conditional statements to output messages based on time values.
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1
ArraysBreak / Continue
Animal [] zoo = new Animal [4];
zoo [0] = new Tiger(); zoo [1] = new Giraffe(); …for (int i = 0; i < 10; i++) { if (i == 4) { continue; //This skips the value of 4 } if (i == 6) { break; //This jumps out of the for loop } } String [] cars = {"Volvo", "BMW", "Ford", "Mazda"}; System.out.println(cars.length); //Outputs 4 int [][] myNumbers = {{1, 2, 3, 4}, {4, 5, 6}}; int x = myNumbers [1][2]; System.out.println(x); //Outputs 6 If...Else Arrays.sort(cars); System.out.println(Arrays.toString(cars)); //[BMW, Ford, Mazda, Volvo] SORTING OBJECTS WITH MULTIPLE PARAMETERS: NATURAL SORTING (Created within class) public class Person implements Comparable<Person>{… @Override public int compareTo(Person o) { return Double.compare(this.weight, o2.weight); } ----> Use wrapperclass int time = 22; if (time < 10) { System.out.println("Good morning!"); } else if (time < 20) { System.out.println("Good day!"); } else { System.out.println("Good evening!"); } //Outputs "Good evening!" variable = (condition) ? expressionTrue : Arrays.sort(listOfPeople); / Collections.sort(...); ALTERNATIVE SORTING (Created in sepparate class) public class SortOnName implements Comparator<Person>{ @Override public int compare(Person o1, Person o2) { return o1.getName().compareTo(o2.getName());