













Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!














The syntax for declaring and initializing a string variable
How to declare and initialize a string
How to join strings
How to join a string and a number
firstName = "Bob"; // firstName is Bob lastName = "Smith"; // lastName is Smith name = firstName + " "; // name is Bob followed by a space name = name + lastName; // name is Bob Smith
firstName = "Bob"; // firstName is Bob lastName = "Smith"; // lastName is Smith name = firstName + " "; // name is Bob followed by a space name += lastName; // name is Bob Smith
Example 1: New line String
Result
How to create an object from a class Syntax ClassName objectName = new ClassName(arguments); Examples
How to call a method from an object Syntax objectName.methodName(arguments) Examples
// create a Scanner object Scanner sc = new Scanner(System.in); // read a string System.out.print("Enter product code: "); String productCode = sc.next(); // read a double value System.out.print("Enter price: "); double price = sc.nextDouble(); // read an int value System.out.print("Enter quantity: "); int quantity = sc.nextInt(); // perform a calculation and display the result double total = price * quantity; System.out.println(); System.out.println(quantity + " " + productCode
userEntry.equals("Y") // equal to a string literal userEntry.equalsIgnoreCase("Y") // equal to a string literal (!lastName.equals("Jones")) // not equal to a string literal // equal to another string variable code.equalsIgnoreCase(productCode)
The syntax of the if/else statement if (booleanExpression) {statements} [else if (booleanExpression) {statements}] ... [else {statements}] How to code if/else statements An if/else statement , or just if statement , always contains an if clause. It can also contain one or more else if clauses, and a final else clause. If a clause requires more than one statement, you enclose the block of statements in braces. Otherwise, the braces are optional. Any variables that are declared within a block have block scope so they can only be used within that block.
A loop that continues while choice is “y” or “Y” String choice = "y"; while (choice.equalsIgnoreCase("y")) { // get the invoice subtotal from the user Scanner sc = new Scanner(System.in); System.out.print("Enter subtotal: "); double subtotal = sc.nextDouble(); // see if the user wants to continue System.out.print("Continue? (y/n): "); // what if you forget to reset the value for choice? choice = sc.next(); System.out.println(); }