Java Quick Overview
Java Quick Overview
Arrays in Java
1. Basic structure of a Java program int[] data = new int[10]; // Array to store 10 integer values
...
public class MyClass for (int i = 0; i < data.length; i++)
{ ...
public static void main(String[] args)
{ int[] someData = {10, 11, 12}; // Array with pre-defined data
// Main code of our program
} int[][] data2 = new int[5][]; // Array with 5 rows
} data2[0] = new int[3]; // Row 1 has 3 columns
data2[1] = new int[10]; // Row 2 has 10 columns
...
2. Basic data types: for (int i = 0; i < data2.length; i++)
for (int j = 0; j < data2[i].length; j++)
byte, short, int, long // float, double // char // boolean // String ...
try
{
// Code that may fail
} catch (NumberFormatException e1) { 15. Inheritance
// Error message for number format
} catch (DivideByZeroException e2) { public class Dog extends Animal
// Error message for dividing by zero
...
} catch (Exception eN) { Methods that can be overriden from Object:
// Error message for any other error
} @Override @Override
public boolean equals(Object o) public String toString()
Throwing exceptions:
We can use "super" to call methods and constructors from parent class
public static void a() throws InterruptedException
{ public Dog() {
throw new InterruptedException ("Exception in a"); super()
} ...
try
{
16. Abstract classes
a();
} catch (...) public abstract class Animal {
...
public abstract void talk();
}
13. Defining classes and objects
class Person
17. Interfaces
{
String name; public interface Shape { public class Circle implements Shape
int age; float calculateArea();
void draw();
public Person(String name, int age) }
{
this.name = name; 18. Anonymous classes
this.age = age;
} Person[] people = new Person[10];
...
public String getName() Arrays.sort(people, new Comparator<Person>()
{ {
return name; @Override
} public int compare(Person p1, Person p2)
{
public void setName(String name) return Integer.compare(p1.getAge(), p2.getAge())
{ }
this.name = name; });
}
… 19. Collections
}
List<String> myList = new ArrayList<>();
Person p = new Person("Nacho", 40); myList.add("Hello");
System.out.println(p.getName()); for (int i = 0; i < myList.size(); i++)
System.out.println(myList.get(i));
14. Visibility
Map<String, Person> data = new HashMap<>();
data.put("1111111A", new Person("Nacho", 40));
public: everyone can see the element for (String key: data.keySet())
protected: only subclasses and classes from the same package System.out.println(data.get(key));
private: only the own class
Set<String> mySet = new HashSet<>();
package (default value): only classes from the same package mySet.add("One");
Iterator<String> it = mySet.iterator();
while(it.hasNext())
System.out.println(it.next());