0% found this document useful (0 votes)
78 views36 pages

w01 Intro Curs

This document provides an introduction to Java development. It discusses how to break down problems into manageable parts through continued splitting using specifications, user stories, features, and tasks. It also provides an example of breaking down a problem to solve invoices. The document then discusses how programs are created using source code, compilers, bytecode, and libraries. It outlines the tools that will be used, including the JDK, an IDE like IntelliJ, and optionally a version control system like Git. Finally, it begins introducing concepts in Java like variables, methods, classes, and primitive types.

Uploaded by

Cosmin Grosu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views36 pages

w01 Intro Curs

This document provides an introduction to Java development. It discusses how to break down problems into manageable parts through continued splitting using specifications, user stories, features, and tasks. It also provides an example of breaking down a problem to solve invoices. The document then discusses how programs are created using source code, compilers, bytecode, and libraries. It outlines the tools that will be used, including the JDK, an IDE like IntelliJ, and optionally a version control system like Git. Finally, it begins introducing concepts in Java like variables, methods, classes, and primitive types.

Uploaded by

Cosmin Grosu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

JAVA Development

Introduction module
Introduction

Your expectations
Introduction

Our expectations
• ask questions
• really, ask anything
• work on exercises
How development works?

I have a big problem, how do I start to program?

● Problem gets expressed as ...


● Specifications get broken down into ...
● User stories are split into …
● Features are split into ...
● Tasks are made up of ...
● Small changes to the code

Key takeaway:
Continue breaking down the problem until you have manageable parts!
How development works?

Example:

● Problem: I need to monitor my finances


● Sub-problems: I need to monitor my accounts, my loans, my spending, my invoices
● Story: I should be able to view my invoices ordered by amount and filterable by company
● Feature: Create a page listing invoices
● Tasks: Read invoices from the database, Display them on a page, Support filtering the list of invoices

Key takeaway:
Continue splitting the problem until you have manageable parts.

This applies to all problems regardless of size!


How development works?
Problem solving – Example 2

Problem: solve quadratic equation

1. Start with the general solution formula:

2. See what the formula for the discriminant is:

3. Compute delta
4. Check if the equation has real solutions
5. Compute the first solution
6. Print the first solution
7. Check if there is a second solution
8. If yes, print the 2nd solution
How development works?
Problem solving

This sequence of steps that need to be taken to solve a problem is called an..

Algorithm!
Practice

Break down the following problems

1. Convert from base 10 to base 2


2. Convert from base 2 to base 10
3. Find the smallest number in a list
4. Compute the sum of the odd numbers in a list (what if the list is ordered?)
Let’s setup the tools!
How are programs created?

• Source code: human readable text, respecting programming language’s syntax, stored in
text files (.java), describes application’s logic

• Compiler (javac): validates and translates source code to compiled code (‘bytecode’)

• Bytecode: stored in binary files (aka “not text”; like .class/.jar), can be executed by a Java
Virtual Machine (JVM), multi-platform (runs on: Windows/MacOS/Linux..)

• Libraries: prepackaged functionality


■ standard libraries (come with Java platform)
■ other/external libraries
Tools we’ll be using

● The JDK (Java Development Kit; not the JRE!)


○ Oracle JDK 8 (or OpenJDK on Linux)

● An IDE (Integrated Development Environment)


○ IntelliJ Idea (Community Edition)

● Version Control System (optional)


○ Git and SourceTree (or TortoiseGit)
Introduction to Java
So what is Java?

A software environment specifically designed to develop various types of


applications.

● JRE?
● JDK??
● JVM???
● ...bytecode?

What are all these?


Hello World

Simplest Java program:

class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!") ;
}
}

Gotchas:
● Don’t forget the semicolon at the end of the 3rd line
● Make sure that the file is called HelloWorld.java (same name as class + .java extension)
General structure of Java code

The code of a Java program is organized on multiple levels:


- The code is stored in one or more .java files
- Each .java file contains at least one class (may contain more) -> OOP language
- Each class contains one or more methods (and/or fields..)
- the method with predefined name “main” has a special role (starting point)
- Each method may contain one or more blocks of code
- Each block of code consists of a sequence of statements
- Statements may contain expressions
- Expressions are composed of variables/literals + operators

Java files may contain a few other kinds of code (like comments, annotations..).
Hello World - code structure

HelloWorld program: it consists of just one file (HelloWorld.java), containing one class:

class HelloWorld { //begin class..

public static void main(String[] args) { //begin method..

String name = "John"; //1st statement (declare and initialize a variable)


System.out.println("Hello " + name + "!"); //2nd stmt (method call + an expression)

} //..end method

} //..end class
Variables

A variable is a name that can be assigned to values of a specified type.


(Java is a strongly typed language, unlike Python, JavaScript. Is this better? Where does this matter?...)

Declaration: Examples:
<type> variableName; String myName;
int myAge;
Assignment:
variableName = <value>; myName = "Andrei";
myAge = 20;
myAge = myAge + 1; //reassignment
Declaration combined with assignment:
double pi = 3.14;
<type> variableName = <value>;
int answer = 42;
Variables - declaration vs assignment

Rules:
- declaration: a variable can be declared only once; the name of a variable
must be unique (in its scope)
- assignment:
- regular variables can be re-assigned multiple times
- constants: variables declared as ‘final’ can be assigned only once
Examples:
int a; //declared, not initialized final int c; //declared final, not initialized
int b=1; //declared and initialized c = 1; //can be assigned (once!)
final int d = 1; //declared and initialized
int a; //-> error: 'a' already declared
a = 1; //can be reassigned.. c = 2; //-> error: cannot reassign final var 'c'
a = b+1; //..multiple times d = 2; //-> error: cannot reassign final var 'd'
Variables - scope

● Blocks of code are groups of statements, surrounded by “{“ and “}”


○ In our example, there is a single block of code (the main method’s body)

● Every single variable that we declare has a scope


○ The scope is the visibility domain of the variable (who has access to it)
○ Important: A variable defined in a code block is visible only in that block!

● For now, we’ll focus on the local scope (we’ll see later that there is also a
global scope)

Let’s look at an example!


Variables - scope

public static void main(String[] args){


int a = 1;
{
int b = 2;
}
System.out.println(a);
System.out.println(b);
}

Can you tell what’s wrong with this piece of code?


Variables - scope

public static void main(String[] args){ There are two blocks of code here: the
int a = 1; method body and the small nested block
{
int b = 2; - Variable “a” is defined within the
} method body, so it’s visible
System.out.println(a); throughout the whole method body
System.out.println(b); //error! - Variable “b”, on the other hand, is
} visible only in its small block

Therefore the code will not compile and


will not work.

How can we make it work?...


Naming things

Naming things - one of the most important abilities of a programmer!


- Need: you’ll need to decide on custom names for: variables, methods, classes (+packages)
- General rules for Java names (‘identifiers’):
- can be composed of: letters, digits and these 2 characters: ‘_’ , ‘$’; but cannot start with a digit
- are case sensitive ( “Name” is different from “name”)
- cannot be one of the Java keywords (reserved terms, like: final, static, if, while…)
- Naming conventions:
- case: class names should start with uppercase; variables/methods should start with lowercase; constants
should be all uppercase
- names composed of multiple words - should use ‘camel case’: the starting letter of each word, except first
one, should be uppercased; examples: myVariable, someOtherNameHere
- for constants, use ‘snake case’: SOME_CONSTANT_HERE
- Recommendations:
- avoid using ‘_’ and ‘$’ (even if permitted by syntax)
- avoid generic names, choose names which are descriptive but not too short/long (IDE autocompletion helps!)
- you can use shorter names for variables used in smaller scopes
Naming things - examples

public class SomeClassName { //class names should start with uppercase


public static void main(String[] args) {
//constants should be all uppercase (separate words with ‘_’)
double SOME_CONSTANT = 3.14;

//variables should start with lowercase (use camel case for multiple words)
int someVariable;
String anotherVariable = "text";
boolean isEnabled = true; //usual for boolean vars to start with ‘is…’

//avoid unusual chars (_ $) or names looking like common class names


int _avoid_names_like_this;
int $or_like_this$;
String String; //valid, but don't!..
}

//method names should start with lowercase (and use camel case); same for their parameters
static void someMethodName(int paramName1, int paramName2) { … }
}
Types - Primitives

Type Description
byte on 8-bit, -128 (-2^7) to 127 (inclusive, 2^7 - 1); example: byte a = 100, byte b = -50

short on 16-bit, -32,768 (-2^15) to 32767 (inclusive, 2^15 -1); example: short s = 10000, short r = -20000

int on 32-bit, - 2,147,483,648 (-2^31) to 2,147,483,647(inclusive) (2^31 -1); example: int a = 100000, int b = -200000

long on 64-bit, -9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807 (inclusive)(2^63 -1);


example: long a = 100000L, long b = -200000L

float single-precision 32-bit IEEE 754 floating point; should not be used for precise values such as currency
example: float f1 = 234.5f

double double-precision 64-bit IEEE 754 floating point; should not be used for precise values such as currency
example: double d1 = 123.4

boolean one bit, can hold only 2 values (true/false); example: boolean b = true

char 16-bit Unicode character; char data type is used to store any character; example: char letterA = 'A'

Questions: - why multiple types for similar data? (short vs int vs long - why not use long all the time?)
- what happens when reaching the range limits?
Types - Non-primitives

References
● created using the constructor of the classes (using 'new’);
● default value is null
● example: Employee emp = new Employee("Razvan");

Strings
● Holds fragments of text
● Made up of several char values
● String is also a reference type, not a primitive! (doesn’t need ‘new’ to build, but can be null !)
● example: "Hello World", "two\nlines"

Literals
● fixed values that appear directly in the source code: 100, 2.5, 33.8d, true, ‘A’
● byte, int, long, short can be expressed in decimal (base 10), hexadecimal (base 16) and octal:
int decimal = 100; int hexa = 0x64;
Operators

Operators: special symbols that perform specific operations on one, two or three operands
and then return a result.

• Arithmetic operators: + , - , / , * , % , ++ , --

• Relational operators: == (equal to), != (not equal to), > (greater than), < (less than),
>= (greater than or equal to), <= (less than or equal to)

• Logical operators: && (logical and), || (logical or), ! (logical not)

• Bitwise operators: & (bitwise and), | (bitwise or), ^ (bitwise XOR), ~ (bitwise complement),
<< (left shift), >> (right shift)

• Conditional operator: ( ? : )
- - ternary operator, usage: (<condition>) ? <value for true> : <value for false>

• Assignment operators: = , += , -= , *= , /= , %= , <<= , >>= , &= , ^= , |=


Operators - logical

Bitwise and logical operators:

This is a table with the value representations for the bitwise operations of OR, AND, XOR
and the logical operation NOT.
Operators - short-circuit

The logical operators ‘&&’ and ‘||’ behave similarly to their bitwise counterparts (‘&’ and ‘|’),
with a CRITICAL distinction: they can be short-circuited.

Short-circuiting means that at evaluation time, based on the previous values table, expression
composed of multiple operators will be evaluated only until necessary:
● && (logical AND): expression is evaluated until it encounters the first FALSE operand (as in this case
the end result will for sure be FALSE, no matter the rest of expression), or until its end
● || (logical OR): expression is evaluated until it encounters the first TRUE (as in this case the end
result will for sure be TRUE, no matter the rest of expression), or until its end

Example:
(a > 0) && (false) && (b ==2) && (c<0) //=> evaluation stops at 2nd term, end result is: false
true || (a>0) || (b==2) //=> evaluation stops at 1st term, end result is: true
Expressions

Expression - a construct made of variables/literals + operators (and possibly method calls),


which evaluate to a single value.
The type of the returned value depends on the values used in the expression.
Examples: 2 + 3 //=> returns an int value (5)
2.0 + 3 * 5 //=> returns a double value (17.0)
(a > b) ? a : b //=> return a value of same type as a,b
computeSum(2, 3) //=> type or returned value depends on method definition

An expression may be composed of multiple operators (as long as the types of operands match). In this
case it’s evaluated by applying the operators in a specific order, given by their precedence (priority) - see:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html
- Tip: when you are unsure about the evaluation order, or want to change the default one, you can use
parentheses ‘(‘ and ‘)’ to force a specific order:
a + b / 100 //evaluates ‘b/100’ first, then +
(a + b) / 100 //evaluates ‘a+b’ first, then /
Statements

A statement is the basic executable unit of code (can be used to build a full program).
- It is similar to a full phrase in natural language (it should say/mean something, do an action..)
- Need to be terminated with a “;”. Usually written one per line, but multiple per line are allowed.
- Multiple types:
- expression statements: some types of expressions (assignments, method calls..) with an “;” after
- declaration statements: declarations of a variables
- control flow statements - detailed in a later lesson

Note: a block of executable Java code expects a list of full statements, not just expressions!

Examples of valid statements: Invalid statements:


double aValue; //declaration statement double aValue //missing ‘;’
aValue = 123.45; //assignment statement “some text”; //just a literal value, meaning?
aValue++; //increment statement 2 + 5; //just an expression, what to
someMethod(1, 2); //method call // do with the returned value?
Methods

A method is a named block of code (containing multiple statements)


- definition: must specify its signature - the name, if it requires any input parameters
(and of what types), and the type of the result it produces (including case of no result);
- usage: once defined, it may be called by any other code having access to it, and after
passing some values for the expected parameters, it will run and produce the
corresponding results (and/or side-effects)

Advantages:
- easy to reuse the code (run it multiple times, with different params..)
- DRY principle (Don’t Repeat Yourself)
- allows problem decomposition (split complex operations to simpler steps, give them
human-friendly names)
Methods - definition

The basic syntax for defining a method is:


modifier returnType methodName (argumentList) //signature
{
//method body
}
● modifier - controls who can access/use this method, explained later (use ‘public static’ for now)
● argumentList - a list of zero or more parameters (type and name), separated by “,”
● returnType - the type of result returned by this method, may be:
○ an actual Java type (of any kind)
○ void - meaning the method does not return any result (it’s called only for its side-effects)
● method body: a block of statements (surrounded by braces: { } ); if the returnType is not ‘void’,
the body must finish with a “return” statement, returning a value of the expected type.
Methods - examples

Method returning void (no value): Method returning some value:

public static void add (int a, int b) { public static int add (int a, int b) {
int sum = a + b; return (a + b);
System.out.println(sum) ; }
}
public static void writeSum(int a, int b) {
int sum = add(a, b);
System.out.println(sum) ;
}
Methods - full example

import java.util.Scanner; //needed for using Scanner later

public class HelloPerson {

/*main method = the starting point for execution*/


public static void main(String[] args) {
String name = readName(); //calling a method (to read data from console)
sayHi(name); //calling another method, with a param (to print a greeting)
}

static String readName() {


System.out.print("Enter your name: ");
Scanner in = new Scanner(System.in); //need this first, to read from input
return in.next();
}

static void sayHi(String name) {


System.out.println("Hello, " + name + "!");
}
}
Questions?
Resources

Some useful resources:

Tutorials:
- Java tutorial: http://tutorials.jenkov.com/java/index.html
- Oracle docs: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/index.html

Online exercises:
- Coding bat: https://codingbat.com/java
- Codewars: https://www.codewars.com/?language=java

You might also like