Introduction to Java Programming

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

What is the primary purpose of a computer program?

  • To create operating systems
  • To execute a sequence of instructions (correct)
  • To design computer hardware
  • To manage network security

Assembly language provides a direct correspondence between instructions and architecture's machine code instructions.

True (A)

What component of an operating system is responsible for loading programs and libraries into memory?

Loader

The ______ translates a program in a high-level language to machine instructions.

<p>compiler</p> Signup and view all the answers

Match the following computer components with their functions:

<p>CPU = Executes instructions and controls the computer's operations Memory = Stores programs and data while they are being used ALU = Performs arithmetic and logical operations Input/Output Modules = Allows the computer to interact with external devices</p> Signup and view all the answers

Which phase of Java programming involves verifying that bytecodes are valid and do not violate security restrictions?

<p>Verify (C)</p> Signup and view all the answers

Java identifiers are case-insensitive.

<p>False (B)</p> Signup and view all the answers

What is the file extension used for Java bytecode files after compilation?

<p>.class</p> Signup and view all the answers

In Java, comments that are ignored by the compiler but used by the javadoc tool for automatically generating documentation are called ______ comments.

<p>documentation</p> Signup and view all the answers

Match the following Java IDE components with their functions:

<p>Editor = Allows writing and modifying source code. Compiler = Translates source code into bytecode. Interpreter/Loader = Executes bytecode. Debugger = Helps find and fix errors in code.</p> Signup and view all the answers

Which of the following is NOT a primitive data type in Java?

<p>String (D)</p> Signup and view all the answers

In Java, it is possible to divide a string literal across multiple lines of code without concatenation.

<p>False (B)</p> Signup and view all the answers

What is the term for combining two or more strings together in Java?

<p>Concatenation</p> Signup and view all the answers

A named location in memory used to store a data value is called a ______.

<p>variable</p> Signup and view all the answers

Match numeric data size with their memory:

<p>byte = 8 bits short = 16 bits int = 32 bits long = 64 bits</p> Signup and view all the answers

Which operator has the highest precedence in Java?

<p>() (B)</p> Signup and view all the answers

Constants can change their value during the execution of a program.

<p>False (B)</p> Signup and view all the answers

What reserved word is used to declare a constant in Java?

<p>final</p> Signup and view all the answers

Converting a value from one data type to another is known as ______.

<p>casting</p> Signup and view all the answers

Match data conversion:

<p>Promotion = Automatic data type conversion to a larger type Casting = Explicit data type conversion, which may result in data loss</p> Signup and view all the answers

Which Java class is commonly used to read input from the console?

<p>Scanner (A)</p> Signup and view all the answers

A Scanner object automatically closes the input stream after reading all the data.

<p>False (B)</p> Signup and view all the answers

What method of the Scanner class is used to read an entire line of input as a String?

<p>nextLine()</p> Signup and view all the answers

Methods of the Scanner class separate input into ______, using whitespace as a delimiter by default.

<p>tokens</p> Signup and view all the answers

Match scanner class methods with action:

<p>next() = Returns the next input token hasNext() = Returns true if there is another token.</p> Signup and view all the answers

What is the equality operator to compare primitive types?

<p>== (B)</p> Signup and view all the answers

Equality Relational operator can not be used to compare strings.

<p>True (A)</p> Signup and view all the answers

What kind of expression is required inside parentheses in an if statement?

<p>Boolean</p> Signup and view all the answers

A block of code that executes repeatedly while a condition is true is called a ______.

<p>loop</p> Signup and view all the answers

Match looping statements with description.

<p>for loop = Good to be used when the start and end values are clearly definied. while loop = Executes codes, if the condition is true.</p> Signup and view all the answers

Which statement allows skipping the remainder of the current iteration of a loop and proceeding with the next iteration?

<p>continue (D)</p> Signup and view all the answers

A break statement will cause a loop to immediately terminate.

<p>True (A)</p> Signup and view all the answers

What is a series of programming language statements that are performed a given a name?

<p>Method</p> Signup and view all the answers

A method that does not return any value has a return type of ______.

<p>void</p> Signup and view all the answers

Match definition with name:

<p>formal parameters = parameter in header of the method actual parameters = parameter in the invocation</p> Signup and view all the answers

Which access modifier provides the broadest access to a class member?

<p>public (C)</p> Signup and view all the answers

A constructor must have a return type, even if it is void.

<p>False (B)</p> Signup and view all the answers

What are methods called that are used to access the variable value of an object?

<p>Accessors</p> Signup and view all the answers

The process of hiding the implementation details of a class and protecting its data from unauthorized access is called ______.

<p>encapsulation</p> Signup and view all the answers

Object orientated relationships

<p>Inheritance = Is a Aggregation = Has a</p> Signup and view all the answers

Flashcards

Computer Program

Sequence of instructions for a computer to execute.

Assembly Language

Low-level language that directly corresponds to machine code.

High-Level Language

User-friendly language independent of computer's hardware.

Assembler

Translates assembly code into machine instructions.

Signup and view all the flashcards

Compiler

Translates high-level code into machine instructions.

Signup and view all the flashcards

Linker

Links object modules into a single executable file.

Signup and view all the flashcards

Loader

Loads programs/libraries into computer memory.

Signup and view all the flashcards

Interpreter

Executes instructions directly without prior compilation.

Signup and view all the flashcards

Classes

Java programs consist of these.

Signup and view all the flashcards

Objects

Instances of classes.

Signup and view all the flashcards

Attributes

Data of an object.

Signup and view all the flashcards

Methods

Actions related to objects.

Signup and view all the flashcards

Java Program Phases

Edit, Compile, Load, Verify, Execute.

Signup and view all the flashcards

JDK

Software development environment for Java applications.

Signup and view all the flashcards

.java

File name must match class name with this extension.

Signup and view all the flashcards

main() method

Java code within an application class is written in this method.

Signup and view all the flashcards

//

The compiler ignores everything after this to the end of the line.

Signup and view all the flashcards

/* ... */

The compiler ignores everything between these.

Signup and view all the flashcards

/** documentation */

The compiler ignores this kind of comment.

Signup and view all the flashcards

Identifiers

Words used when writing Java programs.

Signup and view all the flashcards

Valid Identifier

Combination of letters, digits, _ and $, but cannot start with digit.

Signup and view all the flashcards

Case Sensitive

Case matters in Java.

Signup and view all the flashcards

Variable Naming

Lowercase first letter, then CamelCase.

Signup and view all the flashcards

Class Naming

Capitalize the first letter of each word.

Signup and view all the flashcards

White Space & Indentation

Removes unnecessary spaces for better readability.

Signup and view all the flashcards

Java's Primitive Data Types

byte, short, int, long, float, double, char, boolean

Signup and view all the flashcards

Integer Types

No fractional part.

Signup and view all the flashcards

Floating Point Types

Can have a fractional part.

Signup and view all the flashcards

Character String

An object in Java, defined by String class.

Signup and view all the flashcards

Concatenate strings using this operator.

Signup and view all the flashcards

Variable

Named memory location to hold a data value.

Signup and view all the flashcards

Variable Declaration

Reserves memory space for a certain data type.

Signup and view all the flashcards

Assignment Statement

Assigning values to variables.

Signup and view all the flashcards

Constants

Identifiers that hold a fixed value.

Signup and view all the flashcards

Expression

Combination of operators and operands.

Signup and view all the flashcards

Arithmetic Operators

+, -, *, /, %

Signup and view all the flashcards

Increment/Decrement

++, --

Signup and view all the flashcards

Relational Operators

, >=, <, <=, ==, !=

Signup and view all the flashcards

Logical Operators

&&, ||, !

Signup and view all the flashcards

Data Conversion

Convert data type to another type.

Signup and view all the flashcards

Study Notes

  • These Java notes do not replace a textbook, they are summary notes and may not cover all lecture details

Introduction to Java

  • A computer program comprises instructions in a programming language for a computer to execute
  • Computer programming involves designing/building executable programs, algorithm creation, accuracy profiling, resource consumption analysis, and algorithm implementation.
  • Programming languages offer notations for writing computer programs
  • Assembly language offers low-level programming with strong instruction-to-architecture correspondence
  • High-level languages are user-friendly, independent of computer hardware
  • Java was developed by James Gosling and colleagues at Sun Microsystems in the early 1990s
  • Java is an object-oriented, platform-independent programming language, promising "Write Once, Run Anywhere"
  • Structure includes classes
  • Objects are class instances: each class yields many objects; programs feature objects from various classes.
  • Classes contains attributes and methods
  • Attributes hold object data, methods perform related actions.
  • Java has a rich set of classes in its class libraries, known as API's

Java Program Phases

  • Edit: creates files ending with ".java."
  • Compile: generates ".class" files with bytecodes.
  • Load: transfers bytecodes from disk to memory.
  • Verify: confirms bytecode validity, ensuring no security breaches.
  • Execute: Java Runtime reads/ translates bytecodes for the computer.
  • Oracle develops Java SDK (Software Development Kit), commonly referred to as JDK (Java Development Kit).
  • JDK aids Java app development, including JRE, compiler, archiver, and documentation generator.
  • Get JDK from: https://www.oracle.com/technetwork/java/javase/downloads/index.html.
  • IDEs simplify Java tasks with tools for editing, compiling, and running programs.
  • Eclipse is a powerful Java IDE.

Basic Java Elements

  • Source files: classname.java
  • the file extension .java must match the class name.
  • Outputs: "Welcome to Java!" when executing WelcomeJavaApp.java
  • The WelcomeJavaApp class exemplifies an application class featuring a "main" method
  • Comments in Java includes
  • // text: Compiler ignores from // to line end.
  • /* text */: Compiler ignores content between /* and */.
  • /** documentation */: Used by JDK javadoc tool for generating documentation, otherwise similar to /* */.
  • Identifiers are program words of numbers, letters, underscores (_), and dollar signs ($), but not digits.
  • Valid identifiers: c3po, a77_4E, _4aT, $a70b, $, _0, _a, _$, $1, 1, $X$, _x$, a, A.
  • Invalid identifiers: a7+e44, _4-aT, 7aa, an.ne, ba ba
  • Case sensitivity applies to Java identifiers
  • Reserved words in Java includes abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, default, do, double, else, enum, extends, false, final, finally, float, for, goto, if, implements, import, instanceof, int, interface, long, native, new, null, package, private, protected, public, return, short, static, strictfp, super, switch, synchronized, this, throw, throws, transient, true, try, void, volatile, while

Java Naming Conventions

  • Class names are written in CamelCase
  • Variable names are all lower case
  • Multi word names are camel case but lower case for the first word
  • Constant Identifiers: ALL_CAPS

White Space and Indentation

  • Whitespace improves code readability, while poor indentation hinders understanding.

Primitive Data Types

  • Java uses a strong type system in which each data value has a specific type.
  • Java offers 8 primitive data types, all of them numeric

Integer Data Types

  • Integer data types has no fractional segments
  • Integer data types examples include byte, short, int, and long.
  • Data type byte: 8 bits (1 byte); Range: -128 to +127
  • Data type short: 16 bits (2 bytes); Range: -32,768 to +32,767
  • Data type int: 32 bits (4 bytes); Range: ~-2 billion to +2 billion
  • Data type long: 64 bits (8 bytes); Range: ~-10E18 to +10E18

Floating Point Data Types

  • Floating point types includes fractional values represented by float and double
  • Data type float: 32 bits (4 bytes); Range: ~-3.4E+38 to +3.4E+38
  • Data type double: 64 bits (8 bytes); Range: ~-1.7E+308 to +1.7E+308

Character Strings

  • A character string, defined by String, is a Java object.
  • The double quotation marks define a String literal, which contains any valid characters
  • Examples: "", "x", "C3PO", "-248", "Menekse cad. Lale sok. No: 14/22, Sevgi Mah., Antalya".
  • Multiple segments, divided through program lines, uses + concatenation.

Variables, Identifiers and Assignments

  • Identifiers label various sections of code.
  • Composed of letters, numbers, underscores (_), and dollar($) signs, but cannot start with numbers.
  • Valid identifiers: c3po, a77_4E, _4aT, $a70B, $, _0, _a, _$, $1, 1, $X$, _x$
  • Invalid identifiers: a7+e44, _4-aT, 7aa, beat.les, ab ba
  • Variables are named memory locations holding data.
  • Variable declarations specify memory space for particular values.

Declaration

  • Allocates an integer, int keys;.
  • Allocates space with initial value: int keys = 88;
  • Multiple variables of same type: int result = 0, count = 0, limit = 80, number;
  • Assignment statements assign values to variables
  • Identifier = Expression basic assignment format.

Constants

  • Constants are identifiers holding fixed values
  • Constants are declared using the final keyword.
  • Constants are written in capital letters
  • final int MAX_OCCUPANCY = 487;
  • An expression is a mix of operators, operands that performs calculation, like variables, literals.

Operators and Expressions

  • Arithmetic Operators: +, -, *, /, %
  • Increment / Decrement Operators: ++, --
  • Relational Operators: >, >=, <, <=, ==, !=
  • Logical Operators: && (and), || (or), ! (not)
  • Assignment Operators: =, +=, -=, *=, /=, %=

Operator Precedence

  • Higher-precedence operators apply before lower-precedence operators.

Data conversion

  • Data Conversion converts data values of one type to another.
  • Potential data loss exists, care is required

Simple Input

  • The Scanner class simplifies reading input values.
  • Creation of scanner object required

Conditionals and Loops

  • Boolean expressions yield boolean values (true or false)
  • Equality and Relational Operators compare data of the same type
  • Equality: ==, Not equal: !=
  • Less than: <, Less than or equal to: <=
  • Greater than: >, Greater than or equal to: >=

Logical Operators

  • NOT !a: is true if a is false
  • AND a && b: is true if both a and b are true
  • OR a || b: is true if either a or b or both are true
  • If statement executes if statement if the boolean expression is true.

If else statement

  • If the boolean expression is true the if block is executed. If false the else block is executed

Nested if statement

  • An if-else statement that contains another if statement inside the if block, else block or both
  • Comparing strings: Use .equals() and .compareTo() rather than operators.
  • s1.equals(s2) determines lexical equality of strings s1 and s2
  • s1.compareTo(s2) compares s1 and s2. In which positive values indicate s1 > s2 and negative indicate s1 < s2.

Switch statements

  • The switch statement executes programs based on a value, which can be int, byte, short, char, or String
  • Values for each case must be constant
  • Print the values from 1 to 7.

For loop

  • A loop that repeats a statement a specific number of times that can be determined before the loop is started.

While Statement

  • Runs so long as the condition is true

Do statement

  • The do statement runs similar to the while statement except the condition is at the end of the loop. The code will always run at least once.
  • break statements can stop looping, control transfers after the loop finishes
  • use continue to skip current step, resuming with next

Methods in Java

  • Methods are named programming statement groups, defined like functions in C and Python.
  • Method declarations specify code for execution when the method is invoked.
  • Every method in Java is part of some class. Each may be an application or class object
  • When a method is called, control is given to that method. After it's completed and done, control then reverts to the one who gave the control.
  • The called method might be in the same or different class; calling needs the other method's name, or the other object.
  • methods may return value or may not return
  • Return type: primitive, class, or void
  • Return statements transfer control to caller, otherwise they do not contains a return statement
  • Parameter inputs may be 0 to many
  • The parameter, passed in with method invokes, makes a list of the right values

Method Parameters Names

  • Formal parameters: Names in method header.
  • Actual parameters: Values in invocation, can be any variables.
  • When called: copy of the value, each actual becomes stored.
  • Need types and numbers of parameter.
  • A method's invocation must include the parameter list with parentheses, or empty if no arguments.

Local Data

  • Scope: sections where valid references can have variables
  • Variables form inside one method are the local type given, in data from objects
  • Limited access to where variables work

Using Classes and Objects

  • Java involves using a class library, supporting development, and containing classes with helpful methods
  • String class is in Java's standard library (java.lang) accessible via Java environments.
  • Class library clusters related classes, known as Java APIs and application interfaces
  • Each class belongs to a package; String class is part of java.lang, Scanner is in java.util
  • java.lang offers general support, automatically importing into Java programs.
  • java.util provides utilities, like the Scanner class.
  • To use classes from a non java.lang package, import with java.util.Scanner; or java.util.*;.

Creating Objects

  • Class objectName = new Constructor(arguments);
  • // variable of a basic data type such as int num; String name; Variable that holds an integer value:
  • 24 = num ; String value that contains “Kaan Ekermen”. Note that the new operator returns a reference to a newly created object.
  • After creating , the dot operator to access run its methods like count = name.length();
  • Object declarations combine reference variables and creation: String title = new String("Java Software Solutions"); Aliases: String name1 = "Ingrid Bergman"; String name2 = "Dr. Alexander Fleming"; Name2 = name1;

String Class

  • It is a class that deals with strings. Some useful methods to use: String() , int Length() ,char charAt (int index), boolean equals(String str) and etc... String (String str)

Charaters Methods

  • That called character methods such as "Character.methodName(char)", some example is boolean isLetter(), boolean isLetterOrDigit(), boolean isUpperCase(), and e tc..

Math Class

  • Provided in java.lang package
  • Provide basic mathematical function such as .abs - value ,pi π Number Class: Radom() : that can generates radnom numbers

Formatting Output

  • The Prinf ( Print formula)
  • Format spifiers such as type
  • Int %d %nd % and double %f %. N %m
  • Number Format: that can output and display such as amount and etc...

File Input and Output

The Scanner class together with File objects can read a text file. Scanner fileScan = new Scanner (new File(fileName)); to opening a file String line = fileScan.nextLine(); // read a line from text file.

  • To text files; open/close is not always correct. So, we should use Scanner a lot instead Class PrintWriter- for text, can access all file including print, println a lot!

Arrays

  • Powerful language used to arrange and organized data
  • Fixed Array: That is set for space
  • In java the arrays will always be starting at zero not 1
  • Declaring and Using Arrays. Cannot use the other date type beside what if was set for
  • Set an Array list

2D Arrays

  • Array can have one , two, three or even more dimensions Java still allow but not directly 3D

ArrayList

  • Part of java .util.package in java class library
  • Different with other is that it shrink dynamically as needed unlike array that are fixed
  • Object get (int index ) in other word get the list and attention you must type cast it!
  • If you delete an arralist it will COLLAPSE AND so this means to be keen to keep them close with what is kept together.

Static members

  • All methods from the math class
  • They aint object but through that class name of the object The Static Variables.

Class Relationship

  • Software have varoius to relationship type of relationships.
  • dependency relation " uses"
  • a relationship "has-a" Inheritence- a relationship "is a" Method Design

Static members

  • All methods from the math class
  • They aint object but through that class name of the object The Static Variables.

Class Relationship

  1. Software have varoius to relationship type of relationships.
  2. dependency relation " uses" but in another word: If class A uses class B , there must be a point when A references B ( has access to the other) . However this point can be minimised!
  3. Aggregation a relationship "has-a" Inheritence- a relationship "is a" Method Design, but in Java parameter always get a copy of other side!

Sorting And Searching

  • In order and numerical method is algorithm that the list in order to search

Sorting and Searcing Algorithms

  • In computer science, a sorting algorithm is an algorithm that puts elements of a list in a certain order to search. Such as. Numerical search and lexicographical.
  • There is bubble search and other type
  • Linear Search and or Sequential search is a method for finding particular values.

Recursion

  • Power in programming technique and is to provide elegant solution to certain problems.
  • Think with two parts and the problem is dived to those part
  • Base care and or simple case. And complex case

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Use Quizgecko on...
Browser
Browser