Kihagyás

First things to do

  1. install Java JDK on your own computer.
  2. Install the development environment on your own computer. Anyone can use anything at home, but the Cabinet does not have all the development environments in existence, so it is a good idea to use one at home that is also available in the Cabinet. We recommend IntelliJ IDEA.
  3. Bíró registration (on both Bírós)

Attention!

Checking access to the Bíró, solving problems if necessary. For those who have not done so before, please register to Bíró on [this][biro_regist] and [this][biro_regist2] link. On both! If anyone is unsure if they have already registered, they should register again. Registration for the Bíró was not required to complete the Programming Fundamentals Practical Course!

Common [problems and their solutions] related to Java usage and installation in English. If someone has a problem other than these, please contact your demonstrator by e-mail or post the problem in the course forum of the consolidated scene.

About compiled languages

Compiled programming languages are languages where the source code is first converted into machine code by a compiler, and then we can run the converted, compiled code. The compilation process consists of several steps, which are outlined schematically: first, the compiler checks the syntactic correctness of the code, then it compiles it into machine code, and finally it creates an executable file. The result of the compilation is usually a self-executing program containing instructions that can be directly interpreted by the architecture. In general, compiled binary machine code applications contain both hardware-dependent and operating system-dependent instructions.

The advantage of compiled languages is that programs generally run faster because the code does not need to be interpreted at runtime. Another advantage is the type checking that is done at compile time, which helps to detect errors early. On the other hand, they have the disadvantage that the program has to be compiled separately for each platform to be supported, and the development cycle can be longer due to the compile time. Classic examples of compiled languages are C, C++, Rust and Go. Java is a special case: although it is a compiled language, the compiler does not directly produce machine code, but platform-independent bytecode, which is then run by the Java Virtual Machine (JVM). This ensures the "Write Once, Run Anywhere" principle (with which the Java language was advertised at its inception), while retaining many of the advantages of compiled languages.

What does this look like in practice?

In Python, you could just run the application with python fajl.py, but in Java, you need to compile your source files before running the program. Of course, in a smarter IDE this process can be automated, but if you compile the program yourself, you have to be careful, as it can be a source of errors.

Briefly about Java

![How Java works]gyak1_execution.

source of image, where you can read more about how the Java virtual machine works.

Java ecosystem

In order to run and develop Java programs, you will need a compile and run environment and a compiler. To run our finished program, all we need is the JRE (Java Runtime Environment), which provides the minimum requirements for running Java applications, such as the JVM (Java Virtual Machine). We will also need the JDK (Java Development Kit) for development. This includes the programming tools needed to run Java applications, as well as to build and compile them (so you don't need to download the JRE separately, it is included in the JDK).

The most recent Java distributions currently available no longer offer separate downloadable JRE and JDK packages, these can only be downloaded together. More information on how to get and install Java is available [here][installation].

Our first Java language program

The related Oracle site.

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

As you can see, the situation here is a bit more complicated than it was with Python. Below we look at the main differences:

Types

On the one hand, in Java, types already appear, and we will need to use them everywhere. You cannot create a variable without specifying an explicit type. You can read about types below.

Syntax differences

In Python, we did not have an explicit block syntax, the indentation was used to indicate which code fragment belonged to which block. In Java, on the other hand, we use traditional block syntax in the form of hyphens. Everything between a { and } is in the same block.

It may seem strange that in Java, it is obligatory to use semicolons at the end of statements. It is required after every executable statement, value assignment, method call or declaration. The absence of a semicolon results in a compilation error. However, you do not need to put a semicolon after blocks ({ }), class and method declarations, and control structure headers (e.g. if, for, while). The semicolon allows multiple statements to be written on a single line, although this is rarely used in practice because it impairs the readability of the code, so it is best to avoid. In Java, you can't write functions "just like that", you have to put everything into a class (what this is, why it's good, will be explained in detail later).

Entry point

In many programming languages (including Java), executable programs must have an entry point, usually called main function. This is a special method with the exact header (signature) public static void main(String[] args) (you might also see String..., but it means the same thing). All executable Java programs must include this function, because the JVM (Java Virtual Machine) looks for it and calls it first when the program starts. If we don't make an entry point, our program will not work, we will get an error when we want to run it.

Think of Python

Python does not require a separate entry point definition, it simply executes the code "line by line" (top to bottom). In Python, you will often see the if __name__ == "__main__": structure, which serves a similar purpose to main functions, but is optional. Using this structure allows the same file to be imported as a module and run directly.

Details about the main method:

  • public: the method is externally accessible, this is necessary for the JVM to find the method.
  • static: can be run without instantiating the class, this is necessary for the JVM to find the method.
  • void: the method does not return a value (no return type is required in Python), but in Java a return type is required. If the method does not return anything, this will be void.
  • main: the method name must be "main"
  • String[] args: array of command line arguments (in Python sys.argv)

Compile, run

Save the completed file as HelloWorld.java. It is important to always save the file with the name of your public class (which is after public class). In this case, you can give the class (and the file) any name you like, just make sure you save it with the same name.

Translation

Now all that's left is the compilation itself, and then running the program. The completed programs can be compiled from the command line using the javac command (which is the binary of the installed Java compiler), javac FileName.java, in this case javac HelloWorld.java. (You can read more about the Java compiler and its switches on this page.) Normally, after issuing the command, there is no response at all, we just get the cursor back after a while.

Translation

After the compilation is finished, you should see a file called HelloWorld.java and a file called HelloWorld.class, which was created after the compilation. This file contains the completed Java bytecode, which we can then carry around and run on any machine that has a Java virtual machine (i.e. the target machine has the JDK installed).

Run

The completed application is run using the java command, which is used as follows: java ClassName arg1 arg2 arg3 ... argN, in this case java HelloWorld. It is important that .class extension is not allowed after HelloWorld. The command causes the JRE to look for the specified class on the file system, and once loaded, to start executing the main method contained in it. If it cannot find the file, or if it does not contain main, it will exit with an error.

Comment

You can look into the .class extension file after compilation with the javap command in the JDK, or even decompile them, so you will have to pay attention to this here later (especially if you want to sell your program for money). You can use different obfuscation methods here, but this is not material for this course.

Normally, after running the program, the text "Hello World!" is displayed on the console.

Default outputs

As we have seen, in Java you can print text to the screen using System.out.println(). However, this does not necessarily always mean the terminal. System.out is the default output, which in our case was directed to the terminal. This can of course be changed to write to another location, such as a file.

There are several functions available to write it out:

System.out.print("This is a text");
System.out.println("This is a text!");
System.out.printf("This %d is a formatted expression that might be familiar from Python\n", 1);
System.out.format("This %d is a formatted expression that might be familiar from Python\n", 1);

Output

This is a textThis is a text!

This 1 is a formatted expression that might be familiar from Python

This 1 is a formatted expression that might be familiar from Python

The difference between System.out.print and System.out.println is that the former does not add a line break at the end of the printout, while the println version does. The linebreaking character is always the linebreaking character of the platform, never a burned-in character, so it is recommended to use it for most printouts containing linebreaking.

The bottom two are the Java equivalents of the formatted expression familiar from Python.

The use of the burned-in \n, \r\n characters should be avoided if possible, as this may compromise platform independence. The simplest way to print an empty line break is to use System.out.println();. If you want to use a line break within a printout at all costs, you can use System.lineSeparator() to request a platform-specific line break character instead of a line break character.

System.out.printf("This is %d a printout" + System.lineSeparator(), 1);

Similar to the printout we have learned so far, the default error output is also familiar. In Java, this is System.err, which can be printed out in the way we have already seen. This is used to report error messages. It is used in exactly the same way as System.out, the only obvious difference being that the text written to System.err is displayed in red in the internal console of the development environment.

When using the simple terminal, this default output and error output are the same, so both outputs are seen in the console. However, the two outputs can be directed to two different locations.

The operation of the two outputs relative to each other is asynchronous. This means that it does not necessarily print things out exactly when we tell it to: if the default output is not able to do its job, the data to be printed out is waiting; while the default error output may be free, so that at the code line level, even if we print to the default output first and then to the error output, what we print to the error output may appear on the console first. So the following code has two possible outputs:

System.out.println("Now an error message will follow:");
System.err.println("This is the error message.");

One of the outputs:

Output

Now an error message will follow:

This is the error message.

The other is:

Output

This is the error message.

Now an error message will follow:

It follows that the error output should NOT be used to simply color the text, because it may confuse what you are saying. Of course, there is no need to worry about the two messages sent to System.out getting mixed up, they are waiting in order.

To work faster, IntelliJ IDEA and Eclipse also make it easy to write to the output.

  • IntelliJ IDEA: To get the default output, you can simply type sout and then use Ctrl+Space to add System.out.println() and serr to System.err.println().
  • Eclipse: To get the default output, simply type sysout and then Ctrl+Space to System.out.println() and syserr to System.err.println().

Types

Although most of the types in this material should be familiar from Basics of Programming, they are also introduced here, from a Java perspective.

Strongly typed programming languages

In strongly typed languages, all variables have a strictly defined data type, which must be explicitly declared (i.e. must be specified) before use. For example, in Java:

int number = 5;
String text = "Hello";

In these languages, it is typically not possible to mix values of different types or convert them implicitly. Type conversion must always be done explicitly. The compiler checks for type errors at compile time. Bad example:

int number = "10"; // Will not work
String text = 5; // Will not work

A little Python flashback

Python is a dynamically typed language, which means that:

  • You don't have to declare the type of variables in advance.
  • The type of a variable can change at runtime.
  • Python handles type conversions automatically.

`python number = 5 # will be int print(type(number)) # int number = "text" # may later become a string print(type(number)) # str

Some basic types in Java

Simple (primitive) data types: boolean, char, byte, short, int, long, float, double. Some of these types may be familiar from Python, but there are also some types that are yet unknown.

Integer types

Type for storing signed integers. Similar to Python's int type, but with the important difference that while in Python you can store practically any integer, in strongly typed languages (such as Java) int is usually 32 bits (4 bytes), which means that it can store values between -2^31 and (2^31-1) (between -2,147,483,648 and 2,147,483,647).

There are several integer value storing types in Java. If you want to store a larger integer than the one above, you can use the long (64 bits, 8 bytes) type, and for smaller integers you can use the short (16 bits, 2 bytes) or byte (8 bits, 1 byte) data type. It is also possible to store larger numbers, but this is not the subject of this course.

public class IntExample {
    public static void main(String[] args) {
        // Basic value assignment
        byte b1 = 127;
        byte b2 = -128;

        // Hexadecimal form
        short s1 = 0xFF; // 255 decimal

        // Binary format
        int i1 = 0b1010; // 10 decimal

        // Traditional only
        int number = 2354;

        // Large number, use underscore for readability
        int i2 = 1_000_000;

        // For long type, L or l "required" at the end
        long l1 = 12345678910L;
        // int l3 = 12345678910; // would be too large int

        long l2 = 0xFFFFL; // in hexadecimal form

        // Print out values
        System.out.println("byte values: " + b1 + ", " + b2);
        System.out.println("short value from hex: " + s1);
        System.out.println("int value from binary: " + i1);
        System.out.println("int value traditional: " + sam);
        System.out.println("int value from underscore: " + i2);
        System.out.println("long values: " + l1 + ", " + l2);
    }
}

Increment and decrement

Many languages, including Java, provide special operators to increment and decrement numbers by 1. The ++ operator increments by one and the -- operator decrements by one. These operators can be used in both prefix (operator before the variable) and postfix (operator after the variable) modes. The prefix version (++i) first increments the value and then returns it, while the postfix version (i++) first returns the original value and then increments it.

public class IncrementExample {
    public static void main(String[] args) {
        int a = 5;

        // Postfix increment - first the value of a is printed out (5), then it is increment
        System.out.println("a++ : " + a++); // 5
        System.out.println("value of a now: " + a); // 6

        // Prefix increment - first increments the value of a, then prints it out
        System.out.println("++a : " + + ++a); // 7

        // Decrement works similarly
        System.out.println("a-- : " + a--); // 7
        System.out.println("--a : " + --a); // 5

        // The same can be achieved this way:
        a += 1; // increment
        a -= 1; // decrease
    }
}

Floating point number types

Floating-point numbers allow you to store decimal fractions in your program. The name comes from the fact that the decimal point (".") can "float", i.e. its position can be changed during the internal representation of the number. Java offers two types of these numbers: the 4-byte (32-bit) float and the 8-byte (64-bit) double.

Floating-point numbers are stored according to the IEEE 754 standard, which divides the storage of the number into three parts: sign, mantissa and exponent. This storage method allows for the storage of very large and very small numbers, however it is important to note that floating point numbers are not always exact, some numbers cannot be represented exactly in binary floating point form. For this reason, they are generally avoided in the financial sector, and fixed point or special financial types (e.g. BigDecimal) are used instead. The double type is the more commonly used choice, as it provides higher precision than float.

public class FloatingPointExample {
    public static void main(String[] args) {
        // Basic value assignment
        float f1 = 3.14f; // use of f or F is mandatory
        float f2 = -45.67F;

        // Use of underscore
        float f3 = 3.141_592f;

        // Scientific notation is also allowed
        double d1 = 1.23e2; // 123.0
        double d2 = 1.23e-2; // 0.0123

        // Conventional value assignment
        double d3 = 3.1415;
        double d4 = 0.333d;
        double d5 = 0.333D;

        // Use of underscore
        double d6 = 1_234.567_89;

        // Print out values
        System.out.println("float values: " + f1 + ", " + f2);
        System.out.println("double values in scientific notation: " + d1 + ", " + d2);
        System.out.println("use underscore: " + f3 + ", " + d3);
        System.out.println("traditional printout: " + d4 + ", " + d5);
    }
}

Text

In Java, text is stored using the type String. Its purpose is exactly the same as the str type in Python, to store and manipulate text (strings). An important difference is that there is no multi-line text with three quotes, and you cannot use the % operator for formatted text. In addition, of course, you have to use text in a slightly different way than in Python, but much of the functionality is also available in Java.

Strings can be specified only between double quotes (e.g. String text = "Hello World";), a very important difference from Python.

It is of type immutable, meaning that once you create a text (String object) you cannot change its contents later. Every text operation actually creates a new text, this is very similar to Python.

Storing texts in memory

JVM (Java Virtual Machine) stores text literals in a special memory area called String Pool for reusability.

Strings contain a number of useful methods to make them easy to manage:

  • contains: returns whether the text passed as a parameter is contained in the text for which it is called.
  • endsWith: returns whether the text passed as a parameter ends with the text called.
  • equals(): compare strings
  • indexOf: returns the index at which the text passed as parameter starts in the text for which it is called. Returns -1 if the parameter is not found in the text.
  • isEmpty: returns whether the text is empty.
  • length: this method returns the length of the text.
  • replace(): replaces characters or substrings
  • substring(): cut a text string
  • startsWith: returns whether the text passed as a parameter starts with the text that was called.
  • toLowerCase: return the lowercase version of the text.
  • toUpperCase: returns the uppercase version of the text.

You can use the + operator to concatenate strings.

public class StringExample {
    public static void main(String[] args) {
        // Create string
        String text = "Hello World";

        // Basic operations
        System.out.println("Original text: " + text);
        System.out.println("Length: " + text.length());
        System.out.println("Uppercase: " + text.toUpperCase());
        System.out.println("Lowercase: " + text.toLowerCase());

        // Substring operations
        System.out.println("First 5 characters: " + substring.substring(0, 5));
        System.out.println("'World' starting position: " + text.indexOf("World"));

        // String comparison
        String differentText = "Hello World";
        System.out.println("Equal? " + text.equals(differentText));

        // Replace
        System.out.println("Replace World with Java: " + text.replace("World", "Java"));
        // Immutable type
        System.out.println("Immutable: " + text);

        // String concatenation
        String firstName = "Kovács";
        String lastName = "Firstname";
        String fullName = firstName + " " + lastName;
        System.out.println("concatenated name: " + fullName);
    }
}

Efficient concatenation

For large amounts of concatenation, it is recommended to use StringBuilder or StringBuffer for better performance.

You can specify only one character between single quotes, which will take you to a new data type, the character.

Character

The char type stores a single Unicode character in 16 bits. An important difference to String is that characters are specified between apostrophes (single quotes, '), not double quotes ("). The character type can store plain characters, numbers (as characters), and special characters with escape sequences (for example \u0041).

public class CharExample {
    public static void main(String[] args) {
        // Basic characters
        char letter = 'a';
        char number = '5';

        // Special characters
        char newline = '\n';
        char tabulator = '\t';

        // Unicode characters
        char unicode = '\u0041'; // Letter 'A

        // Print
        System.out.println("Character: " + letter);
        System.out.println("Digit: " + number);
        System.out.println("Unicode character: " + unicode);

        // Char operations
        letter = 'a' + 1;
        System.out.println("Next character: " + letter); // 'b'
    }
}

Boolean

The type boolean is used to store logical values, it can only take two values: true or false. It is important to note that in Java, these are written in lower case (as opposed to Python's True/False).

public class BooleanCharExample {
    public static void main(String[] args) {
        // Boolean values
        boolean true = true;
        boolean false = false;

        // Logical operations
        boolean and = true && false; // and operation
        boolean or = true || false; // or operation
        boolean no = !true; // negation

        // Comparisons
        int x = 5;
        boolean greater = x > 3;
        boolean equals = x == 5;

        // Printout
        System.out.println("True value: " + true);
        System.out.println("And operation: " + and);
        System.out.println("Or operation: " + or);
        System.out.println("Negate: " + no);
        System.out.println("Compare: " + greater);
    }
}

Logical operations in Java

Logical operations in Java are more strict than in Python. While in Python any value can be evaluated to a logical value (e.g. an empty list becomes False, 0 also becomes False), in Java only values of type boolean can be used in logical operations. Java's logical operators (&&, ||, !) work only with boolean operands and always return boolean values. So, if you want to decide whether a variable has a value of zero, if (variable){} is not the right code, you have to convert it to a logical expression: if (variable !=0){}.

Operation Python Java Note
And and && Java: boolean values only
Or or \|\|| Java: boolean values only
No not ! Java: boolean values only
"Truthy" evaluation if list: Does not exist Java: explicit comparison required, e.g. if (list.length > 0)
Numbers if number: Does not exist Java: explicit comparison required, e.g. if (number != 0)
Strings if text: Does not exist Java: explicit comparison required, e.g. if (!text.isEmpty())
Null values if obj is not None: Does not exist Java: explicit comparison required, e.g. if (obj != null)

So in Java, you must always use explicit logical expressions, you cannot rely on a value evaluating to true or false.

Differences in control structures

Conditional control

if (number > 0) {
    System.out.println("positive");
} else if (number < 0) {
    System.out.println("negative");
} else {
    System.out.println("zero");
}
if number > 0:
    print("positive")
if number < 0:
    print("negative")
else:
    print("zero")

In Java, you have to use parentheses and block notation, but other than that, if is quite similar, you have to use else if instead of elif.

Cycles

For

Python's for loop works on directly iterable objects basically, such as a list or text.

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}
for i in range(5):
    print(i)

In contrast, in Java we have a "traditional" for loop, which implements an arithmetic iteration control. This consists of three parts:

  • Initialization: at the start of the loop, it runs once. The variables used in the loop are created here.
  • Condition: checked again and again each iteration. If true, the loop continues; if false, the loop stops running.
  • Step: the loop variable is stepped here in general.
public class ForExample {
    public static void main(String[] args) {
        // Basic for loop
        for (int i = 0; i < 5; i++) {
            System.out.println("Number: " + i);
        }

        // Multi-step
        for (int i = 0; i < 10; i += 2) {
            System.out.println("Even number: " + i);
        }

        // Counting backwards
        for (int i = 5; i > 0; i--) {
            System.out.println("Countdown: " + i);
        }
    }
}

Of course, any part can be omitted, in which case an empty statement is substituted for that part.

public class ForEmptyExample {
    public static void main(String[] args) {
        int i = 0; // Loop variable declared outside

        // Empty initialization (i already exists)
        for (; i < 5; i++) {
            System.out.println(i);
        }

        // Empty stepping part (stepping inside the loop)
        for (int j = 0; j < 5;) {
            System.out.println(j);
            j++; // Step here
        }

        // Empty condition (infinite loop, set with breaks)
        for (int k = 0; ; k++) {
            System.out.println(k);
            if (k >= 5) {
                break; // Exit the loop
            }
        }

        // All parts empty (infinite loop)
        int counter = 0;
        for (;;) {
            System.out.println("Infinite loop: " + counter);
            counter++;
            if (counter >= 5) {
                break;
            }
        }
    }
}

While

While loop is similar, but in Java you need brackets:

while (x < 5) {
    x++;
}
while x < 5:
    x += 1

In contrast, do-while is a structure that first executes the loop body and only then checks the condition. Because of this, you're guaranteed to run the body at least once, regardless of the condition (look for the semicolon at the end of the while).

Syntax:

do {
    // loop body
} while (condition); // semicolon is important!

A concrete example:

public class DoWhileExample {
    public static void main(String[] args) {
        int number = 5;

        // The loop runs once anyway
        do {
            System.out.println("Value of number: " + number);
            number--;
        } while (number > 0);
    }
}
Property While Do-while
Check condition Beginning of cycle End of cycle
Minimum number of runs 0 1
Syntax while (condition) { } do { } while (condition);
semicolon at end not required must
Typical usage Precondition iteration Postcondition iteration, input validation

The do-while loop is often used in situations where you want to be sure that the loop fragment is executed at least once, for example, when validating user input.

Switch

A switch is a control structure that compares the value of a variable with several constant values. It is essentially a more elegant and often more transparent alternative to structures consisting of several if-else if statements. Of course, you can use both in many cases, it just means less coding in many cases, which is also a source of fewer errors.

The basic syntax is:

switch (variable) {
    case value1:
        // code
        break;
    case value2:
        // code
        break;
    default:
        // code
        break;
}

After each branch (case) there is usually a default branch for unhandled values, but this is optional. This is often where some kind of default operation or error is thrown.

The switch structure works only with the following types (which may be placed after the switch statement):

  • byte, short, char, int (integer types)
  • enum (enumeration type)
  • String (text type)
if (menuItem == 1) {
  System.out.println("New game");
} else if (menuItem == 2) {
  System.out.println("Loading");
} else if (menuItem == 3) {
  System.out.println("Options");
} else {
  System.out.println("Exit");
}
switch (menuItem) {
    case 1:
        System.out.println("New game");
        break;
    case 2:
        System.out.println("Loading");
        break;
    case 3:
        System.out.println("Options");
        break;
    default:
        System.out.println("Exit");
        break;
}

The use of break can be crucial, since the evaluation can fall-through after the comparison.

int month = 8;
switch (month) {
    case 12:
    case 1:
    case 2:
        System.out.println("Winter");
        break;
    case 3:
    case 4:
    case 5:
        System.out.println("Spring");
        break;
    default:
        System.out.println("Other season");
}

As you can see, if the month takes any of the values 12, 1, 2, "Winter" is printed to the default output.

public class WeeklyMenu {
   public static void main(String[] args) {
       int day = 3; // Wednesday

       System.out.print("Today's menu: ");
       switch (day) {
           case 1:
               System.out.println("Meat soup and stir-fry");
               break;
           case 2:
               System.out.println("Fruit soup and stew");
               break;
           case 3:
               System.out.println("Goulash soup and pancakes");
               break;
           case 4:
               System.out.println("Vegetable soup and fried fish fillet");
               break;
           case 5:
               System.out.println("Beans goulash and cottage cheese");
               break;
           case 6:
           case 7:
               System.out.println("Weekend menu: Jókai bean soup and Tomato cabbage");
               break;
           default:
               System.out.println("Invalid day!");
               break;
       }
   }
}

Summary: Java vs Python

Feature Python Java
Block Notation Indentation Brackets {}
End of statement Line break Punctuation ;
If syntax if posed: if (posed) {
Else if elif posed: else if (posed) {
For loop for element in list: for (int i = 0; i < n; i++) {
While loop while condition: while (condition) {
Increment/decrement x += 1, x -= 1 x++, x--, x += 1, x -= 1
Compare ==, != .equals() for strings, == for primitive types
Logical operators and, or, not &&, ||, !
Remarks # or '''' // or /* */
String formatting f "x = {x}" String.format("x = %d", x) or "x = " + x `
null value None null
True/False True, False true, false

Read from default input

The following shows how to read a text or number from the default input. The purpose is to allow the reader to start creating interactive applications. It is not our intention to go into all the details, the details will be explained in a [later][file handling] exercise.

To use it, you first need to import the Scanner class from the java.util package. By default, it reads from the standard input (keyboard), which is indicated by the System.in parameter when it is created: Scanner sc = new Scanner(System.in);.

The Scanner class provides several methods for scanning different types of data:

  • nextLine(): reads an entire line as a String
  • next(): read the next word (up to whitespace) as String
  • nextInt(): reads an integer
  • nextDouble(): reads a floating point number
  • nextBoolean(): reads a logical value
import java.util.Scanner;

public class Reading {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Hello! What's your name?");
        String name = sc.nextLine();
        System.out.println("Hello " + name + "! How old are you?");
        int age = sc.nextInt();
        System.out.println("Hello " + name + ", who " + age + " years old.");
    }
}

Online development tools

Nowadays there are many online development tools to choose from, offering different options and features. They can be useful if you are a guest or sitting in front of a computer where you don't have Java and can't install it (e.g. you don't have administrator privileges), or if you want to test a code quickly, even from a tablet or phone. Some online development environments to choose from are IdeOne, TutorialsPoint Java compiler, CodeChef, Browxy, JDoodle. However, they are not recommended for everyday use at home, as these tools may have several limitations (e.g. heavy/unfriendly debugging).

Videos

Tasks

  1. Write a program that prints an arbitrary text 100 times, and the number of times it has printed the text.

  2. Ask for an age and indicate whether the person is a minor, an adult or a pensioner (0-18, 19-65, 65+) Tip: Use if-else structure, pay attention to intervals.

  3. ask for two numbers and an operation sign (+,-,*,/), then perform the operation. *Tip: Use a switch structure to handle operations.

  4. Write out the multiplication table from 1 to 10, nicely formatted.

  5. Ask for a password over and over until it matches the super-secure "password123". *Tip: Use a do-while loop and String comparison.

  6. Ask for a text and count the vowels in it. Tip: Use String methods and for cycles.

  7. Write out the numbers from 1 to 100, but write "Fizz" for multiples of 3 and "Buzz" for multiples of 5.

  8. Ask for 7 daily maximum temperatures and calculate the average.

  9. Ask the user for numbers until they enter 0. Count the even and odd numbers.

  10. Write a program that asks for the user's PIN. The user has 3 attempts to enter the correct PIN (1234). *Tip: Use for cycle and interrupt. Write out a joke when entering the correct password.

  11. Write out all the Armstrong numbers between 1 and 1000 (A number is an Armstrong number if the sum of the powers of the digits of its digits is equal to the number itself, e.g. 153 = 1^3 + 5^3 + 3^3).

  12. Create a simple bank transaction simulator where the user can deposit, withdraw money, retrieve balance. Create a log of all transactions (output to default error output).

Tasks (with automatic evaluation)

The texts and outline of the tasks are available here: HaziFeladatUres.java. The functions' body must be created! Testing of the solution is automatic, by compiling and running the file you can do it on any computer, even without internet!

  1. Create a static function called beinglazy. The function is given two parameters: whether it is a weekday and whether it is a holiday. You can be lazy in the morning if it is a weekend or if you are on vacation.
  2. Create a static function called lastdigitequality. The function expects two numbers. Return true if the last digits of the numbers are the same.
  3. Create a static function named lastdigitequalityN. The function expects three numbers (a, b, n). Return true if the last n digits of the first two numbers are equal (the last parameter 3).
  4. Create a static function called month' that expects one number. The function returns the given month in text (without accents) if the given number is between 1 and 12. In all other cases, it returns with the textunknown'!
  5. Create a static function called primes that waits for a number. The function returns the number of primes up to the given number (including the number given as a parameter).

Java API

Detailed description of javadoc