Quiz CompSci Summary
Quiz Structure
Public class: Represents a class declaration in Java, serving as a blueprint for objects. It encapsulates data (variables/fields) and methods that operate on that data.
Example class header:
public class QuizOpening curly brace:
{indicates the beginning of the class body.
Method Declarations: Define the behavior or actions that an object can perform. Each method has a specific syntax for its header and a body containing programming statements.
Method header example:
public void methodName(String[] cipple).public: Access modifier, meaning the method is accessible from any other class.void: Return type, indicating the method does not return any value.methodName: The name of the method.(String[] cipple): The parameter list, specifying the type and name of inputs the method expects.
Opening curly brace for the method:
{marks the start of the method's code block.Programming statements included such as:
int val = 20;Declares an integer variablevaland initializes it to .System.out.println(val);Prints the value ofvalto the console.Closing curly braces
}: Indicate the end of a method body and, subsequently, the end of the class body for the outermost brace.
Java Application Standard Method
Main Method: All executable Java applications must contain this entry point. The Java Virtual Machine (JVM) starts program execution here.
Full method header syntax:
public static void main(String[] args)public: Access modifier, allowing the JVM to access this method.static: Indicates that this method belongs to the class itself, not to a specific instance (object) of the class, allowing it to be called without creating an object.void: Return type, meaning the method does not return any value.main: The required name for the entry-point method.(String[] args): A parameter that allows the program to accept command-line arguments as an array of strings.
Curly Brackets in Java
Curly Braces: Used to define code blocks, grouping related statements together in various contexts.
Encloses a group of statements for classes, methods, conditional statements (
if/else), and loops (for/while):Encloses an initializer block or an array definition:
{}Curly braces are not used to enclose a string of characters; double quotes are used for string literals:
"Hello"
Complete Statement: Every executable statement in Java must end with a semicolon:
;Class Body: All methods, constructors, and field declarations that belong to a class are defined within its class body, enclosed by curly braces.
Output Statements in Java
Standard Output: Java sends information to standard output (usually the console) using the
System.outobject.System.outis an instance of thePrintStreamclass, located within theSystemclass, which provides access to platform-independent system functionality.
Commonly used print methods:
System.out.print(value): Prints thevalueto the console without adding a new line character at the end.System.out.println(value): Prints thevalueto the console and then moves the cursor to the next line.System.out.printf(format, args...): Allows for formatted output, similar to C'sprintffunction, using format specifiers.
Example Outputs
If
public void method1()code runs:Statements include printing out a variable:
int varX = 43;Output line:
System.out.println(varX);Expectation: This will successfully compile and print
43ifSystem.out.println(varX);is within themethod1scope or a scope wherevarXis accessible. IfSystem.out.println(varX);were called outsidemethod1withoutvarXbeing declared in an accessible scope, it would result in a compile-time error due to an unknown variable reference.
Console Output for Specific Code Examples
Code example:
int value = 25;
value = 10;
System.out.print("value is " + value);
Output:
value is 10(The variablevalueis first assigned , then re-assigned . The last assignment determines the final value.)Usage of the
+operator in this context:
Concatenation: The
+operator is used to join strings, or a string with another data type (like an integer or double), resulting in a single, combined string.
Identifiers in Java
Identifiers are names used for variables, methods, classes, and packages. They must follow specific rules:
Valid identifiers include:
value,VALUE,value123,$value,_value
Invalid identifiers examples:
Starting with numbers (e.g.,
123value)Including spaces (e.g.,
my value)Containing special characters other than
$or_(e.g.,value#)Using Java reserved keywords (e.g.,
class,public,int)
Variable Types and Declarations
Floating-point types: Used to store numbers with decimal places.
float: Single-precision 32-bit floating-point. RequiresforFsuffix (e.g.,).double: Double-precision 64-bit floating-point. This is the default floating-point type if no suffix is specified.
A variable can hold only one value at a time; assigning a new value overwrites the previous one.
Example for integer variable:
int dollar = 12;Declares an integer variabledollarand initializes it to .Output of
System.out.print(dollar);will be:12
For double type:
double pay = 1,023.0;will not compile due to wrong number format. Java uses a dot (.) as the decimal separator, not a comma (,). The comma would be interpreted as a list of separate values or an invalid character in a number literal.
Operators and Their Priorities
List of Operators - Highest to Lowest Priority:
!- logical NOT (negation)*- multiplication/- division%- modulus (remainder of division)+- addition (or string concatenation)-- subtraction
Primitive Data Types Ranking
Order from lowest (smallest range/memory) to highest (largest range/memory) for numeric types, indicating implicit casting hierarchy:
byte(8-bit integer)short(16-bit integer)int(32-bit integer)long(64-bit integer)float(32-bit floating-point)double(64-bit floating-point)
Constants Declaration
Constants are variables whose values cannot be changed after initialization. They are declared using the
finalkeyword.Example of declaring a constant in Java:
final double PI = 3.14;The value ofPIcannot be modified later in the program.Naming convention: By convention, constants are typically named using all uppercase letters with underscores (
_) to separate words (e.g.,MAX_VALUE).
String Manipulation
A String is a sequence of characters. In Java,
Stringis a class, not a primitive type, andStringobjects are immutable (their content cannot be changed after creation).Created as:
String name = "Henry";(String literal, often preferred)or
String name = new String("Henry");(Using thenewkeyword to create an object explicitly)
Example to access a character:
System.out.println(name.charAt(3));The
charAt(int index)method returns the character at the specified index.Indexing in Java (and most programming languages) starts at .
For
"Henry",charAt(0)is 'H',charAt(1)is 'e',charAt(2)is 'n',charAt(3)is 'r'.This will output the fourth character:
r.
Scanner Class and Input
The
Scannerclass is part of thejava.utilpackage and is used to obtain input from various sources, such as the keyboard (console).Importing Scanner class before using it:
import java.util.Scanner;
Creating a Scanner object to read from standard input (
System.in):Scanner keyB = new Scanner(System.in);(System.inrepresents the standard input stream, typically the keyboard).Common methods:
keyB.nextInt(): Reads an integer.keyB.nextDouble(): Reads a double.keyB.next(): Reads a single word (token) as a String.keyB.nextLine(): Reads an entire line of input as a String.
Variable Scope
Scope refers to the region of a program where a variable can be accessed or used.
Variables declared inside methods are local variables. They are only accessible within the method (or the specific block of code, like a loop or
ifstatement) where they are declared.Local variables are not in scope outside that method or block. Their lifetime begins when execution enters their block and ends when execution exits it.
Example of local variable usage:
int value = 12;is declared within a specific block and is in scope only where declared and within its sub-blocks.
Print Formatting in Java
Using
printffor formatted output with format specifiers:Syntax example:
System.out.printf("Hi - my age is %d, height is %d%n", age, height);%d: Format specifier for decimal integers (int,long).%f: Format specifier for floating-point numbers (float,double).%s: Format specifier for strings.%c: Format specifier for characters.%nor\n: Platform-independent new line character.printfallows control over precision, width, and alignment.
Documentation and Comments in Java
Single-line comments start with
//and extend to the end of the line. Used for brief explanations or disabling code.Multi-line comments are enclosed with
/*...*/. Used for longer explanations that span multiple lines.Documentation comments start with
/**and end with*/. They are used to generate API documentation (Javadoc) and provide a concise summary of classes, methods, and fields.
Java Class Concepts
Class: A fundamental building block in object-oriented programming. It serves as a blueprint or a template for creating objects (instances).
Example:
public class Homework { private int number; private char letter; }private int number;: This is a field (or instance variable), representing the state of an object.private char letter;: Another field.
Methods in classes: Define the behaviors that objects of the class can perform.
Accessors (getters): Methods designed to retrieve (get) the current value of a private field. They typically have a
getprefix (e.g.,int getNumber()).Mutators (setters): Methods designed to modify (set) the value of a private field. They typically have a
setprefix and accept a parameter (e.g.,void setNumber(int newNumber)).
Control Structures
If Statements: Used to define conditions, allowing different blocks of code to execute based on whether a boolean expression is true or false.
Basic structure:
if (condition) {
// code to execute if condition is true
} else if (anotherCondition) {
// code to execute if condition is false and anotherCondition is true
} else {
// code to execute if all preceding conditions are false
}
Switch Statements: Provide an alternative to multiple
if-else ifstatements when you need to select one of many code blocks to execute based on the value of a single variable.Applicable to
byte,short,int,char,enum, andString(since Java 7).Uses
caselabels for specific values and abreakstatement to exit theswitchblock.A
defaultcase can be included to handle any value not explicitly matched by acase.
Conclusion
Always ensure correctness in syntax, semantics, and data types in Java programming to avoid compile-time and runtime errors.
Awareness of variable scope (local vs. instance), appropriate use of data types, valid identifiers, and understanding operator precedence is critical for effective and error-free coding in Java.
Best practices, such as consistent naming conventions and clear commenting, enhance code readability and maintainability.