\\ arguments given when running java
java MyProgram arg1 arg2 arg3
\\ general example
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
System.out.print("Hello World")
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Other day");
}
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
int[] myNumbers = {10, 20, 30, 40};
System.out.println(myNumbers[0]); // Outputs 10
public class Main {
public static class MyClass {
int x = 5;
}
public static void main(String[] args) {
MyClass myObj = new MyClass();
System.out.println(myObj.x);
}
}
class MyClass {
int x = 5;
}
public class Main {
public static void main(String[] args) {
MyClass myObj = new MyClass();
System.out.println(myObj.x);
}
}
Output
5
Dog inheretes the animalSound() method from the aminal class but redefines it by
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
public void animalSound() {
System.out.println("The dog says: bow wow"); // redefine what animalSount() does
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.animalSound();
}
}
The ability of a variable, function, or object to take on multiple forms. Here we see that we can instantiate a Dog object from the Animal class.
Animal myAnimal = new Dog(); // Polymorphism
myAnimal.animalSound(); // Outputs: The dog says: bow wow
The technique of making the fields in a class private and providing access via public methods. Because name is a private attribute, it can only be accessed via getName() and setName(), rather than through the instantiated object directly.
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
}