SlideShare a Scribd company logo
1 of 108
Download to read offline
1
2
3
4
SEMESTRAL PLANS
WEEKLY PLANS
•
•
•
•
•
• • ✓
✓
✓
✓
•
•
• • •
•
✓
✓
✓
✓
•
•
•
•
•
•
•
• • ✓
✓
✓
✓
• • • • ✓
✓
•
•
• • ✓
✓
✓
•
•
•
• • • ✓
✓
✓
✓
• • • • ✓
•
•
• ✓
✓
✓
•
•
• •
•
•
•
✓
✓
✓
✓
• • • • ✓
•
•
•
•
•
•
✓
✓
✓
•
•
•
•
•
•
• •
•
✓
✓
✓
✓
• • • • ✓
✓
•
• •
•
• ✓
✓
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Part 1.
public class Exercise1
{
public static void main(String[] args)
{
System.out.println("Correct!");
}
}
Part 2. (Total: 17 items)
Class cell phone Object
brand
model
LCD size
weight
dimensions/size
talk time
battery standby time
Nokia
Nokia n70
176 x 208 pixels
125 grams
109 x 53 x 24 mm
3.5 hours
11 days
Send_Message Call
Take_Picture Record_Video
•
•
•
•
•
•
•
•
•
•
•
System.out.print();
System.out.println();
printWelcome()
public class Exercise2
{
public static void mail(String[] args)
{
System.out.print("+++++++++");
System.out.println("+++++++++");
System.out;println("++ ++")'
System.out.println("++ ++");
System.out.println("+++++++++")>
System.oul.printtn("+++++++++");
}
}
System.out.println() System.out.print()
System.out.print()
System.out.println()
public class Exercise2
{
public static void main(String[] args)
{
System.out.println("+++++++++");
System.out.println("+++++++++");
System.out.println("++ ++");
System.out.println("++ ++");
System.out.println("+++++++++");
System.out.println("+++++++++");
}
}
public class Lesson2
{
public static void main(String[] args)
{
System.out.println("The quick brown fox jumped over
the");
System.out.println("lazy dog and ran through the
forest.");
System.out.println(" ");
System.out.println(" ___ /");
System.out.println(" ^ ^ ");
System.out.println("  o / ");
System.out.println("Fox");
}
}
System.out.print()
System.out.println("HelloEveryone!!!");
"Hello Everyone!!!" ""Hello Everyone!!!""
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
** *** ********** ** * **
** *** ** ** ** *** **
** *** ** ** ** ** ** **
** *** ** ** ** ** ** **
***** ** ** ** ** ** **
** *** ** ** ** ** ** **
** *** ** ** ** ** ** **
** *** ** ** *** ***
** *** ********** * *
•
•
•
•
•
•
•
•
•
public class Lesson3
{
public static void main(String[] args)
{
final double d = 10.8;
final boolean b = false;
final String s1 = "quick brown fox";
final String s2 = "slow yellow fox";
final int i = 4;
System.out.println(d);
System.out.println(b);
System.out.println(s1 + " and " + s2);
System.out.println(i);
System.out.println((int)d - i);
}
}
public class Exercise3
{
public static void main(String[] args)
{
final double d = 5.5;
final String s1 = "tekki";
final int i = 4;
System.out.println(d);
System.out.println(s1 + " is cool!");
System.out.println(i);
System.out.println((int)d - i);
}
}
Average = (int)((Quiz_1+Quiz_2)/2); //explicit casting
int
System.out.println((int)d);
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
public class Exercise4
{
public static void main(String[] args)
{
final int A = 1, B = 0;
System.out.print(A);
System.out.print(A);
System.out.print(A);
System.out.print(A);
System.out.print(A);
System.out.print(A);
System.out.println(A);
System.out.print(A);
System.out.print(" ");
System.out.println(A);
System.out.print(A);
System.out.print(" ");
System.out.print(B);
System.out.print(" ");
System.out.print(B);
System.out.print(" ");
System.out.println(A);
System.out.print(A);
System.out.print(" ");
System.out.println(A);
System.out.print(A);
System.out.print(A);
System.out.print(A);
System.out.print(A);
System.out.print(A);
System.out.print(A);
System.out.println(A);
}
}
Part 2.
final int Y = 10, Z = 20;
System.out.println(Z/Y); //to print out “2”
System.out.println(Z+Y); //to print out “30”
System.out.println(Z-Y-Y); //to print out “0”
System.out.println(Z>Y); //to print out “true”
final int Y = 10, Z = 20;
System.out.println(2); //to print out “2”
System.out.println(30); //to print out “30”
System.out.println(0); //to print out “0”
System.out.println(true); //to print out “true”
public class Lesson4
{
public static void main(String[] args)
{
final int A = 3, B = 10;
System.out.println(A+A+A+B); // can be different
System.out.println(A-B);// can be different
System.out.println(A*B);// can be different
System.out.println(B/(A/A));// can be different
System.out.println(B%A);
System.out.println(A>B);// can be different
System.out.println(A<B);// can be different
}
}
Operator Description Example
= assigns values from right side operands to left side operands a=b
+= adds right operand to the left operand and assigns the result
to left
a+=b is same as a=a+b
-= subtracts the right operand from the left operand and assigns
the result to left operand
a-=b is same as a=a-b
*= multiplies the left operand by the right operand and assigns
the result to the left operand
a*=b is same as a=a*b
/= divides the left operand by the right operand and assigns the
result to the left operand
a/=b is same as a=a/b
%= calculates the modulus using two operands and assigns the
result to the left operand
a%=b is same as a=a%b
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
if-else
if-else
•
•
•
•
•
•
if switch
if switch
switch
public class Exercise5
{
public static void main(String[] args){
int x = 0;
System.out.println("Value is: " + x);
if(x%2 == 0)
{
System.out.println("Even!");
} else {
System.out.println("Out!");
}
}
}
public class Lesson5
{
public static void main(String[] args)
{
final double NUMBER = 24.18;
int flag = 0;
System.out.print("Initial value of flag is: ");
System.out.println(flag);
System.out.print("Initial value of NUMBER is: ");
System.out.println(NUMBER);
if(NUMBER > 0)
flag = 1;
else
if(NUMBER < 0)
flag = 2;
else
flag = 0;
switch(flag)
{
case 1: System.out.println("NUMBER is POSITIVE.");
break;
case 2: System.out.println("NUMBER is NEGATIVE.");
break;
case 0: System.out.println("NUMBER is ZERO!");
break;
}
System.out.print("Final value of flag is: ");
System.out.println(flag);
System.out.print("Final value of NUMBER is: ");
System.out.println(NUMBER);
}
}
1. if (a == 5) {
b += 3;
} else {
if (b > 4) {
c = 3;
}
2. if (a == 0) {
b = 1;
} else {
if (a == 1) {
b = 0;
} else {
b = -1;
}
}
3. if (a == 2) {
b = 10;
} else {
b = 35;
}
c = true;
1. switch (sides) {
case 3: polygon = "Triangle"; break;
case 4: polygon = "Quadrilateral"; break;
case 5: polygon = "Pentagon"; break;
case 6: polygon = "Hexagon"; break;
case 7: polygon = "Heptagon"; break;
case 8: polygon = "Octagon"; break;
case 9: polygon = "Nonagon"; break;
case 10: polygon = "Decagon"; break;
}
2. switch (answer) {
case ‘A’:
case ‘a’:
points+=100;
break;
case ‘B’:
case ‘b’:
points+=200;
break;
case ‘C’:
case ‘c’:
points-=100;
break;
default:
points -= 200;
}
•
•
•
•
•
•
•
for
while
do-while
for
while do-while
Are we
there
yet?
Condition
If no,
Repeat
If yes,
Halt Loop
Walk
public class Exercise6
{
public static void main(String[] args){
for(int i = 1; i < 10; i++){
System.out.print(i);
System.out.print(" ");
}
}
}
public class Lesson6
{ public static void main(String[] args)
{ int counter = 0;
for(counter = 1; counter<=20; counter++)
{ System.out.print(counter * 4+ " ");
if(counter%5==0)
System.out.println();
}
}
}
System.out.print(counter * 3+ " ");
if(counter%10==0)
System.out.println();
(int counter = 5; counter >=0 ;counter--) {
System.out.println(counter);
}
continue;
*******
******
*****
****
***
**
*
1******
12*****
123****
1234***
12345**
123456*
1234567
•
•
•
•
•
import java.io.*;
public class Exercise7
{
public static void main(String[] args)
{
BufferedReader dataIn=new BufferedReader(new
InputStreamReader(System.in));
int x = 0;
x = 10;
if(x%2==0)
System.out.println("Multiple of 2");
else
System.out.println("NOT a multiple of 2");
}
}
if(x%2==0)
System.out.println("Even number");
else
System.out.println("Odd number");
import java.io.*;
public class Lesson7
{
public static void main(String[] args)
{
BufferedReader dataIn=new BufferedReader(new
InputStreamReader(System.in));
int x = 0;
String Str_1;
System.out.print("Enter an integer value: ");
try
{
Str_1=dataIn.readLine();
x=Integer.parseInt(Str_1);
}
catch(Exception e)
{
System.out.println("Error reported");
}
if(x%5==0)
System.out.println("Number is a multiple of 5.");
else
System.out.println("Number is NOT a multiple of 5");
}
}
•
•
•
•
•
•
•
•
•
•
•
public class Exercise8
{
public static void main(String[] args){
AccessMe access = new AccessMe();
System.out.println(access.printme());
}
}
public class DRINKCONTAINER
{
private String BRAND, COLOR;
private final double CAPACITY = 10.0;
public double AMOUNTCONTAINED = 0.0;
public double getContents()
{
return AMOUNTCONTAINED;
}
public String getBrand()
{
return BRAND;
}
public String getColor()
{
return COLOR;
}
public void setBrand(String str)
{
BRAND = str;
}
public void setColor(String str)
{
COLOR = str;
}
public void throwContents()
{
AMOUNTCONTAINED = 0;
}
public void addContents(double x)
{
double temp;
temp = AMOUNTCONTAINED + x;
if(temp>=CAPACITY)
{
System.out.println("Maximum Capacity reached.");
AMOUNTCONTAINED = CAPACITY;
}
else
{
AMOUNTCONTAINED = temp;
}
}
}
BRAND and COLOR
as String
CAPACITY in liters
(final double) = 10.0
AMOUNTCONTAINE
D (a double that will
tell how many liters is
already inside a
DRINKCONTAINER
object) that should not
getContents() –
returns
AMOUNTCONTAIN
getColor() – returns
COLOR
setBrand(String str) –
sets the value of
BRAND equal to str
setColor(String str) –
sets the value of
COLOR equal to str
throwContent
s() – sets
AMOUNTCO
NTAINED to
0
addContents(double x) – adds
the argument passed to the
value of
AMOUNTCONTAINED. Again,
AMOUNTCONTAINED should
not exceed CAPACITY
getBrand() – returns
BRAND
public class Container_Controller {
public static void main(String[] args) {
DRINKCONTAINER dc= new DRINKCONTAINER();
System.out.println("Setting container color to
black."); dc.setColor("BLACK");
System.out.println("Setting brand to BRAND X.");
dc.setBrand("BRAND X");
System.out.println("Adding 9 liters of content..");
dc.addContents(9);
System.out.println("Adding 2 liters of content..");
dc.addContents(2);
System.out.println("Adding half liter of
content.."); dc.addContents(9);
System.out.println("CONTAINER DETAILS: ");
System.out.println("color: "+dc.getColor());
System.out.println("brand: "+dc.getBrand());
System.out.println("contents: "+dc.getContents() + "
liters");
System.out.println("Emptying container...");
dc.throwContents();
System.out.println("Container contents:
"+dc.getContents() + " liters");
}
}
dc.setColor("BLACK"); //
dc.setBrand("BRAND X"); //
dc.addContents(9); //
dc.addContents(2); //
// 10.0,
// 10.0 “spilt”
// 10.0
dc.addContents(9); //
•
•
•
•
•
public class Puppy{
public Puppy(){
}
public Puppy(String name){
// This constructor has one parameter, name.
}
}
•
•
•
•
•
•
int [] INTARRAY=new int [30];
int i;
double DOUBLEAVERAGE = 0.0;
double [] DOUBLEARRAY=new double [30];
INTARRAY
DOUBLEAVERAGE
DOUBLEARRAY
INTARRAY
DOUBLEAVERAGE
public class Exercise9
{
public static void main(String[] args)
{
int [] INTARRAY=new int [10];
int i;
for(i = 1;i<5;i++)
{
INTARRAY[i] = i * 2;
}
for(i = 1;i<5;i++)
{
System.out.println(INTARRAY[i]);
}
}
}
public class Lesson9
{
public static void main(String[] args)
{
int [] INTARRAY=new int [30];
int i;
double DOUBLEAVERAGE = 0.0;
double [] DOUBLEARRAY=new double [30];
for(i = 0;i<30;i++)
{
INTARRAY[i] = (i + 1) * 3;
DOUBLEAVERAGE = DOUBLEAVERAGE + INTARRAY[i];
}
DOUBLEAVERAGE/=30;
for(i = 0;i<30;i++)
{
DOUBLEARRAY[i] = INTARRAY[i] - DOUBLEAVERAGE;
}
System.out.println("MULTIPLE DIFFERENCE");
for(i = 0;i<30;i++)
{
System.out.println(INTARRAY[i]+"
"+DOUBLEARRAY[i]);
}
}
}
public class Array1
{
public Array1() { }
public static void main(String[] args){
String [] MySubjects = {"Math", "Science",
"English"};
String [] MyTeachers = {"Teacher1", "Teacher2",
"Teacher3"};
System.out.print("Here are my subjects: ");
System.out.print("My favorite subject is:
"+MySubjects[1]);
System.out.print("My favorite teacher is:
"+MyTeachers[2]);
}
}
dataType[] arrayRefVar;
dataType[] arrayRefVar[]
arrayRefVar = new dataType[arraySize]
dataType[] arrayREfVar = new dataType[arraySize]
dataType[] arrayRefVar = {value 0, value 1, …, valuen];
•
•
•
•
•
import javax.swing.*;
import java.awt.*;
public class Lesson10
{
public static void main(String[] args)
{
JFrame f1 = new JFrame("Joy de Jesus");
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
p1.setLayout(new GridLayout(2,2));
p2.setLayout(new GridLayout(2,2));
p3.setLayout(new GridLayout(2,2));
p4.setLayout(new GridLayout(2,2));
JButton b1 = new JButton("1");
p1.add(new JButton(" "));
p1.add(new JButton(" "));
p1.add(new JButton(" "));
p1.add(new JButton(" "));
p2.add(new JButton(" "));
p2.add(new JButton(" "));
p2.add(new JButton(" "));
p2.add(p1);
p3.add(new JButton(" "));
p3.add(new JButton(" "));
p3.add(new JButton(" "));
p3.add(p2);
p4.add(new JButton(" "));
p4.add(new JButton(" "));
p4.add(new JButton(" "));
p4.add(p3);
f1.setContentPane(p4);
f1.pack();
f1.show();
}
}
byte[] bytes = <any code generating byte array>
String content = new String(bytes);
readAllBytes() Files
byte[] bytes = Files.readAllBytes(<Path object>);
Path path = file.toPath();
File file = new File(uri);
String uri = resource.getFile();
ClassLoader
URL resource = classLoader.getResource(<string path and
file>);
ClasssLoader
getSystemClassLoader()
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
package app.book.vc;
import app.book.model.Book;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import app.book.service.*;
public class GuiBook implements ActionListener {
private Book book;
private JPanel labelPanel = new JPanel();
private JPanel contentPanel = new JPanel();
private JPanel buttonPanel = new JPanel();
private static final String PREVIOUS_PAGE_BUTTON_LABEL = "Previous Page";
private static final String NEXT_PAGE_BUTTON_LABEL = "Next Page";
private JLabel labelPage = new JLabel();
private JTextArea labelContent = new JTextArea();
// private JScrollPane scrollPaneContent = new JScrollPane();
private JButton btnPrevPage = new JButton(PREVIOUS_PAGE_BUTTON_LABEL);
private JButton btnNextPage = new JButton(NEXT_PAGE_BUTTON_LABEL);
private BookService bookService;
package app.book.vc;
public class BookController {
public static void main(String args[]){
new GuiBook();
}
}
public GuiBook() {
String[] authors = {"Mrs. Goose"};
book = new Book("Title", 4, authors);
labelPage.setText(String.valueOf(book.getCurrentPage()));
labelPanel.add(labelPage);
// contentPanel.add(scrollPaneContent);
contentPanel.setBackground(Color.white);
contentPanel.setSize(360, 500);
contentPanel.add(labelContent);
btnPrevPage.addActionListener(this);
btnNextPage.addActionListener(this);
buttonPanel.add(btnPrevPage);
buttonPanel.add(btnNextPage);
buttonPanel.setSize(360,60);
JFrame jFrame = new JFrame("");
jFrame.add(labelPanel, BorderLayout.NORTH);
jFrame.add(contentPanel, BorderLayout.CENTER);
jFrame.add(buttonPanel, BorderLayout.SOUTH);
jFrame.setSize(360,560);
jFrame.show();
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setResizable(false);
bookService = new BookServiceImpl();
labelContent.setText(bookService.turnPage(book.getCurrentPage()));
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals(NEXT_PAGE_BUTTON_LABEL)) {
book.turnPageForward();
}
if (e.getActionCommand().equals(PREVIOUS_PAGE_BUTTON_LABEL)) {
book.turnPageBackward();
}
labelPage.setText(String.valueOf(book.getCurrentPage()));
labelContent.setText(bookService.turnPage(book.getCurrentPage()));
}
}
package app.book.model;
public class Book extends ReadingMaterial {
private String[] authors;
public Book(String title, int totalPage, String authors[]) {
super(title, totalPage);
this.authors = authors;
}
public String[] getAuthors() {
return authors;
}
//override setCurrentPage, allow changing of page when selected page is
within bounds
public void setCurrentPage(int selectedPage) {
if (selectedPage > 0 && selectedPage <= getTotalPage()) {
super.setCurrentPage(selectedPage);
} else {
System.out.println("Invalid page " + selectedPage + ".");
}
}
}
package app.book.model;
public class ReadingMaterial {
private String title;
private int totalPage;
private int currentPage = 1;
public String getTitle() {
return title;
}
public int getTotalPage() {
return totalPage;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int turnPageForward(){
if (this.currentPage < this.totalPage) {
this.setCurrentPage(this.currentPage + 1);
}
return this.currentPage;
}
public int turnPageBackward() {
if (getCurrentPage() > 1) {
this.setCurrentPage(getCurrentPage() - 1);
}
return this.currentPage;
}
public int turnPageForward(int skipCount){
if (this.currentPage < this.totalPage) {
if (this.currentPage + skipCount > this.totalPage) {
this.setCurrentPage(this.totalPage);
}if (this.currentPage + skipCount < 1) {
this.setCurrentPage(1);
}
else {
this.setCurrentPage(this.currentPage + skipCount);
}
}
return this.currentPage;
}
public ReadingMaterial(String title, int totalPage) {
this.title = title;
this.totalPage = totalPage;
}
}
package app.book.service;
public interface BookService {
String turnPage(int page);
}
package app.book.service;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
public class BookServiceImpl implements BookService {
@Override
public String turnPage(int page) {
String content = "";
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
URL resource = classLoader.getResource("txt/" + page);
String uri = resource.getFile();
File file = new File(uri);
Path path = file.toPath();
try {
byte[] bytes = Files.readAllBytes(path);
content = new String(bytes);
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
}
1 1
1
2 2
2
3 3
3
4 4
4 4
pack() show()
o
o
o
o
o
o
o
Java_Programming_by_Example_6th_Edition.pdf
Java_Programming_by_Example_6th_Edition.pdf
Java_Programming_by_Example_6th_Edition.pdf
Java_Programming_by_Example_6th_Edition.pdf
Java_Programming_by_Example_6th_Edition.pdf

More Related Content

Similar to Java_Programming_by_Example_6th_Edition.pdf

Nested For Loops and Class Constants in Java
Nested For Loops and Class Constants in JavaNested For Loops and Class Constants in Java
Nested For Loops and Class Constants in JavaPokequesthero
 
Trace the following part of codes step by step- Show exactly what it w.docx
Trace the following part of codes step by step- Show exactly what it w.docxTrace the following part of codes step by step- Show exactly what it w.docx
Trace the following part of codes step by step- Show exactly what it w.docxgtameka
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)Chhom Karath
 
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 Problem1 java codeimport java.util.Scanner; Java code to pr.pdf Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Problem1 java codeimport java.util.Scanner; Java code to pr.pdfanupamfootwear
 
Sharable_Java_Python.pdf
Sharable_Java_Python.pdfSharable_Java_Python.pdf
Sharable_Java_Python.pdfICADCMLTPC
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
ch05-program-logic-indefinite-loops.ppt
ch05-program-logic-indefinite-loops.pptch05-program-logic-indefinite-loops.ppt
ch05-program-logic-indefinite-loops.pptMahyuddin8
 
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_17-Feb-2021_L8-...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_17-Feb-2021_L8-...WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_17-Feb-2021_L8-...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_17-Feb-2021_L8-...MaruMengesha
 
Computer java programs
Computer java programsComputer java programs
Computer java programsADITYA BHARTI
 
Getting started cpp full
Getting started cpp   fullGetting started cpp   full
Getting started cpp fullVõ Hòa
 
Java basic Programming.pptx
Java basic Programming.pptxJava basic Programming.pptx
Java basic Programming.pptxnuevodennis
 
Control statements
Control statementsControl statements
Control statementsraksharao
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Ayes Chinmay
 
Java AssignmentWrite a program using sortingsorting bubble,sele.pdf
Java AssignmentWrite a program using sortingsorting bubble,sele.pdfJava AssignmentWrite a program using sortingsorting bubble,sele.pdf
Java AssignmentWrite a program using sortingsorting bubble,sele.pdfeyewatchsystems
 
I am constantly getting errors and cannot figure this out. Please he.pdf
I am constantly getting errors and cannot figure this out. Please he.pdfI am constantly getting errors and cannot figure this out. Please he.pdf
I am constantly getting errors and cannot figure this out. Please he.pdfallystraders
 

Similar to Java_Programming_by_Example_6th_Edition.pdf (20)

Nested For Loops and Class Constants in Java
Nested For Loops and Class Constants in JavaNested For Loops and Class Constants in Java
Nested For Loops and Class Constants in Java
 
UNIT 2 LOOP CONTROL.pptx
UNIT 2 LOOP CONTROL.pptxUNIT 2 LOOP CONTROL.pptx
UNIT 2 LOOP CONTROL.pptx
 
Trace the following part of codes step by step- Show exactly what it w.docx
Trace the following part of codes step by step- Show exactly what it w.docxTrace the following part of codes step by step- Show exactly what it w.docx
Trace the following part of codes step by step- Show exactly what it w.docx
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
Introduction to Java Programming Part 2
Introduction to Java Programming Part 2Introduction to Java Programming Part 2
Introduction to Java Programming Part 2
 
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 Problem1 java codeimport java.util.Scanner; Java code to pr.pdf Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 
Parameters
ParametersParameters
Parameters
 
Sharable_Java_Python.pdf
Sharable_Java_Python.pdfSharable_Java_Python.pdf
Sharable_Java_Python.pdf
 
Comp102 lec 6
Comp102   lec 6Comp102   lec 6
Comp102 lec 6
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
ch05-program-logic-indefinite-loops.ppt
ch05-program-logic-indefinite-loops.pptch05-program-logic-indefinite-loops.ppt
ch05-program-logic-indefinite-loops.ppt
 
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_17-Feb-2021_L8-...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_17-Feb-2021_L8-...WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_17-Feb-2021_L8-...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_17-Feb-2021_L8-...
 
5 Rmi Print
5  Rmi Print5  Rmi Print
5 Rmi Print
 
Computer java programs
Computer java programsComputer java programs
Computer java programs
 
Getting started cpp full
Getting started cpp   fullGetting started cpp   full
Getting started cpp full
 
Java basic Programming.pptx
Java basic Programming.pptxJava basic Programming.pptx
Java basic Programming.pptx
 
Control statements
Control statementsControl statements
Control statements
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
 
Java AssignmentWrite a program using sortingsorting bubble,sele.pdf
Java AssignmentWrite a program using sortingsorting bubble,sele.pdfJava AssignmentWrite a program using sortingsorting bubble,sele.pdf
Java AssignmentWrite a program using sortingsorting bubble,sele.pdf
 
I am constantly getting errors and cannot figure this out. Please he.pdf
I am constantly getting errors and cannot figure this out. Please he.pdfI am constantly getting errors and cannot figure this out. Please he.pdf
I am constantly getting errors and cannot figure this out. Please he.pdf
 

Recently uploaded

What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 

Recently uploaded (20)

What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 

Java_Programming_by_Example_6th_Edition.pdf

  • 1. 1
  • 2. 2
  • 3. 3
  • 4. 4
  • 6.
  • 10. • • • • ✓ ✓ ✓ • • • • • • ✓ ✓ ✓ ✓ • • • • ✓
  • 14.
  • 16. Part 1. public class Exercise1 { public static void main(String[] args) { System.out.println("Correct!"); } }
  • 17. Part 2. (Total: 17 items) Class cell phone Object brand model LCD size weight dimensions/size talk time battery standby time Nokia Nokia n70 176 x 208 pixels 125 grams 109 x 53 x 24 mm 3.5 hours 11 days Send_Message Call Take_Picture Record_Video
  • 18.
  • 19.
  • 20.
  • 23. public class Exercise2 { public static void mail(String[] args) { System.out.print("+++++++++"); System.out.println("+++++++++"); System.out;println("++ ++")' System.out.println("++ ++"); System.out.println("+++++++++")> System.oul.printtn("+++++++++"); } }
  • 24. System.out.println() System.out.print() System.out.print() System.out.println() public class Exercise2 { public static void main(String[] args) { System.out.println("+++++++++"); System.out.println("+++++++++"); System.out.println("++ ++"); System.out.println("++ ++"); System.out.println("+++++++++"); System.out.println("+++++++++"); } } public class Lesson2 { public static void main(String[] args) { System.out.println("The quick brown fox jumped over the"); System.out.println("lazy dog and ran through the forest."); System.out.println(" "); System.out.println(" ___ /"); System.out.println(" ^ ^ "); System.out.println(" o / "); System.out.println("Fox"); } }
  • 26. public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); } }
  • 27.
  • 28. ** *** ********** ** * ** ** *** ** ** ** *** ** ** *** ** ** ** ** ** ** ** *** ** ** ** ** ** ** ***** ** ** ** ** ** ** ** *** ** ** ** ** ** ** ** *** ** ** ** ** ** ** ** *** ** ** *** *** ** *** ********** * *
  • 29.
  • 31.
  • 32. public class Lesson3 { public static void main(String[] args) { final double d = 10.8; final boolean b = false; final String s1 = "quick brown fox"; final String s2 = "slow yellow fox"; final int i = 4; System.out.println(d); System.out.println(b); System.out.println(s1 + " and " + s2); System.out.println(i); System.out.println((int)d - i); } } public class Exercise3 { public static void main(String[] args) { final double d = 5.5; final String s1 = "tekki"; final int i = 4; System.out.println(d); System.out.println(s1 + " is cool!"); System.out.println(i); System.out.println((int)d - i); } }
  • 33. Average = (int)((Quiz_1+Quiz_2)/2); //explicit casting int System.out.println((int)d);
  • 34.
  • 36.
  • 38.
  • 39. public class Exercise4 { public static void main(String[] args) { final int A = 1, B = 0; System.out.print(A); System.out.print(A); System.out.print(A); System.out.print(A); System.out.print(A); System.out.print(A); System.out.println(A); System.out.print(A); System.out.print(" "); System.out.println(A); System.out.print(A); System.out.print(" "); System.out.print(B); System.out.print(" "); System.out.print(B); System.out.print(" "); System.out.println(A); System.out.print(A); System.out.print(" "); System.out.println(A); System.out.print(A); System.out.print(A); System.out.print(A); System.out.print(A); System.out.print(A); System.out.print(A); System.out.println(A); } }
  • 40. Part 2. final int Y = 10, Z = 20; System.out.println(Z/Y); //to print out “2” System.out.println(Z+Y); //to print out “30” System.out.println(Z-Y-Y); //to print out “0” System.out.println(Z>Y); //to print out “true” final int Y = 10, Z = 20; System.out.println(2); //to print out “2” System.out.println(30); //to print out “30” System.out.println(0); //to print out “0” System.out.println(true); //to print out “true” public class Lesson4 { public static void main(String[] args) { final int A = 3, B = 10; System.out.println(A+A+A+B); // can be different System.out.println(A-B);// can be different System.out.println(A*B);// can be different System.out.println(B/(A/A));// can be different System.out.println(B%A); System.out.println(A>B);// can be different System.out.println(A<B);// can be different } }
  • 41.
  • 42. Operator Description Example = assigns values from right side operands to left side operands a=b += adds right operand to the left operand and assigns the result to left a+=b is same as a=a+b -= subtracts the right operand from the left operand and assigns the result to left operand a-=b is same as a=a-b *= multiplies the left operand by the right operand and assigns the result to the left operand a*=b is same as a=a*b /= divides the left operand by the right operand and assigns the result to the left operand a/=b is same as a=a/b %= calculates the modulus using two operands and assigns the result to the left operand a%=b is same as a=a%b Operator Description & Bitwise AND | Bitwise OR ^ Bitwise exclusive OR << left shift >> right shift
  • 45.
  • 46. public class Exercise5 { public static void main(String[] args){ int x = 0; System.out.println("Value is: " + x); if(x%2 == 0) { System.out.println("Even!"); } else { System.out.println("Out!"); } } }
  • 47. public class Lesson5 { public static void main(String[] args) { final double NUMBER = 24.18; int flag = 0; System.out.print("Initial value of flag is: "); System.out.println(flag); System.out.print("Initial value of NUMBER is: "); System.out.println(NUMBER); if(NUMBER > 0) flag = 1; else if(NUMBER < 0) flag = 2; else flag = 0; switch(flag) { case 1: System.out.println("NUMBER is POSITIVE."); break; case 2: System.out.println("NUMBER is NEGATIVE."); break; case 0: System.out.println("NUMBER is ZERO!"); break; } System.out.print("Final value of flag is: "); System.out.println(flag); System.out.print("Final value of NUMBER is: "); System.out.println(NUMBER); } }
  • 48. 1. if (a == 5) { b += 3; } else { if (b > 4) { c = 3; } 2. if (a == 0) { b = 1; } else { if (a == 1) { b = 0; } else { b = -1; } } 3. if (a == 2) { b = 10; } else { b = 35; } c = true; 1. switch (sides) { case 3: polygon = "Triangle"; break; case 4: polygon = "Quadrilateral"; break; case 5: polygon = "Pentagon"; break; case 6: polygon = "Hexagon"; break; case 7: polygon = "Heptagon"; break; case 8: polygon = "Octagon"; break; case 9: polygon = "Nonagon"; break; case 10: polygon = "Decagon"; break; }
  • 49. 2. switch (answer) { case ‘A’: case ‘a’: points+=100; break; case ‘B’: case ‘b’: points+=200; break; case ‘C’: case ‘c’: points-=100; break; default: points -= 200; }
  • 50.
  • 51.
  • 52.
  • 53.
  • 55. for while do-while Are we there yet? Condition If no, Repeat If yes, Halt Loop Walk
  • 56.
  • 57. public class Exercise6 { public static void main(String[] args){ for(int i = 1; i < 10; i++){ System.out.print(i); System.out.print(" "); } } } public class Lesson6 { public static void main(String[] args) { int counter = 0; for(counter = 1; counter<=20; counter++) { System.out.print(counter * 4+ " "); if(counter%5==0) System.out.println(); } } } System.out.print(counter * 3+ " "); if(counter%10==0) System.out.println();
  • 58. (int counter = 5; counter >=0 ;counter--) { System.out.println(counter); }
  • 62.
  • 64.
  • 65. import java.io.*; public class Exercise7 { public static void main(String[] args) { BufferedReader dataIn=new BufferedReader(new InputStreamReader(System.in)); int x = 0; x = 10; if(x%2==0) System.out.println("Multiple of 2"); else System.out.println("NOT a multiple of 2"); } }
  • 66. if(x%2==0) System.out.println("Even number"); else System.out.println("Odd number"); import java.io.*; public class Lesson7 { public static void main(String[] args) { BufferedReader dataIn=new BufferedReader(new InputStreamReader(System.in)); int x = 0; String Str_1; System.out.print("Enter an integer value: "); try { Str_1=dataIn.readLine(); x=Integer.parseInt(Str_1); } catch(Exception e) { System.out.println("Error reported"); } if(x%5==0) System.out.println("Number is a multiple of 5."); else System.out.println("Number is NOT a multiple of 5"); } }
  • 67.
  • 68.
  • 69.
  • 70.
  • 72.
  • 73. public class Exercise8 { public static void main(String[] args){ AccessMe access = new AccessMe(); System.out.println(access.printme()); } }
  • 74. public class DRINKCONTAINER { private String BRAND, COLOR; private final double CAPACITY = 10.0; public double AMOUNTCONTAINED = 0.0; public double getContents() { return AMOUNTCONTAINED; } public String getBrand() { return BRAND; } public String getColor() { return COLOR; } public void setBrand(String str) { BRAND = str; } public void setColor(String str) { COLOR = str; } public void throwContents() { AMOUNTCONTAINED = 0; } public void addContents(double x) { double temp; temp = AMOUNTCONTAINED + x; if(temp>=CAPACITY) { System.out.println("Maximum Capacity reached."); AMOUNTCONTAINED = CAPACITY; } else { AMOUNTCONTAINED = temp; } } } BRAND and COLOR as String CAPACITY in liters (final double) = 10.0 AMOUNTCONTAINE D (a double that will tell how many liters is already inside a DRINKCONTAINER object) that should not getContents() – returns AMOUNTCONTAIN getColor() – returns COLOR setBrand(String str) – sets the value of BRAND equal to str setColor(String str) – sets the value of COLOR equal to str throwContent s() – sets AMOUNTCO NTAINED to 0 addContents(double x) – adds the argument passed to the value of AMOUNTCONTAINED. Again, AMOUNTCONTAINED should not exceed CAPACITY getBrand() – returns BRAND
  • 75. public class Container_Controller { public static void main(String[] args) { DRINKCONTAINER dc= new DRINKCONTAINER(); System.out.println("Setting container color to black."); dc.setColor("BLACK"); System.out.println("Setting brand to BRAND X."); dc.setBrand("BRAND X"); System.out.println("Adding 9 liters of content.."); dc.addContents(9); System.out.println("Adding 2 liters of content.."); dc.addContents(2); System.out.println("Adding half liter of content.."); dc.addContents(9); System.out.println("CONTAINER DETAILS: "); System.out.println("color: "+dc.getColor()); System.out.println("brand: "+dc.getBrand()); System.out.println("contents: "+dc.getContents() + " liters"); System.out.println("Emptying container..."); dc.throwContents(); System.out.println("Container contents: "+dc.getContents() + " liters"); } } dc.setColor("BLACK"); // dc.setBrand("BRAND X"); // dc.addContents(9); //
  • 76. dc.addContents(2); // // 10.0, // 10.0 “spilt” // 10.0 dc.addContents(9); //
  • 77.
  • 78. • • • • • public class Puppy{ public Puppy(){ } public Puppy(String name){ // This constructor has one parameter, name. } }
  • 79.
  • 80.
  • 82. int [] INTARRAY=new int [30]; int i; double DOUBLEAVERAGE = 0.0; double [] DOUBLEARRAY=new double [30];
  • 84. public class Exercise9 { public static void main(String[] args) { int [] INTARRAY=new int [10]; int i; for(i = 1;i<5;i++) { INTARRAY[i] = i * 2; } for(i = 1;i<5;i++) { System.out.println(INTARRAY[i]); } } } public class Lesson9 { public static void main(String[] args) { int [] INTARRAY=new int [30]; int i; double DOUBLEAVERAGE = 0.0; double [] DOUBLEARRAY=new double [30]; for(i = 0;i<30;i++) { INTARRAY[i] = (i + 1) * 3; DOUBLEAVERAGE = DOUBLEAVERAGE + INTARRAY[i]; } DOUBLEAVERAGE/=30; for(i = 0;i<30;i++) { DOUBLEARRAY[i] = INTARRAY[i] - DOUBLEAVERAGE; } System.out.println("MULTIPLE DIFFERENCE"); for(i = 0;i<30;i++) { System.out.println(INTARRAY[i]+" "+DOUBLEARRAY[i]); } } }
  • 85. public class Array1 { public Array1() { } public static void main(String[] args){ String [] MySubjects = {"Math", "Science", "English"}; String [] MyTeachers = {"Teacher1", "Teacher2", "Teacher3"}; System.out.print("Here are my subjects: "); System.out.print("My favorite subject is: "+MySubjects[1]); System.out.print("My favorite teacher is: "+MyTeachers[2]); } }
  • 86.
  • 87. dataType[] arrayRefVar; dataType[] arrayRefVar[] arrayRefVar = new dataType[arraySize] dataType[] arrayREfVar = new dataType[arraySize] dataType[] arrayRefVar = {value 0, value 1, …, valuen];
  • 88.
  • 89.
  • 91.
  • 92. import javax.swing.*; import java.awt.*; public class Lesson10 { public static void main(String[] args) { JFrame f1 = new JFrame("Joy de Jesus"); JPanel p1 = new JPanel(); JPanel p2 = new JPanel(); JPanel p3 = new JPanel(); JPanel p4 = new JPanel(); p1.setLayout(new GridLayout(2,2)); p2.setLayout(new GridLayout(2,2)); p3.setLayout(new GridLayout(2,2)); p4.setLayout(new GridLayout(2,2)); JButton b1 = new JButton("1"); p1.add(new JButton(" ")); p1.add(new JButton(" ")); p1.add(new JButton(" "));
  • 93. p1.add(new JButton(" ")); p2.add(new JButton(" ")); p2.add(new JButton(" ")); p2.add(new JButton(" ")); p2.add(p1); p3.add(new JButton(" ")); p3.add(new JButton(" ")); p3.add(new JButton(" ")); p3.add(p2); p4.add(new JButton(" ")); p4.add(new JButton(" ")); p4.add(new JButton(" ")); p4.add(p3); f1.setContentPane(p4); f1.pack(); f1.show(); } } byte[] bytes = <any code generating byte array> String content = new String(bytes); readAllBytes() Files byte[] bytes = Files.readAllBytes(<Path object>);
  • 94. Path path = file.toPath(); File file = new File(uri); String uri = resource.getFile(); ClassLoader URL resource = classLoader.getResource(<string path and file>); ClasssLoader getSystemClassLoader() ClassLoader classLoader = ClassLoader.getSystemClassLoader();
  • 95.
  • 96. package app.book.vc; import app.book.model.Book; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import app.book.service.*; public class GuiBook implements ActionListener { private Book book; private JPanel labelPanel = new JPanel(); private JPanel contentPanel = new JPanel(); private JPanel buttonPanel = new JPanel(); private static final String PREVIOUS_PAGE_BUTTON_LABEL = "Previous Page"; private static final String NEXT_PAGE_BUTTON_LABEL = "Next Page"; private JLabel labelPage = new JLabel(); private JTextArea labelContent = new JTextArea(); // private JScrollPane scrollPaneContent = new JScrollPane(); private JButton btnPrevPage = new JButton(PREVIOUS_PAGE_BUTTON_LABEL); private JButton btnNextPage = new JButton(NEXT_PAGE_BUTTON_LABEL); private BookService bookService; package app.book.vc; public class BookController { public static void main(String args[]){ new GuiBook(); } }
  • 97. public GuiBook() { String[] authors = {"Mrs. Goose"}; book = new Book("Title", 4, authors); labelPage.setText(String.valueOf(book.getCurrentPage())); labelPanel.add(labelPage); // contentPanel.add(scrollPaneContent); contentPanel.setBackground(Color.white); contentPanel.setSize(360, 500); contentPanel.add(labelContent); btnPrevPage.addActionListener(this); btnNextPage.addActionListener(this); buttonPanel.add(btnPrevPage); buttonPanel.add(btnNextPage); buttonPanel.setSize(360,60); JFrame jFrame = new JFrame(""); jFrame.add(labelPanel, BorderLayout.NORTH); jFrame.add(contentPanel, BorderLayout.CENTER); jFrame.add(buttonPanel, BorderLayout.SOUTH); jFrame.setSize(360,560); jFrame.show(); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jFrame.setResizable(false); bookService = new BookServiceImpl(); labelContent.setText(bookService.turnPage(book.getCurrentPage())); } @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals(NEXT_PAGE_BUTTON_LABEL)) { book.turnPageForward(); } if (e.getActionCommand().equals(PREVIOUS_PAGE_BUTTON_LABEL)) { book.turnPageBackward(); } labelPage.setText(String.valueOf(book.getCurrentPage())); labelContent.setText(bookService.turnPage(book.getCurrentPage())); } }
  • 98. package app.book.model; public class Book extends ReadingMaterial { private String[] authors; public Book(String title, int totalPage, String authors[]) { super(title, totalPage); this.authors = authors; } public String[] getAuthors() { return authors; } //override setCurrentPage, allow changing of page when selected page is within bounds public void setCurrentPage(int selectedPage) { if (selectedPage > 0 && selectedPage <= getTotalPage()) { super.setCurrentPage(selectedPage); } else { System.out.println("Invalid page " + selectedPage + "."); } } } package app.book.model; public class ReadingMaterial { private String title; private int totalPage; private int currentPage = 1; public String getTitle() { return title; } public int getTotalPage() { return totalPage; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int turnPageForward(){ if (this.currentPage < this.totalPage) { this.setCurrentPage(this.currentPage + 1); } return this.currentPage; }
  • 99. public int turnPageBackward() { if (getCurrentPage() > 1) { this.setCurrentPage(getCurrentPage() - 1); } return this.currentPage; } public int turnPageForward(int skipCount){ if (this.currentPage < this.totalPage) { if (this.currentPage + skipCount > this.totalPage) { this.setCurrentPage(this.totalPage); }if (this.currentPage + skipCount < 1) { this.setCurrentPage(1); } else { this.setCurrentPage(this.currentPage + skipCount); } } return this.currentPage; } public ReadingMaterial(String title, int totalPage) { this.title = title; this.totalPage = totalPage; } } package app.book.service; public interface BookService { String turnPage(int page); }
  • 100. package app.book.service; import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; public class BookServiceImpl implements BookService { @Override public String turnPage(int page) { String content = ""; ClassLoader classLoader = ClassLoader.getSystemClassLoader(); URL resource = classLoader.getResource("txt/" + page); String uri = resource.getFile(); File file = new File(uri); Path path = file.toPath(); try { byte[] bytes = Files.readAllBytes(path); content = new String(bytes); } catch (IOException e) { e.printStackTrace(); } return content; } }
  • 101. 1 1 1 2 2 2 3 3 3 4 4 4 4 pack() show()
  • 102.