Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 9

Lab 1

Java basics
• Java is pure OOP language
• Java program is composed of 1 or more classes
– Class is a blue print for collection of similar objects
– Defines state and behavior of objects
• Data
• Operations
• A java program must have a main method
• One of the public class name must match the
java file name
Conventions
• Names in java are camel cased if name is composed
of multiple words
• Class name (Every word should start with capital
letter)
– GradeBook, Book, UserGroup
• Method names (camel cased with the exception of
the first word)
– calculateAverage(), findMaximumMark(), calculate()
• Variable names (Same with that of method names)
– minimumMark , birthDate, grade, maximumMark
Input / output
• Standard output is done via
– System.out.print()
– Ssytem.out.println()
– These are methods defined in java.lang class
• Standard Input form the keyboard is done through Scanner class
– U need to Import java.util.Scanner
• The following are some of the methods provided by scanner
class
– nextInt(); to input integer
– nextDouble(); to input double
– next(); to input string
– nextChar(); to input character
– nextLong(); to input long
Example
• Write a program called KeyboardScanner to prompt
user for an int, a double, and a String. The output shall
look like (the inputs are shown in bold):
– Enter an integer: 12
– Enter a floating point number: 33.44
– Enter your name: Peter
– Hi! Peter, the sum of 12 and 33.44 is 45.44
import java.util.Scanner; // needed to use Scanner for input
public class KeyboardScanner {
public static void main(String[] args) {
int num1; double num2; String name; double sum;
// Setup a Scanner called in to scan the keyboard (System.in)
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer: ");
num1 = in.nextInt(); // use nextInt() to read int
System.out.print("Enter a floating point number: ");
num2 = in.nextDouble(); // use nextDouble() to read double
System.out.print("Enter your name: ");
name = in.next(); // use next() to read String
// Display ...... // Close the input stream
in.close();
}}
OOP Basics
• Constructor
– Overloaded constructor
• This keyword
• Getter and setter methods
• toString()
– Return description of an instance
– Invoked as instance.toString() //explicit call
– Println(instanceName) //implicit call
Example 1
Exercise 1

You might also like