Classes
/**
* JAVA CLASSES
* --------------------------------------
* In Java, everything goes into a class.
* - src/main/Classes.java
*
* Java virtual machine (JVM) compiles the class and creates an archive.
* - target/classes/Class.class
*
* Key Points:
* - Every java program starts in main() method.
* - Return type `void` means there is no returned value.
* - Every statement must end in semicolon.
*
* Objects:
* - A class is a blueprint for an object.
* - Instance variables (fields) is what an object knows.
* - Methods are what an object does.
* -----------------------------------
*/
package com.minte9.basics.classes;
public class Classes {
public static void main(String[] args) {
A obj = new A();
obj.setName("John");
System.out.println("Hello " + obj.name); // Hello John
}
}
class A {
public String name;
public void setName(String name) { // This is a class method
this.name = name;
}
}
Input Stream
/**
* INPUT STREAM - Scanner
* ----------------------------------------
* Read input from stdin (standard input)
* Write output to stdout (standard output)
* ----------------------------------------
*/
package com.minte9.basics.classes;
import java.util.Scanner;
public class InputStream {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt(); // 10
int b = scanner.nextInt(); // 20
System.out.println("b: " + b); // b: 20
System.out.println("a: " + a); // a: 10
// ---------------------------
// a: 20
// a: 10
int n = scanner.nextInt(); // 2147483647
double d = Double.parseDouble(scanner.next()); // 235345345345.234534
scanner.nextLine();
String s = scanner.nextLine(); // Hello World
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + n);
// --------------------------------
// String: Hello World
// Double: 2.3534534534523453E11
// Int: 2147483647
scanner.close();
}
}
Questions and answers:
Clink on Option to Answer
1. In Java code source goes into:
- a) a class
- b) a file with .class extension
2. JVM Compiler creates a new related file:
- a) MyClass.class
- b) MyClass.java
3. Where does every Java program start?
- a) In the main() method
- b) In the constructor
4. What does void in main() mean?
- a) The method returns nothing
- b) The method returns a String
5. Every statement in Java must end with:
- a) A semicolon ;
- b) A colon :
6. What is a class in Java?
- a) A blueprint for an object
- b) An object itself
7. What do instance variables represent?
- a) What an object knows (its data)
- b) What an object prints
8. What do methods represent?
- a) What an object does (its behavior)
- b) What an object stores
9. What does this.name = name; mean?
- a) Assign a value to the current object’s variable
- b) Create a new class