Lab01 Variables and Strings
Lab01 Variables and Strings
Lab #01
Contents
• Java language & programs
• Variable in Java
• String in Java
2
Java Language
• Java is an Object Oriented Programming language (OOP)
– Objects can perform actions
– Objects are affected by the actions of other objects
– The actions of Objects are known as methods
– Same types of Objects are said to be in the same Class
• Java Applications
– Java classes with a main method
3
Identifiers
• Identifiers are names for variables, classes, etc.
• Must not start with a digit, all the characters must be letters,
digits or the underscore symbol
• Good ones are compact, but indicate what they stand for
– radius, width, height, length
• Bad ones are either too long
– theRadiusOfTheCircle
– theWidthOfTheBoxThatIsBeingUsed
– the_width_of_the_box_that_is_being_used
• Or too short
– a, b, c, d, e
• Good identifiers will help understand your program!
4
Java Language (Contd)
5
Keywords
• Some words are reserved, and can’t be used as identifiers
6
Variables
• We’ve seen variables before in math
– y = mx + b
– Here y, m, x, and b can hold any value
• To store things in a computer program, we also use variables
• Example: 5
x
– int x = 5;
– This defines/declares an integer variable with value 5
• The variable is x
• The type is int
7
Variables (Contd)
• An integer variable can only hold integers
– In other words, it can’t hold 4.3
– d = 4.3;
• The variable is d
• The type is double
8
Variables (Contd)
• Assignment operator =
– Allows the variable to be updated
target = expression;
• Consider
– int j = 11;
– j = 1985;
9
Primitive variable assignment
• Consider
1
a
int aSquared = a * a; 5
a = 5;
a
• Consider b
10
– int b = 10; c
6
int c = b – 4;
10
Operators +=, -=, *=, ++, --
15
int x = 15; x
20
x += 5; x = x + 5; x
10
x -= 10; x = x - 10; x
x *= 5; x = x * 5; x 50
x++; x = x + 1; x 51
x--; x = x - 1; x
50
11
Increment/Decrement Operations
• You can do a pre-increment, or a post-increment
Pre Post
++x; x++;
--x; x--;
• Difference?
12
Printing Variables
• To print a variable to the screen, put it in a
System.out.println() statement:
– int x = 5;
– System.out.println(“The value of x is “ + x);
• Important points:
– Strings are enclosed in double quotes
– If there are multiple parts to be printed, they are separated by a plus sign.
This will automatically concatenate the parts.
13
Variables must be declared before use
14
You can only declare variables once
15
Variable Initialization
• Consider the following code:
– int x;
– System.out.println(x);
• What happens?
• Error message:
– variable x might not have been initialized
16
Primitive variable types
• Java has 8 primitive types:
– float
floating point numbers
– double
– boolean two values: true and false
– char a single character
– byte
– short
integer numbers
– int
– long
17
Primitive real (floating-point) types
• A float takes up 4 bytes of space
– Has 6 decimal places of accuracy: 3.14159
18
Primitive integer types
-215= 215-1=
short 2
-32,768 32,767
-263=-9,223,372,036, 263-1=9,223,372,036,
long 8
854,775,808 854,775,807
19
Type Casting
• Consider the code. Is it possible to assign the value of
a variable of one type to
a variable of another type?
• Yes
– You can assign the value of any type to that of another type that
is lower in the following list:
– byte < short < int < long < float < double
20
Primitive Boolean type
• The boolean type has only two values:
– true
– false
21
Constants
• Consider the following:
– final int x = 5;
• The value of x can NEVER be changed!
– The value assigned to it is “final”
22
Expressions
• What is the value used to initialize expression
– int expression = 4 + 2 * 5;
23
Question on expressions
24
Java operators
• The following are the common operators for ints:
– +-/*%
– Division /
• 6 / 2 yields 3
• 7 / 2 yields 3, not 3.5
• Because everything is an int, the answer is an int
– Modulus is %
• Returns the remainder
• 7 % 2 yields 1
• 6 % 2 yields 0
• Floats and doubles use the same first four operators
– +-/*
– 7.0 / 2.0 yields 3.5
– 7.0 / 2 yields 3.5
– 7 / 2.0 yields 3.5
– 7 / 2 yields 3
25
Java operators (Contd)
• Booleans have their own operators
– && is AND
• Only true when both operands are true
• true && true yields true
• false && true yields false
– || is OR
• True when either of the operands (or both) are true
• true || false yields true
• false || false yields false
– ! is NOT
• Changes the value
• !true yields false
• !false yields true
26
Self-Test (1)
❖ 프로젝트 명: Project01_1
❖ git commit -m “Project01_1”
27
Self-Test (1)
• Git을 이용한 Self-Test 수행 과정
1. Self-Test의 Template이 저장되어 있는 Template 프로젝트 Clone
2. Eclipse를 통해 Template 프로젝트 Import
3. Self-Test 코드 작성
4. Eclipse를 통해 작성한 프로젝트 Export
5. 각자 학번에 해당하는 프로젝트 Clone
6. Clone한 프로젝트를 통해 Git에 작성한 Export한 프로젝트 업로드
28
Self-Test (1)
-hconnect 접속 후
Template 프로젝트
클릭.
29
Self-Test (1)
30
Self-Test (1)
• Git 사용자 설정하기
– user.name은 학번
– user.email은 GitLab에 등록한 email (기본값: 학번 +
@hanyang.ac.kr ))
31
Self-Test (1)
• Template 클론하기.
.
32
Self-Test (1)
• git clone을 할 때 요구하는 Username은 학번, Password
는 GitLab webpage에서 설정한 password로 입력.
(단, 비밀번호를 주의해서 칠 것)
33
Self-Test (1)
• Template 클론하기.
34
Self-Test (1)
클릭
35
Self-Test (1)
• 이클립스에서 Import
36
Self-Test (1)
• 이클립스에서 Import
37
Self-Test (1)
3. Self-Test 코드 작성
• counter 와 totalDistance 2개의 변수를 선언할 것
• counter는 int type이며 3으로 초기화 되고,
totalDistance는 int type이며 15로 초기화 된다.
• quotient와 remainder 2개의 변수를 int type으로 선언할 것
• quotient은 totalDistance를 counter로 나눴을 때의 몫
remainder는 totalDistance를 counter로 나눴을 때의 나머지
• 정상 출력 결과
38
Self-Test (1)
4. Eclipse를 통해 작성한 프로젝트 Export
– 업로드하고자 하는 프로젝트
오른쪽 마우스 버튼
– Export 클릭
39
Self-Test (1)
40
Self-Test (1)
41
Self-Test (1)
42
Self-Test (1)
5. 각자 학번에 해당하는 프로젝트 Clone
• 생성되어 있는 자신의 Git repository clone 받기
43
Self-Test (1)
6. 한 프로젝트를 통해 Git에 작성한 Export한 프로젝트
업로드
• Clone받은 폴더로 이동 (처음에는 텅 빈 디렉토리)
$ cd YEAR_ITE0000_20XXXXXXXX
$ git status
44
Self-Test (1)
• 현재 디렉토리에 있는 모든 추가/수정된 파일들을 Stage 영역으로 이동
(test.c가 git에 의해 관리됨)
$ git add .
45
Self-Test (1)
• git push를 통해 Remote로 전송된 파일은 GitLab webpage에서 확인 가능하다
46
The String Class
• The String class is used to store and process strings
of characters
– A string is a sequence of characters gathered together, like the
word “Hello”, or the phrase “practice makes perfect”
– String creation:
• String s = “Java is fun.”;
• String s = new String(“Java is fun.”);
47
Working with Strings
• A convenience is in String concatenation:
– String a = “hello “;
String b = “world”;
String c; c
Hello World
c = a + b;
48
Working with Strings (Contd)
• Take the following example, where we are concatenating a String
a with an int i:
– String a = “Ten “;
int i = 4;
String c; Ten 4
c
c = a + i;
49
Working with Strings (Contd)
• Anytime you concatenate a String with another type,
the other type is first converted into a String and then
the two are concatenated. Really, this is done using
method toString()which every object inherits from
Object
– c = a + i; // c = a + i.toString();
50
Working with Strings (Contd)
– String a = “”
int b = 2;
int c = 3;
a = b + c;
51
Sub-Strings (1)
• You can extract a substring from a larger String object
with the substring()method of class String.
The first argument 0, is the 1st
character of the substring that
– String greet = “Howdy”; you do want to copy.
String s = greet.substring(0, 4);
Howdy
The 4 is the 1st character that
you don’t want to copy.
0 1 2 3 4
52
Sub-Strings (2)
• Consider
• What is output?
– Month is August.
53
Replacing Substrings
• This returns a string with the specified substrings
replaced
n = b.replace(‘h’, ‘H’);
54
Some more methods
55
Some more methods (Contd)
56
Some more methods (Contd)
57
String method examples
// index 012345678901
String s1 = “Stuart Reges”;
String s2 = “Marty Stepp”;
System.out.println(s1.length()); // 12
System.out.println(s1.indexOf("e")); // 8
System.out.println(s1.substring(7, 10)); // “Reg”
String s3 = s2.substring(1, 7);
System.out.println(s3.toLowerCase()); // “arty s”
58
String method examples (Contd)
59
Console Output
• Output to the console can be performed using the
System.out.println(<arguments>)
60
Print vs. Println
• If the print method is used, then the cursor is not
moved to a newline.
61
Print vs. Println (Contd)
• If the println method is used then the cursor is
moved to a new line
62
Formatting Output
63
Formatted specifiers
64
Formatting Output (Contd)
65
Console Input
• It is just as important to input information into your
programs as it is to output information.
66
Console Input (Contd)
• Java allows for keyboard input using the Scanner class.
• Scanner is a part of the java.util package
• Before you can use the Scanner class you must first import that
package.
67
Importing Packages
• Packages are collections of “pre-compiled” classes that can be
utilized.
• We must import the package containing the class we would like
to use before we can use that class.
– This is done by using the keyword import and the package name at the
start of you code.
68
Console Input (Contd)
• To use the Scanner within you applications you must import the
Scanner class as follows
– import java.util.Scanner;
69
Console Input (Contd)
• The Scanner object provides us with various methods for
reading input.
70
Console Input (Contd)
• int intValue = keyboard.nextInt();
• double dValue = keyboard.nextDouble();
Reads one integer or double value.
Each number separated by a whitespace is
considered different.
71
Console Input (Contd)
• NextLine()
– This method reads the remaining strings up to the end of the line and
discards the eol (end of line) character.
72
Scanner Class
• It is possible to change the delimiters used by the scanner class
• This changes the delimiters from being whitespaces to the user-
specified value
– Scanner keyboard2 = new Scanner(System.in);
– Keyboard2.useDelimiter("##");
73
Comments
• Double slashes ( //) are used in the Java programming language,
and tell the compiler to treat everything from the slashes to the
end of the line as text.
• Instead of double slashes, you can use C-style comments ( /* */)
to enclose one or more lines of code to be treated as text.
• Comments are ignored by the compiler but are useful to other
programmers
74
Self-Test (2)
❖ 프로젝트 명: Project01_2
❖ git commit -m “Project01_2”
75
Self-Test (2)
• 정상 출력 결과
76