The document provides an overview of Lesson 3 which will address random and math classes, conditional statements including if, if-else, and switch statements. It discusses variables, data types, operators, and methods from classes like Random, Math, and Scanner. The document also covers formatting output, indentation, block statements, nested if statements, and the logic of if and if-else statements.
This document provides an overview of key concepts in the Java programming language, including:
- Java is an object-oriented language that is simpler than C++ and supports features like platform independence.
- The Java development environment includes tools for compiling, debugging, and running Java programs.
- Java programs work with basic data types like int and double, as well as user-defined classes, variables, and arrays.
- The document explains operators, control structures, formatting output, and the basics of classes and objects in Java.
This document provides an overview of primitive data types, expressions, and definite loops (for loops) in Java. It discusses Java's primitive types like int, double, char, and boolean. It covers arithmetic operators, precedence rules, and mixing numeric types. It also introduces variables, declarations, assignments, and using variables in expressions. Finally, it explains the syntax of for loops using initialization, a test condition, and an update to repeat a block of code a specified number of times.
In this page, we will learn about the basics of OOPs. Object-Oriented Program...Indu32
In this page, we will learn about the basics of OOPs. Object-Oriented Programming is a paradigm that provides many concepts, such as inheritance, data binding, polymorphism, etc.
The document discusses Java's primitive data types and for loops. It introduces Java's primitive types like int, double, char, and boolean. It covers expressions, operators, and precedence. It then introduces variables, declaring and initializing variables, and using variables in expressions. Finally, it covers the for loop structure with initialization, test, and update sections to allow repetition of code.
The document discusses Java's primitive data types and for loops. It introduces Java's primitive types like int, double, char, and boolean. It covers expressions, operators, and precedence. It then introduces variables, declaring and initializing variables, and using variables in expressions. Finally, it covers the for loop structure with initialization, test, and update sections to allow repetition of code.
This document provides an overview of basic Java programming concepts including:
- Java programs require a main method inside a class and use print statements for output.
- Java has primitive data types like int and double as well as objects. Variables are declared with a type.
- Control structures like if/else and for loops work similarly to other languages. Methods can call themselves recursively.
- Basic input is done through dialog boxes and output through print statements. Formatting is available.
- Arrays are objects that store multiple values of a single type and know their own length. Strings are immutable character arrays.
Java is software programming language that rules the software world during 1995 to till date. It is an evergreen programming language. Internet flourished with java.
This document provides an introduction to Java programming. It discusses learning about creating Java programs, including input, output, branching, looping, and the history of Java's development. Operators, decision making constructs like if/else statements, and loops like for and while are also covered. The reader will learn the basics of writing Java programs.
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
The document discusses Java syntax and concepts including:
1. It introduces primitive data types in Java like int, float, boolean and String.
2. It covers variables, operators, and expressions - how they are used to store and manipulate data in Java.
3. It explains console input and output using Scanner and System.out methods for reading user input and printing output.
4. It provides examples of using conditional statements like if and if-else to control program flow based on conditions.
Three key points about the document:
1. Java has several primitive data types including boolean, char, byte, short, int, long, float, and double. Arrays allow grouping of multiple variables of the same type.
2. Arrays are dynamically allocated objects in Java. To create an array, the type and size must be specified using new, such as int[] numbers = new int[100]. Individual elements can then be accessed by index like numbers[25].
3. Type conversions may occur automatically between compatible types like int and long. Incompatible types require casting, such as (double)value to convert an int to a double. Arrays can be used to store and average multiple
This document provides an introduction to C++ programming including problem solving skills, software evolution, procedural and object oriented programming concepts, basic C++ programs, operators, header files, conditional statements, loops, functions, pointers, structures and arrays. It discusses topics such as analyzing problems, planning algorithms, coding solutions, evaluating results, procedural and object oriented paradigms, inheritance, polymorphism, flowcharts, basic syntax examples, and more. Various examples are provided to illustrate key concepts in C++.
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysDevaKumari Vijay
The document discusses various Java data types including primitive data types like byte, short, int, long, float, double, char, boolean and their ranges. It also explains variables in Java - local variables, instance variables, static variables. Different types of operators like arithmetic, assignment, comparison, logical, bitwise operators are defined along with examples. The document also covers conditional statements like if-else, switch case and different loops in Java - for, while, do-while loops along with examples. Break and continue statements in Java loops are also explained.
Java allows writing code once that can run on any platform. It compiles to bytecode that runs on the Java Virtual Machine (JVM). Key features include automatic memory management, object-oriented design, platform independence, security, and multi-threading. Classes are defined in .java files and compiled to .class files. The JVM interprets bytecode and uses just-in-time compilation to improve performance.
- Java is a platform independent programming language that is similar to C++ in syntax but similar to Smalltalk in its object-oriented approach. It provides features like automatic memory management, security, and multi-threading capabilities.
- Java code is compiled to bytecode that can run on any Java Virtual Machine (JVM). Only depending on the JVM allows Java code to run on any hardware or operating system with a JVM.
- Java supports object-oriented programming concepts like inheritance, polymorphism, and encapsulation. Classes can contain methods and instance variables to define objects.
- Java is a platform independent programming language that is similar to C++ in syntax but similar to Smalltalk in its object-oriented approach. It provides features like automatic memory management, security, and multi-threading capabilities.
- Java code is compiled to bytecode that can run on any Java Virtual Machine (JVM). The JVM then interprets the bytecode and may perform just-in-time (JIT) compilation for improved performance. This allows Java programs to run on any platform with a JVM.
- Java supports object-oriented programming principles like encapsulation, inheritance, and polymorphism. Classes can contain methods and instance variables. Methods can be called on objects to perform operations or retrieve data.
- Java is a platform independent programming language that is similar to C++ in syntax but similar to Smalltalk in its object-oriented approach. It provides features like automatic memory management, security, and multi-threading capabilities.
- Java code is compiled to bytecode that can run on any Java Virtual Machine (JVM). Only depending on the JVM allows Java code to run on any hardware or operating system with a JVM.
- Java supports object-oriented programming concepts like inheritance, polymorphism, and encapsulation. Classes can contain methods and instance variables. Methods perform actions and can return values.
This document provides an overview of the C++ programming language. It discusses key C++ concepts like classes, objects, functions, and data types. Some key points:
- C++ is an object-oriented language that is an extension of C with additional features like classes and inheritance.
- Classes allow programmers to combine data and functions to model real-world entities. Objects are instances of classes.
- The document defines common C++ terms like keywords, identifiers, constants, and operators. It also provides examples of basic programs.
- Functions are described as modular and reusable blocks of code. Parameter passing techniques like pass-by-value and pass-by-reference are covered.
- Other concepts covered include
The document discusses different ways of implementing type conversion in Java. It covers widening and narrowing conversions, as well as assignment conversion, promotion, and casting. It provides examples of each type of conversion and discusses how conversions can occur during arithmetic expressions and assignments. It also covers wrapper classes and their role in type conversions.
This document provides an overview of the Java programming language. It discusses Java's history and why it was created. It also outlines some of Java's key fundamentals like variables, data types, operators, and control statements. Additionally, it covers object-oriented programming concepts in Java like classes, objects, inheritance and encapsulation. The document is intended to help readers get started with learning Java.
Data types, Variables, Expressions & Arithmetic Operators in javaJaved Rashid
This document covers fundamentals of programming in Java, including data types, variables, expressions, and arithmetic operators. It discusses the 8 primitive data types in Java (byte, short, int, long, float, double, char, boolean), rules for naming variables, how to declare and assign values to variables, and how expressions are evaluated using arithmetic operators. It provides examples of declaring variables of different data types and using variables in expressions and print statements.
Intro to programing with java-lecture 3Mohamed Essam
This document provides an introduction to Java programming concepts including:
- A simple Java program that prints "Welcome to Java!" is presented to demonstrate a class, method, and output.
- Numeric operators, expressions, and performing mathematical computations in Java are explained.
- Common types of errors in programming like syntax errors, runtime errors, and logic errors are defined.
- Increment and decrement operators, augmented assignment operators, and if statements for conditional logic are described to illustrate basic programming constructs in Java.
This chapter provides an in-depth overview of the viscosity of macromolecules, an essential concept in biophysics and medical sciences, especially in understanding fluid behavior like blood flow in the human body.
Key concepts covered include:
✅ Definition and Types of Viscosity: Dynamic vs. Kinematic viscosity, cohesion, and adhesion.
⚙️ Methods of Measuring Viscosity:
Rotary Viscometer
Vibrational Viscometer
Falling Object Method
Capillary Viscometer
🌡️ Factors Affecting Viscosity: Temperature, composition, flow rate.
🩺 Clinical Relevance: Impact of blood viscosity in cardiovascular health.
🌊 Fluid Dynamics: Laminar vs. turbulent flow, Reynolds number.
🔬 Extension Techniques:
Chromatography (adsorption, partition, TLC, etc.)
Electrophoresis (protein/DNA separation)
Sedimentation and Centrifugation methods.
Ad
More Related Content
Similar to Unit 1: Primitive Types - Variables and Datatypes (20)
Java is software programming language that rules the software world during 1995 to till date. It is an evergreen programming language. Internet flourished with java.
This document provides an introduction to Java programming. It discusses learning about creating Java programs, including input, output, branching, looping, and the history of Java's development. Operators, decision making constructs like if/else statements, and loops like for and while are also covered. The reader will learn the basics of writing Java programs.
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
The document discusses Java syntax and concepts including:
1. It introduces primitive data types in Java like int, float, boolean and String.
2. It covers variables, operators, and expressions - how they are used to store and manipulate data in Java.
3. It explains console input and output using Scanner and System.out methods for reading user input and printing output.
4. It provides examples of using conditional statements like if and if-else to control program flow based on conditions.
Three key points about the document:
1. Java has several primitive data types including boolean, char, byte, short, int, long, float, and double. Arrays allow grouping of multiple variables of the same type.
2. Arrays are dynamically allocated objects in Java. To create an array, the type and size must be specified using new, such as int[] numbers = new int[100]. Individual elements can then be accessed by index like numbers[25].
3. Type conversions may occur automatically between compatible types like int and long. Incompatible types require casting, such as (double)value to convert an int to a double. Arrays can be used to store and average multiple
This document provides an introduction to C++ programming including problem solving skills, software evolution, procedural and object oriented programming concepts, basic C++ programs, operators, header files, conditional statements, loops, functions, pointers, structures and arrays. It discusses topics such as analyzing problems, planning algorithms, coding solutions, evaluating results, procedural and object oriented paradigms, inheritance, polymorphism, flowcharts, basic syntax examples, and more. Various examples are provided to illustrate key concepts in C++.
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysDevaKumari Vijay
The document discusses various Java data types including primitive data types like byte, short, int, long, float, double, char, boolean and their ranges. It also explains variables in Java - local variables, instance variables, static variables. Different types of operators like arithmetic, assignment, comparison, logical, bitwise operators are defined along with examples. The document also covers conditional statements like if-else, switch case and different loops in Java - for, while, do-while loops along with examples. Break and continue statements in Java loops are also explained.
Java allows writing code once that can run on any platform. It compiles to bytecode that runs on the Java Virtual Machine (JVM). Key features include automatic memory management, object-oriented design, platform independence, security, and multi-threading. Classes are defined in .java files and compiled to .class files. The JVM interprets bytecode and uses just-in-time compilation to improve performance.
- Java is a platform independent programming language that is similar to C++ in syntax but similar to Smalltalk in its object-oriented approach. It provides features like automatic memory management, security, and multi-threading capabilities.
- Java code is compiled to bytecode that can run on any Java Virtual Machine (JVM). Only depending on the JVM allows Java code to run on any hardware or operating system with a JVM.
- Java supports object-oriented programming concepts like inheritance, polymorphism, and encapsulation. Classes can contain methods and instance variables to define objects.
- Java is a platform independent programming language that is similar to C++ in syntax but similar to Smalltalk in its object-oriented approach. It provides features like automatic memory management, security, and multi-threading capabilities.
- Java code is compiled to bytecode that can run on any Java Virtual Machine (JVM). The JVM then interprets the bytecode and may perform just-in-time (JIT) compilation for improved performance. This allows Java programs to run on any platform with a JVM.
- Java supports object-oriented programming principles like encapsulation, inheritance, and polymorphism. Classes can contain methods and instance variables. Methods can be called on objects to perform operations or retrieve data.
- Java is a platform independent programming language that is similar to C++ in syntax but similar to Smalltalk in its object-oriented approach. It provides features like automatic memory management, security, and multi-threading capabilities.
- Java code is compiled to bytecode that can run on any Java Virtual Machine (JVM). Only depending on the JVM allows Java code to run on any hardware or operating system with a JVM.
- Java supports object-oriented programming concepts like inheritance, polymorphism, and encapsulation. Classes can contain methods and instance variables. Methods perform actions and can return values.
This document provides an overview of the C++ programming language. It discusses key C++ concepts like classes, objects, functions, and data types. Some key points:
- C++ is an object-oriented language that is an extension of C with additional features like classes and inheritance.
- Classes allow programmers to combine data and functions to model real-world entities. Objects are instances of classes.
- The document defines common C++ terms like keywords, identifiers, constants, and operators. It also provides examples of basic programs.
- Functions are described as modular and reusable blocks of code. Parameter passing techniques like pass-by-value and pass-by-reference are covered.
- Other concepts covered include
The document discusses different ways of implementing type conversion in Java. It covers widening and narrowing conversions, as well as assignment conversion, promotion, and casting. It provides examples of each type of conversion and discusses how conversions can occur during arithmetic expressions and assignments. It also covers wrapper classes and their role in type conversions.
This document provides an overview of the Java programming language. It discusses Java's history and why it was created. It also outlines some of Java's key fundamentals like variables, data types, operators, and control statements. Additionally, it covers object-oriented programming concepts in Java like classes, objects, inheritance and encapsulation. The document is intended to help readers get started with learning Java.
Data types, Variables, Expressions & Arithmetic Operators in javaJaved Rashid
This document covers fundamentals of programming in Java, including data types, variables, expressions, and arithmetic operators. It discusses the 8 primitive data types in Java (byte, short, int, long, float, double, char, boolean), rules for naming variables, how to declare and assign values to variables, and how expressions are evaluated using arithmetic operators. It provides examples of declaring variables of different data types and using variables in expressions and print statements.
Intro to programing with java-lecture 3Mohamed Essam
This document provides an introduction to Java programming concepts including:
- A simple Java program that prints "Welcome to Java!" is presented to demonstrate a class, method, and output.
- Numeric operators, expressions, and performing mathematical computations in Java are explained.
- Common types of errors in programming like syntax errors, runtime errors, and logic errors are defined.
- Increment and decrement operators, augmented assignment operators, and if statements for conditional logic are described to illustrate basic programming constructs in Java.
This chapter provides an in-depth overview of the viscosity of macromolecules, an essential concept in biophysics and medical sciences, especially in understanding fluid behavior like blood flow in the human body.
Key concepts covered include:
✅ Definition and Types of Viscosity: Dynamic vs. Kinematic viscosity, cohesion, and adhesion.
⚙️ Methods of Measuring Viscosity:
Rotary Viscometer
Vibrational Viscometer
Falling Object Method
Capillary Viscometer
🌡️ Factors Affecting Viscosity: Temperature, composition, flow rate.
🩺 Clinical Relevance: Impact of blood viscosity in cardiovascular health.
🌊 Fluid Dynamics: Laminar vs. turbulent flow, Reynolds number.
🔬 Extension Techniques:
Chromatography (adsorption, partition, TLC, etc.)
Electrophoresis (protein/DNA separation)
Sedimentation and Centrifugation methods.
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetSritoma Majumder
Introduction
All the materials around us are made up of elements. These elements can be broadly divided into two major groups:
Metals
Non-Metals
Each group has its own unique physical and chemical properties. Let's understand them one by one.
Physical Properties
1. Appearance
Metals: Shiny (lustrous). Example: gold, silver, copper.
Non-metals: Dull appearance (except iodine, which is shiny).
2. Hardness
Metals: Generally hard. Example: iron.
Non-metals: Usually soft (except diamond, a form of carbon, which is very hard).
3. State
Metals: Mostly solids at room temperature (except mercury, which is a liquid).
Non-metals: Can be solids, liquids, or gases. Example: oxygen (gas), bromine (liquid), sulphur (solid).
4. Malleability
Metals: Can be hammered into thin sheets (malleable).
Non-metals: Not malleable. They break when hammered (brittle).
5. Ductility
Metals: Can be drawn into wires (ductile).
Non-metals: Not ductile.
6. Conductivity
Metals: Good conductors of heat and electricity.
Non-metals: Poor conductors (except graphite, which is a good conductor).
7. Sonorous Nature
Metals: Produce a ringing sound when struck.
Non-metals: Do not produce sound.
Chemical Properties
1. Reaction with Oxygen
Metals react with oxygen to form metal oxides.
These metal oxides are usually basic.
Non-metals react with oxygen to form non-metallic oxides.
These oxides are usually acidic.
2. Reaction with Water
Metals:
Some react vigorously (e.g., sodium).
Some react slowly (e.g., iron).
Some do not react at all (e.g., gold, silver).
Non-metals: Generally do not react with water.
3. Reaction with Acids
Metals react with acids to produce salt and hydrogen gas.
Non-metals: Do not react with acids.
4. Reaction with Bases
Some non-metals react with bases to form salts, but this is rare.
Metals generally do not react with bases directly (except amphoteric metals like aluminum and zinc).
Displacement Reaction
More reactive metals can displace less reactive metals from their salt solutions.
Uses of Metals
Iron: Making machines, tools, and buildings.
Aluminum: Used in aircraft, utensils.
Copper: Electrical wires.
Gold and Silver: Jewelry.
Zinc: Coating iron to prevent rusting (galvanization).
Uses of Non-Metals
Oxygen: Breathing.
Nitrogen: Fertilizers.
Chlorine: Water purification.
Carbon: Fuel (coal), steel-making (coke).
Iodine: Medicines.
Alloys
An alloy is a mixture of metals or a metal with a non-metal.
Alloys have improved properties like strength, resistance to rusting.
Understanding P–N Junction Semiconductors: A Beginner’s GuideGS Virdi
Dive into the fundamentals of P–N junctions, the heart of every diode and semiconductor device. In this concise presentation, Dr. G.S. Virdi (Former Chief Scientist, CSIR-CEERI Pilani) covers:
What Is a P–N Junction? Learn how P-type and N-type materials join to create a diode.
Depletion Region & Biasing: See how forward and reverse bias shape the voltage–current behavior.
V–I Characteristics: Understand the curve that defines diode operation.
Real-World Uses: Discover common applications in rectifiers, signal clipping, and more.
Ideal for electronics students, hobbyists, and engineers seeking a clear, practical introduction to P–N junction semiconductors.
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsesushreesangita003
what is pulse ?
Purpose
physiology and Regulation of pulse
Characteristics of pulse
factors affecting pulse
Sites of pulse
Alteration of pulse
for BSC Nursing 1st semester
for Gnm Nursing 1st year
Students .
vitalsign
Multi-currency in odoo accounting and Update exchange rates automatically in ...Celine George
Most business transactions use the currencies of several countries for financial operations. For global transactions, multi-currency management is essential for enabling international trade.
GDGLSPGCOER - Git and GitHub Workshop.pptxazeenhodekar
This presentation covers the fundamentals of Git and version control in a practical, beginner-friendly way. Learn key commands, the Git data model, commit workflows, and how to collaborate effectively using Git — all explained with visuals, examples, and relatable humor.
The ever evoilving world of science /7th class science curiosity /samyans aca...Sandeep Swamy
The Ever-Evolving World of
Science
Welcome to Grade 7 Science4not just a textbook with facts, but an invitation to
question, experiment, and explore the beautiful world we live in. From tiny cells
inside a leaf to the movement of celestial bodies, from household materials to
underground water flows, this journey will challenge your thinking and expand
your knowledge.
Notice something special about this book? The page numbers follow the playful
flight of a butterfly and a soaring paper plane! Just as these objects take flight,
learning soars when curiosity leads the way. Simple observations, like paper
planes, have inspired scientific explorations throughout history.
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessMark Soia
Boost your chances of passing the 2V0-11.25 exam with CertsExpert reliable exam dumps. Prepare effectively and ace the VMware certification on your first try
Quality dumps. Trusted results. — Visit CertsExpert Now: https://www.certsexpert.com/2V0-11.25-pdf-questions.html
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingCeline George
The Accounting module in Odoo 17 is a complete tool designed to manage all financial aspects of a business. Odoo offers a comprehensive set of tools for generating financial and tax reports, which are crucial for managing a company's finances and ensuring compliance with tax regulations.
As of Mid to April Ending, I am building a new Reiki-Yoga Series. No worries, they are free workshops. So far, I have 3 presentations so its a gradual process. If interested visit: https://www.slideshare.net/YogaPrincess
https://ldmchapels.weebly.com
Blessings and Happy Spring. We are hitting Mid Season.
How to Manage Opening & Closing Controls in Odoo 17 POSCeline George
In Odoo 17 Point of Sale, the opening and closing controls are key for cash management. At the start of a shift, cashiers log in and enter the starting cash amount, marking the beginning of financial tracking. Throughout the shift, every transaction is recorded, creating an audit trail.
INTRO TO STATISTICS
INTRO TO SPSS INTERFACE
CLEANING MULTIPLE CHOICE RESPONSE DATA WITH EXCEL
ANALYZING MULTIPLE CHOICE RESPONSE DATA
INTERPRETATION
Q & A SESSION
PRACTICAL HANDS-ON ACTIVITY
1. Unit 1: Primitive Types
Variables and Datatypes
Adapted from:
1) Building Java Programs: A Back to Basics
Approach
by Stuart Reges and Marty Stepp
2) Runestone CSAwesome Curriculum
https://longbaonguyen.github.io
This work is licensed under the
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
2. 2
Data Types
A type is a set of values (e.g. integers, floats, etc..) and a set
of operations (e.g. +, -, *, /, etc..) on them.
Data types can be categorized as either primitive or
reference.
The primitive data types used in this course define the set of
operations for numbers and Boolean(true or false) values.
Reference variables or object variables hold a reference(or
address) to an object of a class(more on this in a future
lecture).
3. 3
Primitive types
The primitive types on the Advanced Placement Computer
Science A exam are:
•int - which store integers (whole numbers like 3, -76, 20393)
•double - which store floating point numbers (decimal
numbers like 6.3, -0.9, and 60293.93032)
•boolean - which store Boolean values (either true or false).
4. 4
Receipt example
What's bad about the following code?
public class Receipt {
public static void main(String[] args) {
// Calculate total owed, assuming 8% tax / 15% tip
System.out.println("Subtotal:");
System.out.println(38 + 40 + 30);
System.out.println("Tax:");
System.out.println((38 + 40 + 30) * .08);
System.out.println("Tip:");
System.out.println((38 + 40 + 30) * .15);
System.out.println("Total:");
System.out.println(38 + 40 + 30 +
(38 + 40 + 30) * .08 +
(38 + 40 + 30) * .15);
}
}
– The subtotal expression (38 + 40 + 30) is repeated
– So many println statements
– We will use variables to solve the above problems.
5. 5
Variables
• variable: A piece of the computer's memory that is given a name
and type, and can store a value.
– Like preset stations on a car stereo, or cell phone speed dial:
– Steps for using a variable:
• Declare it - state its name and type
• Initialize it - store a value into it
• Use it - print it or use it as part of an expression
6. 6
Declaration
• variable declaration: Sets aside memory for storing a value.
– Variables must be declared before they can be used.
• Syntax:
type name;
• The name is an identifier.
– int x;
– double myGPA;
x
myGPA
7. 7
Assignment
• assignment: Stores a value into a variable.
– The value can be an expression; the variable stores its result.
• Syntax:
name = expression;
– int x;
x = 3;
– double myGPA;
myGPA = 1.0 + 2.25;
x 3
myGPA 3.25
8. 8
Using variables
• Once given a value, a variable can be used in expressions:
int x;
x = 3;
System.out.println("x is " + x); // x is 3
System.out.println(5 * x - 1); // 14
• You can assign a value more than once:
int x;
x = 3;
System.out.println(x + " here"); // 3 here
x = 4 + 7;
System.out.println("now x is " + x); // now x is 11
x 3
x 11
string concatenation:
string + number = concatenated string
(more on this later)
9. 9
Declaration/initialization
• A variable can be declared/initialized in one statement.
• Syntax:
type name = value;
– double myGPA = 3.95;
– int x = (12 - 3) * 2;
x 18
myGPA 3.95
10. 10
Assignment and algebra
• Assignment uses = , but it is not an algebraic equation.
= means, "store the value at right in variable at left"
• The right side expression is evaluated first,
and then its result is stored in the variable at left.
• What happens here?
int x = 3;
x = x + 2; // no solutions
// mathematically
// not an equation!
x 3
x 5
11. 11
Multiple Variables
• Multiple variables of the same type can be declared and
initialized at the same time.
• Syntax:
type name1, name 2, name3;
int x, y, z; // declare three integers.
type name1 = value1, name2 = value2, name3 = value3;
int a = 1, b = 2, c = 3; // declare and initialize
// three integers.
12. 12
Assignment and types
• A variable can only store a value of its own type.
– int x = 2.5; // ERROR: incompatible types
• An int value can be stored in a double variable.
– The value is converted into the equivalent real number.
– double myGPA = 4; myGPA 4.0
13. 13
Compiler errors
• Order matters.
– int x;
7 = x; // ERROR: should be x = 7;
• A variable can't be used until it is assigned a value.
– int x;
System.out.println(x); // ERROR: x has no value
• You may not declare the same variable twice.
– int x;
int x; // ERROR: x already exists
– int x = 3;
int x = 5; // ERROR: x already exists
• How can this code be fixed?
14. 14
Printing a variable's value
• Use + to print a string and a variable's value on one line.
– double grade = (95.1 + 71.9 + 82.6) / 3.0;
System.out.println("Your grade was " + grade);
int students = 11 + 17 + 4 + 19 + 14;
System.out.println("There are " + students +
" students in the course.");
• Output:
Your grade was 83.2
There are 65 students in the course.
15. 15
Receipt question
Improve the receipt program using variables.
public class Receipt {
public static void main(String[] args) {
// Calculate total owed, assuming 8% tax / 15% tip
System.out.println("Subtotal:");
System.out.println(38 + 40 + 30);
System.out.println("Tax:");
System.out.println((38 + 40 + 30) * .08);
System.out.println("Tip:");
System.out.println((38 + 40 + 30) * .15);
System.out.println("Total:");
System.out.println(38 + 40 + 30 +
(38 + 40 + 30) * .15 +
(38 + 40 + 30) * .08);
}
}
16. 16
Receipt answer
public class Receipt {
public static void main(String[] args) {
// Calculate total owed, assuming 8% tax / 15% tip
int subtotal = 38 + 40 + 30;
double tax = subtotal * .08;
double tip = subtotal * .15;
double total = subtotal + tax + tip;
System.out.println("Subtotal: " + subtotal);
System.out.println("Tax: " + tax);
System.out.println("Tip: " + tip);
System.out.println("Total: " + total);
}
}
17. 17
Type boolean
• boolean: A logical type whose values are true and false.
int age = 22;
boolean minor = (age < 21);
boolean lovesAPCS = true;
System.out.println(minor); // false
System.out.println(lovesAPCS); // true
System.out.println(4 <= 5); // true
18. 18
final
• The keyword final can be used in front of a variable
declaration to make it a constant that cannot be changed.
Constants are traditionally capitalized.
public class TestFinal
{
public static void main(String[] args)
{
final double PI = 3.14;
System.out.println(PI);
PI = 4.2; // This will cause a syntax error
}
}
19. 19
Naming variables
The name of the variable should describe the data it holds. A name
like score helps make your code easier to read.
A name like x is not a good variable name in programming, because it
gives no clues as to what kind of data it holds.
Do not name your variables crazy things like thisIsAReallyLongName,
especially on the AP exam. You want to make your code easy to
understand, not harder.
20. 20
Naming variables
The convention in Java and many programming languages is to always
start a variable name with a lower case letter and then uppercase the first
letter of each additional word.
Variable names can not include spaces so uppercasing the first letter of
each additional word makes it easier to read the name. Uppercasing the
first letter of each additional word is called camel case.
int numOfLives = 3; // camel case to highlight words
Another option is to use underscore symbol _ to separate words, but you
cannot have spaces in a variable name. Java is case sensitive
so playerScore and playerscore are not the same.
int num_of_lives = 3; // use _ to highlight words.
21. 21
Keywords
• keyword: An identifier that you cannot use to name a
variable because it already has a reserved meaning in Java.
abstract default if private this
boolean do implements protected throw
break double import public throws
byte else instanceof return transient
case extends int short try
catch final interface static void
char finally long strictfp volatile
class float native super while
const for new switch
continue goto package synchronized
22. 22
Input and System.in
(not on AP)
• interactive program: Reads input from the console.
– While the program runs, it asks the user to type input.
– The input typed by the user is stored in variables in the code.
– Can be tricky; users are unpredictable and misbehave.
– But interactive programs have more interesting behavior.
• Scanner: An object that can read input from many sources.
– Communicates with System.in (the opposite of System.out)
– Can also read from files, web sites, databases, ...
23. 23
Scanner syntax
(not on AP)
• The Scanner class is found in the java.util package.
import java.util.*; // so you can use Scanner
• Constructing a Scanner object to read console input:
Scanner name = new Scanner(System.in);
– Example:
Scanner console = new Scanner(System.in);
24. 24
Scanner methods
(not on AP)
– Each method waits until the user presses Enter.
– The value typed by the user is returned.
System.out.print("How old are you? "); // prompt
int age = console.nextInt();
System.out.println("You typed " + age);
• prompt: A message telling the user what input to type.
Method Description
nextInt() reads an int from the user and returns it
nextDouble() reads a double from the user
next() reads a one-word String from the user
nextLine() reads a one-line String from the user
25. 25
Scanner example
(not on AP)
import java.util.*; // so that I can use Scanner
public class UserInputExample {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How old are you? ");
int age = console.nextInt();
int years = 65 - age;
System.out.println(years + " years to retirement!");
}
}
• Console (user input underlined):
How old are you?
36 years until retirement!
29
age 29
years 36
26. 26
Input tokens
(not on AP)
• token: A unit of user input, as read by the Scanner.
– Tokens are separated by whitespace (spaces, tabs, new lines).
– How many tokens appear on the following line of input?
23 John Smith 42.0 "Hello world" $2.50 " 19"
• When a token is not the type you ask for, it crashes.
System.out.print("What is your age? ");
int age = console.nextInt();
Output:
What is your age? Timmy
java.util.InputMismatchException
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
...
27. 27
Scanner example 2
(not on AP)
import java.util.*; // so that I can use Scanner
public class ScannerMultiply {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please type two numbers: ");
int num1 = console.nextInt();
int num2 = console.nextInt();
int product = num1 * num2;
System.out.println("The product is " + product);
}
}
• Valid Outputs (user input underlined):
Please type two numbers: 8
6
The product is 48
// 2 tokens separated by new
// line
Please type two numbers: 8 6
The product is 48
// 2 tokens separated by space
28. 28
Lab 1: String Concatenation
Create a new repl on replit.
Create two integer variables: pens and pencils. Initialize it to
some positive values. Use print statements and String
concatenation to have the following output:
Output: (Assuming that the initialized values for pens=18,
pencils = 10)
There are 18 pens.
There are 10 pencils.
Total is 28 pens and pencils.
29. 29
Lab 2: String Concatenation
Use the SAME repl as from Lab 1 String Concatenation.
Modify your previous lab 1 to ask the user to enter the
number pens and pencils rather than hard coding the values.
Use print statements and String concatenation to have the
following output:
Output:
Enter the number of pens: 10
Enter the number of pencils: 18
Total is 28 pens and pencils.
30. 30
References
For more tutorials/lecture notes in Java, Python, game
programming, artificial intelligence with neural networks:
https://longbaonguyen.github.io
1) Building Java Programs: A Back to Basics Approach by Stuart Reges and
Marty Stepp
2) Runestone CSAwesome Curriculum:
https://runestone.academy/runestone/books/published/csawesome/index.html
Editor's Notes
#2: a variable is also like the MS / MR buttons on a calculator
variables must be declared before they are used, just like methods
#3: a variable is also like the MS / MR buttons on a calculator
variables must be declared before they are used, just like methods
#5: a variable is also like the MS / MR buttons on a calculator
variables must be declared before they are used, just like methods
#10: x = x + 2; increases the value stored in variable x by two.
#25: It's also useful to write a program that prompts for multiple values, both on the same line or each on its own line.
#27: It's also useful to write a program that prompts for multiple values, both on the same line or each on its own line.